code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
assert isinstance(the_dict, dict), 'Geometry must be a dict' geom_type = the_dict.get('type', None) if geom_type == 'Point': return Point.from_dict(the_dict) elif geom_type == 'MultiPoint': return MultiPoint.from_dict(the_dict) elif geom_type == 'Polygon': return Polygon.from_dict(the_dict) elif geom_type == 'MultiPolygon': return MultiPolygon.from_dict(the_dict) else: raise ValueError('Unable to build a GeoType object: unrecognized geometry type')
def build(cls, the_dict)
Builds a `pyowm.utils.geo.Geometry` subtype based on the geoJSON geometry type specified on the input dictionary :param the_dict: a geoJSON compliant dict :return: a `pyowm.utils.geo.Geometry` subtype instance :raises `ValueError` if unable to the geometry type cannot be recognized
2.034335
1.885832
1.078747
if JSON_string is None: raise ParseResponseError('JSON data is None') d = json.loads(JSON_string) observation_parser = ObservationParser() if 'cod' in d: # Check if server returned errors: this check overcomes the lack of use # of HTTP error status codes by the OWM API 2.5. This mechanism is # supposed to be deprecated as soon as the API fully adopts HTTP for # conveying errors to the clients if d['cod'] == "200" or d['cod'] == 200: pass else: if d['cod'] == "404" or d['cod'] == 404: print("OWM API: data not found - response payload: " + json.dumps(d)) return None else: raise APIResponseError("OWM API: error - response payload: " + json.dumps(d), str(d['cod'])) # Handle the case when no results are found if 'count' in d and d['count'] == "0": return [] if 'cnt' in d and d['cnt'] == 0: return [] if 'list' in d: return [observation_parser.parse_JSON(json.dumps(item)) \ for item in d['list']] # no way out.. raise ParseResponseError(''.join([__name__, ': impossible to read JSON data']))
def parse_JSON(self, JSON_string)
Parses a list of *Observation* instances out of raw JSON data. Only certain properties of the data are used: if these properties are not found or cannot be parsed, an error is issued. :param JSON_string: a raw JSON string :type JSON_string: str :returns: a list of *Observation* instances or ``None`` if no data is available :raises: *ParseResponseError* if it is impossible to find or parse the data needed to build the result, *APIResponseError* if the OWM API returns a HTTP status error
4.728193
4.194371
1.127271
root_node = self._to_DOM() if xmlns: xmlutils.annotate_with_XMLNS(root_node, OZONE_XMLNS_PREFIX, OZONE_XMLNS_URL) return xmlutils.DOM_node_to_XML(root_node, xml_declaration)
def to_XML(self, xml_declaration=True, xmlns=True)
Dumps object fields to an XML-formatted string. The 'xml_declaration' switch enables printing of a leading standard XML line containing XML version and encoding. The 'xmlns' switch enables printing of qualified XMLNS prefixes. :param XML_declaration: if ``True`` (default) prints a leading XML declaration line :type XML_declaration: bool :param xmlns: if ``True`` (default) prints full XMLNS prefixes :type xmlns: bool :returns: an XML-formatted string
4.82655
6.179207
0.781095
root_node = ET.Element("ozone") reference_time_node = ET.SubElement(root_node, "reference_time") reference_time_node.text = str(self._reference_time) reception_time_node = ET.SubElement(root_node, "reception_time") reception_time_node.text = str(self._reception_time) interval_node = ET.SubElement(root_node, "interval") interval_node.text = str(self._interval) value_node = ET.SubElement(root_node, "value") value_node.text = str(self.du_value) root_node.append(self._location._to_DOM()) return root_node
def _to_DOM(self)
Dumps object data to a fully traversable DOM representation of the object. :returns: a ``xml.etree.Element`` object
2.07993
2.246357
0.925913
if JSON_string is None: raise parse_response_error.ParseResponseError('JSON data is None') d = json.loads(JSON_string) try: # -- reference time (strip away Z and T on ISO8601 format) t = d['time'].replace('Z', '+00').replace('T', ' ') reference_time = timeformatutils._ISO8601_to_UNIXtime(t) # -- reception time (now) reception_time = timeutils.now('unix') # -- location lon = float(d['location']['longitude']) lat = float(d['location']['latitude']) place = location.Location(None, lon, lat, None) # -- CO samples co_samples = d['data'] except KeyError: raise parse_response_error.ParseResponseError( ''.join([__name__, ': impossible to parse COIndex'])) return coindex.COIndex(reference_time, place, None, co_samples, reception_time)
def parse_JSON(self, JSON_string)
Parses an *COIndex* instance out of raw JSON data. Only certain properties of the data are used: if these properties are not found or cannot be parsed, an error is issued. :param JSON_string: a raw JSON string :type JSON_string: str :returns: an *COIndex* instance or ``None`` if no data is available :raises: *ParseResponseError* if it is impossible to find or parse the data needed to build the result, *APIResponseError* if the JSON string embeds an HTTP status error
5.295182
4.682672
1.130803
if JSON_string is None: raise parse_response_error.ParseResponseError('JSON data is None') d = json.loads(JSON_string) try: # -- reference time (strip away Z and T on ISO8601 format) t = d['time'].replace('Z', '+00').replace('T', ' ') reference_time = timeformatutils._ISO8601_to_UNIXtime(t) # -- reception time (now) reception_time = timeutils.now('unix') # -- location lon = float(d['location']['longitude']) lat = float(d['location']['latitude']) place = location.Location(None, lon, lat, None) # -- CO samples no2_samples = [dict(label=key, precision=d['data'][key]['precision'], value=d['data'][key]['value']) for key in d['data']] except KeyError: raise parse_response_error.ParseResponseError( ''.join([__name__, ': impossible to parse NO2Index'])) return no2index.NO2Index(reference_time, place, None, no2_samples, reception_time)
def parse_JSON(self, JSON_string)
Parses an *NO2Index* instance out of raw JSON data. Only certain properties of the data are used: if these properties are not found or cannot be parsed, an error is issued. :param JSON_string: a raw JSON string :type JSON_string: str :returns: an *NO2Index* instance or ``None`` if no data is available :raises: *ParseResponseError* if it is impossible to find or parse the data needed to build the result, *APIResponseError* if the JSON string embeds an HTTP status error
5.217656
4.418019
1.180995
if JSON_string is None: raise parse_response_error.ParseResponseError('JSON data is None') d = json.loads(JSON_string) try: # -- reference time (strip away Z and T on ISO8601 format) ref_t = d['time'].replace('Z', '+00').replace('T', ' ') reference_time = timeformatutils._ISO8601_to_UNIXtime(ref_t) # -- reception time (now) reception_time = timeutils.now('unix') # -- location lon = float(d['location']['longitude']) lat = float(d['location']['latitude']) place = location.Location(None, lon, lat, None) # -- ozone Dobson Units value du = d['data'] if du is not None: du_value = float(du) else: raise ValueError('No information about Ozon Dobson Units') except KeyError: raise parse_response_error.ParseResponseError( ''.join([__name__, ': impossible to parse UV Index'])) return ozone.Ozone(reference_time, place, None, du_value, reception_time)
def parse_JSON(self, JSON_string)
Parses an *Ozone* instance out of raw JSON data. Only certain properties of the data are used: if these properties are not found or cannot be parsed, an error is issued. :param JSON_string: a raw JSON string :type JSON_string: str :returns: an *Ozone* instance or ``None`` if no data is available :raises: *ParseResponseError* if it is impossible to find or parse the data needed to build the result, *APIResponseError* if the JSON string embeds an HTTP status error
5.305951
5.063566
1.047869
def outer_function(function): if name is None: _name = function.__name__ else: _name = name warning_msg = '"%s" is deprecated.' % _name if will_be is not None and on_version is not None: warning_msg += " It will be %s on version %s" % ( will_be, '.'.join(map(str, on_version))) @wraps(function) def inner_function(*args, **kwargs): warnings.warn(warning_msg, category=DeprecationWarning, stacklevel=2) return function(*args, **kwargs) return inner_function return outer_function
def deprecated(will_be=None, on_version=None, name=None)
Function decorator that warns about deprecation upon function invocation. :param will_be: str representing the target action on the deprecated function :param on_version: tuple representing a SW version :param name: name of the entity to be deprecated (useful when decorating __init__ methods so you can specify the deprecated class name) :return: callable
2.150448
2.181938
0.985568
assert geopolygon is not None assert isinstance(geopolygon, GeoPolygon) data = dict() data['geo_json'] = { "type": "Feature", "properties": {}, "geometry": geopolygon.as_dict() } if name is not None: data['name'] = name status, payload = self.http_client.post( POLYGONS_URI, params={'appid': self.API_key}, data=data, headers={'Content-Type': 'application/json'}) return Polygon.from_dict(payload)
def create_polygon(self, geopolygon, name=None)
Create a new polygon on the Agro API with the given parameters :param geopolygon: the geopolygon representing the new polygon :type geopolygon: `pyowm.utils.geo.Polygon` instance :param name: optional mnemonic name for the new polygon :type name: str :return: a `pyowm.agro10.polygon.Polygon` instance
2.95908
2.794384
1.058938
status, data = self.http_client.get_json( POLYGONS_URI, params={'appid': self.API_key}, headers={'Content-Type': 'application/json'}) return [Polygon.from_dict(item) for item in data]
def get_polygons(self)
Retrieves all of the user's polygons registered on the Agro API. :returns: list of `pyowm.agro10.polygon.Polygon` objects
5.325334
5.290187
1.006644
status, data = self.http_client.get_json( NAMED_POLYGON_URI % str(polygon_id), params={'appid': self.API_key}, headers={'Content-Type': 'application/json'}) return Polygon.from_dict(data)
def get_polygon(self, polygon_id)
Retrieves a named polygon registered on the Agro API. :param id: the ID of the polygon :type id: str :returns: a `pyowm.agro10.polygon.Polygon` object
5.496456
5.668529
0.969644
assert polygon.id is not None status, _ = self.http_client.put( NAMED_POLYGON_URI % str(polygon.id), params={'appid': self.API_key}, data=dict(name=polygon.name), headers={'Content-Type': 'application/json'})
def update_polygon(self, polygon)
Updates on the Agro API the Polygon identified by the ID of the provided polygon object. Currently this only changes the mnemonic name of the remote polygon :param polygon: the `pyowm.agro10.polygon.Polygon` object to be updated :type polygon: `pyowm.agro10.polygon.Polygon` instance :returns: `None` if update is successful, an exception otherwise
5.895801
5.348143
1.102401
assert polygon.id is not None status, _ = self.http_client.delete( NAMED_POLYGON_URI % str(polygon.id), params={'appid': self.API_key}, headers={'Content-Type': 'application/json'})
def delete_polygon(self, polygon)
Deletes on the Agro API the Polygon identified by the ID of the provided polygon object. :param polygon: the `pyowm.agro10.polygon.Polygon` object to be deleted :type polygon: `pyowm.agro10.polygon.Polygon` instance :returns: `None` if deletion is successful, an exception otherwise
6.377034
5.947934
1.072143
assert polygon is not None assert isinstance(polygon, Polygon) polyd = polygon.id status, data = self.http_client.get_json( SOIL_URI, params={'appid': self.API_key, 'polyid': polyd}, headers={'Content-Type': 'application/json'}) the_dict = dict() the_dict['reference_time'] = data['dt'] the_dict['surface_temp'] = data['t0'] the_dict['ten_cm_temp'] = data['t10'] the_dict['moisture'] = data['moisture'] the_dict['polygon_id'] = polyd return Soil.from_dict(the_dict)
def soil_data(self, polygon)
Retrieves the latest soil data on the specified polygon :param polygon: the reference polygon you want soil data for :type polygon: `pyowm.agro10.polygon.Polygon` instance :returns: a `pyowm.agro10.soil.Soil` instance
4.118539
3.707398
1.110897
if palette is not None: assert isinstance(palette, str) params = dict(paletteid=palette) else: palette = PaletteEnum.GREEN params = dict() # polygon PNG if isinstance(metaimage, MetaPNGImage): prepared_url = metaimage.url status, data = self.http_client.get_png( prepared_url, params=params) img = Image(data, metaimage.image_type) return SatelliteImage(metaimage, img, downloaded_on=timeutils.now(timeformat='unix'), palette=palette) # GeoTIF elif isinstance(metaimage, MetaGeoTiffImage): prepared_url = metaimage.url status, data = self.http_client.get_geotiff( prepared_url, params=params) img = Image(data, metaimage.image_type) return SatelliteImage(metaimage, img, downloaded_on=timeutils.now(timeformat='unix'), palette=palette) # tile PNG elif isinstance(metaimage, MetaTile): assert x is not None assert y is not None assert zoom is not None prepared_url = self._fill_url(metaimage.url, x, y, zoom) status, data = self.http_client.get_png( prepared_url, params=params) img = Image(data, metaimage.image_type) tile = Tile(x, y, zoom, None, img) return SatelliteImage(metaimage, tile, downloaded_on=timeutils.now(timeformat='unix'), palette=palette) else: raise ValueError("Cannot download: unsupported MetaImage subtype")
def download_satellite_image(self, metaimage, x=None, y=None, zoom=None, palette=None)
Downloads the satellite image described by the provided metadata. In case the satellite image is a tile, then tile coordinates and zoom must be provided. An optional palette ID can be provided, if supported by the downloaded preset (currently only NDVI is supported) :param metaimage: the satellite image's metadata, in the form of a `MetaImage` subtype instance :type metaimage: a `pyowm.agroapi10.imagery.MetaImage` subtype :param x: x tile coordinate (only needed in case you are downloading a tile image) :type x: int or `None` :param y: y tile coordinate (only needed in case you are downloading a tile image) :type y: int or `None` :param zoom: zoom level (only needed in case you are downloading a tile image) :type zoom: int or `None` :param palette: ID of the color palette of the downloaded images. Values are provided by `pyowm.agroapi10.enums.PaletteEnum` :type palette: str or `None` :return: a `pyowm.agroapi10.imagery.SatelliteImage` instance containing both image's metadata and data
2.496179
2.396438
1.04162
if metaimage.preset != PresetEnum.EVI and metaimage.preset != PresetEnum.NDVI: raise ValueError("Unsupported image preset: should be EVI or NDVI") if metaimage.stats_url is None: raise ValueError("URL for image statistics is not defined") status, data = self.http_client.get_json(metaimage.stats_url, params={}) return data
def stats_for_satellite_image(self, metaimage)
Retrieves statistics for the satellite image described by the provided metadata. This is currently only supported 'EVI' and 'NDVI' presets :param metaimage: the satellite image's metadata, in the form of a `MetaImage` subtype instance :type metaimage: a `pyowm.agroapi10.imagery.MetaImage` subtype :return: dict
4.543985
3.589152
1.266033
return json.dumps({"reference_time": self._reference_time, "location": json.loads(self._location.to_JSON()), "value": self._value, "reception_time": self._reception_time, })
def to_JSON(self)
Dumps object fields into a JSON formatted string :returns: the JSON string
3.959274
4.984851
0.794261
root_node = self._to_DOM() if xmlns: xmlutils.annotate_with_XMLNS(root_node, UVINDEX_XMLNS_PREFIX, UVINDEX_XMLNS_URL) return xmlutils.DOM_node_to_XML(root_node, xml_declaration)
def to_XML(self, xml_declaration=True, xmlns=True)
Dumps object fields to an XML-formatted string. The 'xml_declaration' switch enables printing of a leading standard XML line containing XML version and encoding. The 'xmlns' switch enables printing of qualified XMLNS prefixes. :param XML_declaration: if ``True`` (default) prints a leading XML declaration line :type XML_declaration: bool :param xmlns: if ``True`` (default) prints full XMLNS prefixes :type xmlns: bool :returns: an XML-formatted string
5.057864
6.350004
0.796514
root_node = ET.Element("uvindex") reference_time_node = ET.SubElement(root_node, "reference_time") reference_time_node.text = str(self._reference_time) reception_time_node = ET.SubElement(root_node, "reception_time") reception_time_node.text = str(self._reception_time) value_node = ET.SubElement(root_node, "value") value_node.text = str(self._value) root_node.append(self._location._to_DOM()) return root_node
def _to_DOM(self)
Dumps object data to a fully traversable DOM representation of the object. :returns: a ``xml.etree.Element`` object
1.954632
2.114187
0.924531
params = {'q': 'London,GB'} uri = http_client.HttpClient.to_url(OBSERVATION_URL, self._API_key, self._subscription_type) try: _1, _2 = self._wapi.cacheable_get_json(uri, params=params) return True except api_call_error.APICallTimeoutError: return False
def is_API_online(self)
Returns True if the OWM Weather API is currently online. A short timeout is used to determine API service availability. :returns: bool
10.425144
10.928813
0.953914
assert isinstance(name, str), "Value must be a string" encoded_name = name params = {'q': encoded_name, 'lang': self._language} uri = http_client.HttpClient.to_url(OBSERVATION_URL, self._API_key, self._subscription_type, self._use_ssl) _, json_data = self._wapi.cacheable_get_json(uri, params=params) return self._parsers['observation'].parse_JSON(json_data)
def weather_at_place(self, name)
Queries the OWM Weather API for the currently observed weather at the specified toponym (eg: "London,uk") :param name: the location's toponym :type name: str or unicode :returns: an *Observation* instance or ``None`` if no weather data is available :raises: *ParseResponseException* when OWM Weather API responses' data cannot be parsed or *APICallException* when OWM Weather API can not be reached
7.508002
6.935403
1.082562
geo.assert_is_lon(lon) geo.assert_is_lat(lat) params = {'lon': lon, 'lat': lat, 'lang': self._language} uri = http_client.HttpClient.to_url(OBSERVATION_URL, self._API_key, self._subscription_type, self._use_ssl) _, json_data = self._wapi.cacheable_get_json(uri, params=params) return self._parsers['observation'].parse_JSON(json_data)
def weather_at_coords(self, lat, lon)
Queries the OWM Weather API for the currently observed weather at the specified geographic (eg: 51.503614, -0.107331). :param lat: the location's latitude, must be between -90.0 and 90.0 :type lat: int/float :param lon: the location's longitude, must be between -180.0 and 180.0 :type lon: int/float :returns: an *Observation* instance or ``None`` if no weather data is available :raises: *ParseResponseException* when OWM Weather API responses' data cannot be parsed or *APICallException* when OWM Weather API can not be reached
6.584031
6.761913
0.973694
assert isinstance(zipcode, str), "Value must be a string" assert isinstance(country, str), "Value must be a string" encoded_zip = zipcode encoded_country = country zip_param = encoded_zip + ',' + encoded_country params = {'zip': zip_param, 'lang': self._language} uri = http_client.HttpClient.to_url(OBSERVATION_URL, self._API_key, self._subscription_type, self._use_ssl) _, json_data = self._wapi.cacheable_get_json(uri, params=params) return self._parsers['observation'].parse_JSON(json_data)
def weather_at_zip_code(self, zipcode, country)
Queries the OWM Weather API for the currently observed weather at the specified zip code and country code (eg: 2037, au). :param zip: the location's zip or postcode :type zip: string :param country: the location's country code :type country: string :returns: an *Observation* instance or ``None`` if no weather data is available :raises: *ParseResponseException* when OWM Weather API responses' data cannot be parsed or *APICallException* when OWM Weather API can not be reached
5.336524
5.017972
1.063482
assert type(id) is int, "'id' must be an int" if id < 0: raise ValueError("'id' value must be greater than 0") params = {'id': id, 'lang': self._language} uri = http_client.HttpClient.to_url(OBSERVATION_URL, self._API_key, self._subscription_type, self._use_ssl) _, json_data = self._wapi.cacheable_get_json(uri, params=params) return self._parsers['observation'].parse_JSON(json_data)
def weather_at_id(self, id)
Queries the OWM Weather API for the currently observed weather at the specified city ID (eg: 5128581) :param id: the location's city ID :type id: int :returns: an *Observation* instance or ``None`` if no weather data is available :raises: *ParseResponseException* when OWM Weather API responses' data cannot be parsed or *APICallException* when OWM Weather API can not be reached
5.94056
5.634264
1.054363
assert type(ids_list) is list, "'ids_list' must be a list of integers" for id in ids_list: assert type(id) is int, "'ids_list' must be a list of integers" if id < 0: raise ValueError("id values in 'ids_list' must be greater " "than 0") params = {'id': ','.join(list(map(str, ids_list))), 'lang': self._language} uri = http_client.HttpClient.to_url(GROUP_OBSERVATIONS_URL, self._API_key, self._subscription_type, self._use_ssl) _, json_data = self._wapi.cacheable_get_json(uri, params=params) return self._parsers['observation_list'].parse_JSON(json_data)
def weather_at_ids(self, ids_list)
Queries the OWM Weather API for the currently observed weathers at the specified city IDs (eg: [5128581,87182]) :param ids_list: the list of city IDs :type ids_list: list of int :returns: a list of *Observation* instances or an empty list if no weather data is available :raises: *ParseResponseException* when OWM Weather API responses' data cannot be parsed or *APICallException* when OWM Weather API can not be reached
4.188292
4.121456
1.016217
assert isinstance(pattern, str), "'pattern' must be a str" assert isinstance(searchtype, str), "'searchtype' must be a str" if searchtype != "accurate" and searchtype != "like": raise ValueError("'searchtype' value must be 'accurate' or 'like'") if limit is not None: assert isinstance(limit, int), "'limit' must be an int or None" if limit < 1: raise ValueError("'limit' must be None or greater than zero") params = {'q': pattern, 'type': searchtype, 'lang': self._language} if limit is not None: # fix for OWM 2.5 API bug! params['cnt'] = limit - 1 uri = http_client.HttpClient.to_url(FIND_OBSERVATIONS_URL, self._API_key, self._subscription_type, self._use_ssl) _, json_data = self._wapi.cacheable_get_json(uri, params=params) return self._parsers['observation_list'].parse_JSON(json_data)
def weather_at_places(self, pattern, searchtype, limit=None)
Queries the OWM Weather API for the currently observed weather in all the locations whose name is matching the specified text search parameters. A twofold search can be issued: *'accurate'* (exact matching) and *'like'* (matches names that are similar to the supplied pattern). :param pattern: the string pattern (not a regex) to be searched for the toponym :type pattern: str :param searchtype: the search mode to be used, must be *'accurate'* for an exact matching or *'like'* for a likelihood matching :type: searchtype: str :param limit: the maximum number of *Observation* items in the returned list (default is ``None``, which stands for any number of items) :param limit: int or ``None`` :returns: a list of *Observation* objects or ``None`` if no weather data is available :raises: *ParseResponseException* when OWM Weather API responses' data cannot be parsed, *APICallException* when OWM Weather API can not be reached, *ValueError* when bad value is supplied for the search type or the maximum number of items retrieved
3.711727
3.345969
1.109313
assert type(station_id) is int, "'station_id' must be an int" if station_id < 0: raise ValueError("'station_id' value must be greater than 0") params = {'id': station_id, 'lang': self._language} uri = http_client.HttpClient.to_url(STATION_URL, self._API_key, self._subscription_type, self._use_ssl) _, json_data = self._wapi.cacheable_get_json(uri, params=params) return self._parsers['observation'].parse_JSON(json_data)
def weather_at_station(self, station_id)
Queries the OWM Weather API for the weather currently observed by a specific meteostation (eg: 29584) :param station_id: the meteostation ID :type station_id: int :returns: an *Observation* instance or ``None`` if no weather data is available :raises: *ParseResponseException* when OWM Weather API responses' data cannot be parsed or *APICallException* when OWM Weather API can not be reached
5.309267
5.276494
1.006211
assert type(cluster) is bool, "'cluster' must be a bool" assert type(limit) in (int, type(None)), \ "'limit' must be an int or None" geo.assert_is_lon(lon_top_left) geo.assert_is_lon(lon_bottom_right) geo.assert_is_lat(lat_top_left) geo.assert_is_lat(lat_bottom_right) if limit is not None and limit < 1: raise ValueError("'limit' must be None or greater than zero") params = {'bbox': ','.join([str(lon_top_left), str(lat_top_left), str(lon_bottom_right), str(lat_bottom_right)]), 'cluster': 'yes' if cluster else 'no',} if limit is not None: params['cnt'] = limit uri = http_client.HttpClient.to_url(BBOX_STATION_URL, self._API_key, self._subscription_type, self._use_ssl) _, json_data = self._wapi.cacheable_get_json(uri, params=params) return self._parsers['observation_list'].parse_JSON(json_data)
def weather_at_stations_in_bbox(self, lat_top_left, lon_top_left, lat_bottom_right, lon_bottom_right, cluster=False, limit=None)
Queries the OWM Weather API for the weather currently observed by meteostations inside the bounding box of latitude/longitude coords. :param lat_top_left: latitude for top-left of bounding box, must be between -90.0 and 90.0 :type lat_top_left: int/float :param lon_top_left: longitude for top-left of bounding box must be between -180.0 and 180.0 :type lon_top_left: int/float :param lat_bottom_right: latitude for bottom-right of bounding box, must be between -90.0 and 90.0 :type lat_bottom_right: int/float :param lon_bottom_right: longitude for bottom-right of bounding box, must be between -180.0 and 180.0 :type lon_bottom_right: int/float :param cluster: use server clustering of points :type cluster: bool :param limit: the maximum number of *Observation* items in the returned list (default is ``None``, which stands for any number of items) :param limit: int or ``None`` :returns: a list of *Observation* objects or ``None`` if no weather data is available :raises: *ParseResponseException* when OWM Weather API responses' data cannot be parsed, *APICallException* when OWM Weather API can not be reached, *ValueError* when coordinates values are out of bounds or negative values are provided for limit
2.92282
2.981503
0.980318
geo.assert_is_lon(lon_left) geo.assert_is_lon(lon_right) geo.assert_is_lat(lat_bottom) geo.assert_is_lat(lat_top) assert type(zoom) is int, "'zoom' must be an int" if zoom <= 0: raise ValueError("'zoom' must greater than zero") assert type(cluster) is bool, "'cluster' must be a bool" params = {'bbox': ','.join([str(lon_left), str(lat_bottom), str(lon_right), str(lat_top), str(zoom)]), 'cluster': 'yes' if cluster else 'no'} uri = http_client.HttpClient.to_url(BBOX_CITY_URL, self._API_key, self._subscription_type, self._use_ssl) _, json_data = self._wapi.cacheable_get_json(uri, params=params) return self._parsers['observation_list'].parse_JSON(json_data)
def weather_at_places_in_bbox(self, lon_left, lat_bottom, lon_right, lat_top, zoom=10, cluster=False)
Queries the OWM Weather API for the weather currently observed by meteostations inside the bounding box of latitude/longitude coords. :param lat_top: latitude for top margin of bounding box, must be between -90.0 and 90.0 :type lat_top: int/float :param lon_left: longitude for left margin of bounding box must be between -180.0 and 180.0 :type lon_left: int/float :param lat_bottom: latitude for the bottom margin of bounding box, must be between -90.0 and 90.0 :type lat_bottom: int/float :param lon_right: longitude for the right margin of bounding box, must be between -180.0 and 180.0 :type lon_right: int/float :param zoom: zoom level (defaults to: 10) :type zoom: int :param cluster: use server clustering of points :type cluster: bool :returns: a list of *Observation* objects or ``None`` if no weather data is available :raises: *ParseResponseException* when OWM Weather API responses' data cannot be parsed, *APICallException* when OWM Weather API can not be reached, *ValueError* when coordinates values are out of bounds or negative values are provided for limit
3.278404
3.390528
0.96693
assert isinstance(name, str), "Value must be a string" encoded_name = name params = {'q': encoded_name, 'lang': self._language} uri = http_client.HttpClient.to_url(THREE_HOURS_FORECAST_URL, self._API_key, self._subscription_type, self._use_ssl) _, json_data = self._wapi.cacheable_get_json(uri, params=params) forecast = self._parsers['forecast'].parse_JSON(json_data) if forecast is not None: forecast.set_interval("3h") return forecaster.Forecaster(forecast) else: return None
def three_hours_forecast(self, name)
Queries the OWM Weather API for three hours weather forecast for the specified location (eg: "London,uk"). A *Forecaster* object is returned, containing a *Forecast* instance covering a global streak of five days: this instance encapsulates *Weather* objects, with a time interval of three hours one from each other :param name: the location's toponym :type name: str or unicode :returns: a *Forecaster* instance or ``None`` if forecast data is not available for the specified location :raises: *ParseResponseException* when OWM Weather API responses' data cannot be parsed, *APICallException* when OWM Weather API can not be reached
5.647812
5.506021
1.025752
geo.assert_is_lon(lon) geo.assert_is_lat(lat) params = {'lon': lon, 'lat': lat, 'lang': self._language} uri = http_client.HttpClient.to_url(THREE_HOURS_FORECAST_URL, self._API_key, self._subscription_type, self._use_ssl) _, json_data = self._wapi.cacheable_get_json(uri, params=params) forecast = self._parsers['forecast'].parse_JSON(json_data) if forecast is not None: forecast.set_interval("3h") return forecaster.Forecaster(forecast) else: return None
def three_hours_forecast_at_coords(self, lat, lon)
Queries the OWM Weather API for three hours weather forecast for the specified geographic coordinate (eg: latitude: 51.5073509, longitude: -0.1277583). A *Forecaster* object is returned, containing a *Forecast* instance covering a global streak of five days: this instance encapsulates *Weather* objects, with a time interval of three hours one from each other :param lat: location's latitude, must be between -90.0 and 90.0 :type lat: int/float :param lon: location's longitude, must be between -180.0 and 180.0 :type lon: int/float :returns: a *Forecaster* instance or ``None`` if forecast data is not available for the specified location :raises: *ParseResponseException* when OWM Weather API responses' data cannot be parsed, *APICallException* when OWM Weather API can not be reached
5.26476
5.260351
1.000838
assert type(id) is int, "'id' must be an int" if id < 0: raise ValueError("'id' value must be greater than 0") params = {'id': id, 'lang': self._language} uri = http_client.HttpClient.to_url(THREE_HOURS_FORECAST_URL, self._API_key, self._subscription_type, self._use_ssl) _, json_data = self._wapi.cacheable_get_json(uri, params=params) forecast = self._parsers['forecast'].parse_JSON(json_data) if forecast is not None: forecast.set_interval("3h") return forecaster.Forecaster(forecast) else: return None
def three_hours_forecast_at_id(self, id)
Queries the OWM Weather API for three hours weather forecast for the specified city ID (eg: 5128581). A *Forecaster* object is returned, containing a *Forecast* instance covering a global streak of five days: this instance encapsulates *Weather* objects, with a time interval of three hours one from each other :param id: the location's city ID :type id: int :returns: a *Forecaster* instance or ``None`` if forecast data is not available for the specified location :raises: *ParseResponseException* when OWM Weather API responses' data cannot be parsed, *APICallException* when OWM Weather API can not be reached
4.941589
4.70058
1.051272
assert isinstance(name, str), "Value must be a string" encoded_name = name if limit is not None: assert isinstance(limit, int), "'limit' must be an int or None" if limit < 1: raise ValueError("'limit' must be None or greater than zero") params = {'q': encoded_name, 'lang': self._language} if limit is not None: params['cnt'] = limit uri = http_client.HttpClient.to_url(DAILY_FORECAST_URL, self._API_key, self._subscription_type, self._use_ssl) _, json_data = self._wapi.cacheable_get_json(uri, params=params) forecast = self._parsers['forecast'].parse_JSON(json_data) if forecast is not None: forecast.set_interval("daily") return forecaster.Forecaster(forecast) else: return None
def daily_forecast(self, name, limit=None)
Queries the OWM Weather API for daily weather forecast for the specified location (eg: "London,uk"). A *Forecaster* object is returned, containing a *Forecast* instance covering a global streak of fourteen days by default: this instance encapsulates *Weather* objects, with a time interval of one day one from each other :param name: the location's toponym :type name: str or unicode :param limit: the maximum number of daily *Weather* items to be retrieved (default is ``None``, which stands for any number of items) :type limit: int or ``None`` :returns: a *Forecaster* instance or ``None`` if forecast data is not available for the specified location :raises: *ParseResponseException* when OWM Weather API responses' data cannot be parsed, *APICallException* when OWM Weather API can not be reached, *ValueError* if negative values are supplied for limit
4.19531
4.201966
0.998416
geo.assert_is_lon(lon) geo.assert_is_lat(lat) if limit is not None: assert isinstance(limit, int), "'limit' must be an int or None" if limit < 1: raise ValueError("'limit' must be None or greater than zero") params = {'lon': lon, 'lat': lat, 'lang': self._language} if limit is not None: params['cnt'] = limit uri = http_client.HttpClient.to_url(DAILY_FORECAST_URL, self._API_key, self._subscription_type, self._use_ssl) _, json_data = self._wapi.cacheable_get_json(uri, params=params) forecast = self._parsers['forecast'].parse_JSON(json_data) if forecast is not None: forecast.set_interval("daily") return forecaster.Forecaster(forecast) else: return None
def daily_forecast_at_coords(self, lat, lon, limit=None)
Queries the OWM Weather API for daily weather forecast for the specified geographic coordinate (eg: latitude: 51.5073509, longitude: -0.1277583). A *Forecaster* object is returned, containing a *Forecast* instance covering a global streak of fourteen days by default: this instance encapsulates *Weather* objects, with a time interval of one day one from each other :param lat: location's latitude, must be between -90.0 and 90.0 :type lat: int/float :param lon: location's longitude, must be between -180.0 and 180.0 :type lon: int/float :param limit: the maximum number of daily *Weather* items to be retrieved (default is ``None``, which stands for any number of items) :type limit: int or ``None`` :returns: a *Forecaster* instance or ``None`` if forecast data is not available for the specified location :raises: *ParseResponseException* when OWM Weather API responses' data cannot be parsed, *APICallException* when OWM Weather API can not be reached, *ValueError* if negative values are supplied for limit
4.117484
4.075647
1.010265
assert isinstance(name, str), "Value must be a string" encoded_name = name params = {'q': encoded_name, 'lang': self._language} if start is None and end is None: pass elif start is not None and end is not None: unix_start = timeformatutils.to_UNIXtime(start) unix_end = timeformatutils.to_UNIXtime(end) if unix_start >= unix_end: raise ValueError("Error: the start time boundary must " \ "precede the end time!") current_time = time() if unix_start > current_time: raise ValueError("Error: the start time boundary must " \ "precede the current time!") params['start'] = str(unix_start) params['end'] = str(unix_end) else: raise ValueError("Error: one of the time boundaries is None, " \ "while the other is not!") uri = http_client.HttpClient.to_url(CITY_WEATHER_HISTORY_URL, self._API_key, self._subscription_type, self._use_ssl) _, json_data = self._wapi.cacheable_get_json(uri, params=params) return self._parsers['weather_history'].parse_JSON(json_data)
def weather_history_at_place(self, name, start=None, end=None)
Queries the OWM Weather API for weather history for the specified location (eg: "London,uk"). A list of *Weather* objects is returned. It is possible to query for weather history in a closed time period, whose boundaries can be passed as optional parameters. :param name: the location's toponym :type name: str or unicode :param start: the object conveying the time value for the start query boundary (defaults to ``None``) :type start: int, ``datetime.datetime`` or ISO8601-formatted string :param end: the object conveying the time value for the end query boundary (defaults to ``None``) :type end: int, ``datetime.datetime`` or ISO8601-formatted string :returns: a list of *Weather* instances or ``None`` if history data is not available for the specified location :raises: *ParseResponseException* when OWM Weather API responses' data cannot be parsed, *APICallException* when OWM Weather API can not be reached, *ValueError* if the time boundaries are not in the correct chronological order, if one of the time boundaries is not ``None`` and the other is or if one or both of the time boundaries are after the current time
3.728645
3.590059
1.038603
geo.assert_is_lon(lon) geo.assert_is_lat(lat) params = {'lon': lon, 'lat': lat, 'lang': self._language} if start is not None: unix_start = timeformatutils.to_UNIXtime(start) current_time = time() if unix_start > current_time: raise ValueError("Error: the start time boundary must " "precede the current time!") params['start'] = str(unix_start) else: unix_start = None if end is not None: unix_end = timeformatutils.to_UNIXtime(end) params['end'] = str(unix_end) else: unix_end = None if unix_start is not None and unix_end is not None: if unix_start >= unix_end: raise ValueError("Error: the start time boundary must " "precede the end time!") uri = http_client.HttpClient.to_url(CITY_WEATHER_HISTORY_URL, self._API_key, self._subscription_type, self._use_ssl) _, json_data = self._wapi.cacheable_get_json(uri, params=params) return self._parsers['weather_history'].parse_JSON(json_data)
def weather_history_at_coords(self, lat, lon, start=None, end=None)
Queries the OWM Weather API for weather history for the specified at the specified geographic (eg: 51.503614, -0.107331). A list of *Weather* objects is returned. It is possible to query for weather history in a closed time period, whose boundaries can be passed as optional parameters. :param lat: the location's latitude, must be between -90.0 and 90.0 :type lat: int/float :param lon: the location's longitude, must be between -180.0 and 180.0 :type lon: int/float :param start: the object conveying the time value for the start query boundary (defaults to ``None``) :type start: int, ``datetime.datetime`` or ISO8601-formatted string :param end: the object conveying the time value for the end query boundary (defaults to ``None``) :type end: int, ``datetime.datetime`` or ISO8601-formatted string :returns: a list of *Weather* instances or ``None`` if history data is not available for the specified location
3.465508
3.551796
0.975706
assert type(id) is int, "'id' must be an int" if id < 0: raise ValueError("'id' value must be greater than 0") params = {'id': id, 'lang': self._language} if start is None and end is None: pass elif start is not None and end is not None: unix_start = timeformatutils.to_UNIXtime(start) unix_end = timeformatutils.to_UNIXtime(end) if unix_start >= unix_end: raise ValueError("Error: the start time boundary must " \ "precede the end time!") current_time = time() if unix_start > current_time: raise ValueError("Error: the start time boundary must " \ "precede the current time!") params['start'] = str(unix_start) params['end'] = str(unix_end) else: raise ValueError("Error: one of the time boundaries is None, " \ "while the other is not!") uri = http_client.HttpClient.to_url(CITY_WEATHER_HISTORY_URL, self._API_key, self._subscription_type, self._use_ssl) _, json_data = self._wapi.cacheable_get_json(uri, params=params) return self._parsers['weather_history'].parse_JSON(json_data)
def weather_history_at_id(self, id, start=None, end=None)
Queries the OWM Weather API for weather history for the specified city ID. A list of *Weather* objects is returned. It is possible to query for weather history in a closed time period, whose boundaries can be passed as optional parameters. :param id: the city ID :type id: int :param start: the object conveying the time value for the start query boundary (defaults to ``None``) :type start: int, ``datetime.datetime`` or ISO8601-formatted string :param end: the object conveying the time value for the end query boundary (defaults to ``None``) :type end: int, ``datetime.datetime`` or ISO8601-formatted string :returns: a list of *Weather* instances or ``None`` if history data is not available for the specified location :raises: *ParseResponseException* when OWM Weather API responses' data cannot be parsed, *APICallException* when OWM Weather API can not be reached, *ValueError* if the time boundaries are not in the correct chronological order, if one of the time boundaries is not ``None`` and the other is or if one or both of the time boundaries are after the current time
3.534594
3.315731
1.066007
geo.assert_is_lon(lon) geo.assert_is_lat(lat) if limit is not None: assert isinstance(limit, int), "'limit' must be int or None" if limit < 1: raise ValueError("'limit' must be None or greater than zero") params = {'lat': lat, 'lon': lon} if limit is not None: params['cnt'] = limit uri = http_client.HttpClient.to_url(FIND_STATION_URL, self._API_key, self._subscription_type, self._use_ssl) _, json_data = self._wapi.cacheable_get_json(uri, params=params) return self._parsers['station_list'].parse_JSON(json_data)
def station_at_coords(self, lat, lon, limit=None)
Queries the OWM Weather API for weather stations nearest to the specified geographic coordinates (eg: latitude: 51.5073509, longitude: -0.1277583). A list of *Station* objects is returned, this instance encapsulates a last reported *Weather* object. :param lat: location's latitude, must be between -90.0 and 90.0 :type lat: int/float :param lon: location's longitude, must be between -180.0 and 180.0 :type lon: int/float :param cnt: the maximum number of *Station* items to be retrieved (default is ``None``, which stands for any number of items) :type cnt: int or ``None`` :returns: a list of *Station* objects or ``None`` if station data is not available for the specified location :raises: *ParseResponseException* when OWM Weather API responses' data cannot be parsed, *APICallException* when OWM Weather API can not be reached
4.508
4.672947
0.964702
assert isinstance(station_ID, int), "'station_ID' must be int" if limit is not None: assert isinstance(limit, int), "'limit' must be an int or None" if limit < 1: raise ValueError("'limit' must be None or greater than zero") station_history = self._retrieve_station_history(station_ID, limit, "tick") if station_history is not None: return historian.Historian(station_history) else: return None
def station_tick_history(self, station_ID, limit=None)
Queries the OWM Weather API for historic weather data measurements for the specified meteostation (eg: 2865), sampled once a minute (tick). A *StationHistory* object instance is returned, encapsulating the measurements: the total number of data points can be limited using the appropriate parameter :param station_ID: the numeric ID of the meteostation :type station_ID: int :param limit: the maximum number of data points the result shall contain (default is ``None``, which stands for any number of data points) :type limit: int or ``None`` :returns: a *StationHistory* instance or ``None`` if data is not available for the specified meteostation :raises: *ParseResponseException* when OWM Weather API responses' data cannot be parsed, *APICallException* when OWM Weather API can not be reached, *ValueError* if the limit value is negative
2.749387
2.860263
0.961236
params = {'id': station_ID, 'type': interval, 'lang': self._language} if limit is not None: params['cnt'] = limit uri = http_client.HttpClient.to_url(STATION_WEATHER_HISTORY_URL, self._API_key, self._subscription_type, self._use_ssl) _, json_data = self._wapi.cacheable_get_json(uri, params=params) station_history = \ self._parsers['station_history'].parse_JSON(json_data) if station_history is not None: station_history.set_station_ID(station_ID) station_history.set_interval(interval) return station_history
def _retrieve_station_history(self, station_ID, limit, interval)
Helper method for station_X_history functions.
4.380944
4.363161
1.004076
geo.assert_is_lon(lon) geo.assert_is_lat(lat) params = {'lon': lon, 'lat': lat} json_data = self._uvapi.get_uvi(params) uvindex = self._parsers['uvindex'].parse_JSON(json_data) return uvindex
def uvindex_around_coords(self, lat, lon)
Queries the OWM Weather API for Ultra Violet value sampled in the surroundings of the provided geocoordinates and in the specified time interval. A *UVIndex* object instance is returned, encapsulating a *Location* object and the UV intensity value. :param lat: the location's latitude, must be between -90.0 and 90.0 :type lat: int/float :param lon: the location's longitude, must be between -180.0 and 180.0 :type lon: int/float :return: a *UVIndex* instance or ``None`` if data is not available :raises: *ParseResponseException* when OWM Weather API responses' data cannot be parsed, *APICallException* when OWM Weather API can not be reached, *ValueError* for wrong input values
4.529345
5.035412
0.899498
geo.assert_is_lon(lon) geo.assert_is_lat(lat) params = {'lon': lon, 'lat': lat} json_data = self._uvapi.get_uvi_forecast(params) uvindex_list = self._parsers['uvindex_list'].parse_JSON(json_data) return uvindex_list
def uvindex_forecast_around_coords(self, lat, lon)
Queries the OWM Weather API for forecast Ultra Violet values in the next 8 days in the surroundings of the provided geocoordinates. :param lat: the location's latitude, must be between -90.0 and 90.0 :type lat: int/float :param lon: the location's longitude, must be between -180.0 and 180.0 :type lon: int/float :return: a list of *UVIndex* instances or empty list if data is not available :raises: *ParseResponseException* when OWM Weather API responses' data cannot be parsed, *APICallException* when OWM Weather API can not be reached, *ValueError* for wrong input values
4.405644
4.67683
0.942015
geo.assert_is_lon(lon) geo.assert_is_lat(lat) assert start is not None start = timeformatutils.timeformat(start, 'unix') if end is None: end = timeutils.now(timeformat='unix') else: end = timeformatutils.timeformat(end, 'unix') params = {'lon': lon, 'lat': lat, 'start': start, 'end': end} json_data = self._uvapi.get_uvi_history(params) uvindex_list = self._parsers['uvindex_list'].parse_JSON(json_data) return uvindex_list
def uvindex_history_around_coords(self, lat, lon, start, end=None)
Queries the OWM Weather API for UV index historical values in the surroundings of the provided geocoordinates and in the specified time frame. If the end of the time frame is not provided, that is intended to be the current datetime. :param lat: the location's latitude, must be between -90.0 and 90.0 :type lat: int/float :param lon: the location's longitude, must be between -180.0 and 180.0 :type lon: int/float :param start: the object conveying the time value for the start query boundary :type start: int, ``datetime.datetime`` or ISO8601-formatted string :param end: the object conveying the time value for the end query boundary (defaults to ``None``, in which case the current datetime will be used) :type end: int, ``datetime.datetime`` or ISO8601-formatted string :return: a list of *UVIndex* instances or empty list if data is not available :raises: *ParseResponseException* when OWM Weather API responses' data cannot be parsed, *APICallException* when OWM Weather API can not be reached, *ValueError* for wrong input values
3.342559
3.532031
0.946356
geo.assert_is_lon(lon) geo.assert_is_lat(lat) params = {'lon': lon, 'lat': lat, 'start': start, 'interval': interval} json_data = self._pollapi.get_coi(params) coindex = self._parsers['coindex'].parse_JSON(json_data) if interval is None: interval = 'year' coindex._interval = interval return coindex
def coindex_around_coords(self, lat, lon, start=None, interval=None)
Queries the OWM Weather API for Carbon Monoxide values sampled in the surroundings of the provided geocoordinates and in the specified time interval. A *COIndex* object instance is returned, encapsulating a *Location* object and the list of CO samples If `start` is not provided, the latest available CO samples are retrieved If `start` is provided but `interval` is not, then `interval` defaults to the maximum extent, which is: `year` :param lat: the location's latitude, must be between -90.0 and 90.0 :type lat: int/float :param lon: the location's longitude, must be between -180.0 and 180.0 :type lon: int/float :param start: the object conveying the start value of the search time window start (defaults to ``None``). If not provided, the latest available CO samples value are retrieved :type start: int, ``datetime.datetime`` or ISO8601-formatted string :param interval: the length of the search time window starting at `start` (defaults to ``None``). If not provided, 'year' is used :type interval: str among: 'minute', 'hour', 'day', 'month, 'year' :return: a *COIndex* instance or ``None`` if data is not available :raises: *ParseResponseException* when OWM Weather API responses' data cannot be parsed, *APICallException* when OWM Weather API can not be reached, *ValueError* for wrong input values
4.646732
4.342999
1.069936
geo.assert_is_lon(lon) geo.assert_is_lat(lat) params = {'lon': lon, 'lat': lat, 'start': start, 'interval': interval} json_data = self._pollapi.get_o3(params) ozone = self._parsers['ozone'].parse_JSON(json_data) if interval is None: interval = 'year' ozone._interval = interval return ozone
def ozone_around_coords(self, lat, lon, start=None, interval=None)
Queries the OWM Weather API for Ozone (O3) value in Dobson Units sampled in the surroundings of the provided geocoordinates and in the specified time interval. An *Ozone* object instance is returned, encapsulating a *Location* object and the UV intensity value. If `start` is not provided, the latest available ozone value is retrieved. If `start` is provided but `interval` is not, then `interval` defaults to the maximum extent, which is: `year` :param lat: the location's latitude, must be between -90.0 and 90.0 :type lat: int/float :param lon: the location's longitude, must be between -180.0 and 180.0 :type lon: int/float :param start: the object conveying the start value of the search time window start (defaults to ``None``). If not provided, the latest available Ozone value is retrieved :type start: int, ``datetime.datetime`` or ISO8601-formatted string :param interval: the length of the search time window starting at `start` (defaults to ``None``). If not provided, 'year' is used :type interval: str among: 'minute', 'hour', 'day', 'month, 'year' :return: an *Ozone* instance or ``None`` if data is not available :raises: *ParseResponseException* when OWM Weather API responses' data cannot be parsed, *APICallException* when OWM Weather API can not be reached, *ValueError* for wrong input values
4.537816
4.444977
1.020886
geo.assert_is_lon(lon) geo.assert_is_lat(lat) params = {'lon': lon, 'lat': lat, 'start': start, 'interval': interval} json_data = self._pollapi.get_no2(params) no2index = self._parsers['no2index'].parse_JSON(json_data) if interval is None: interval = 'year' no2index._interval = interval return no2index
def no2index_around_coords(self, lat, lon, start=None, interval=None)
Queries the OWM Weather API for Nitrogen Dioxide values sampled in the surroundings of the provided geocoordinates and in the specified time interval. A *NO2Index* object instance is returned, encapsulating a *Location* object and the list of NO2 samples If `start` is not provided, the latest available NO2 samples are retrieved If `start` is provided but `interval` is not, then `interval` defaults to the maximum extent, which is: `year` :param lat: the location's latitude, must be between -90.0 and 90.0 :type lat: int/float :param lon: the location's longitude, must be between -180.0 and 180.0 :type lon: int/float :param start: the object conveying the start value of the search time window start (defaults to ``None``). If not provided, the latest available NO2 samples value are retrieved :type start: int, ``datetime.datetime`` or ISO8601-formatted string :param interval: the length of the search time window starting at `start` (defaults to ``None``). If not provided, 'year' is used :type interval: str among: 'minute', 'hour', 'day', 'month, 'year' :return: a *NO2Index* instance or ``None`` if data is not available :raises: *ParseResponseException* when OWM Weather API responses' data cannot be parsed, *APICallException* when OWM Weather API can not be reached, *ValueError* for wrong input values
4.438461
4.13368
1.073731
geo.assert_is_lon(lon) geo.assert_is_lat(lat) params = {'lon': lon, 'lat': lat, 'start': start, 'interval': interval} json_data = self._pollapi.get_so2(params) so2index = self._parsers['so2index'].parse_JSON(json_data) if interval is None: interval = 'year' so2index._interval = interval return so2index
def so2index_around_coords(self, lat, lon, start=None, interval=None)
Queries the OWM Weather API for Sulphur Dioxide values sampled in the surroundings of the provided geocoordinates and in the specified time interval. A *SO2Index* object instance is returned, encapsulating a *Location* object and the list of SO2 samples If `start` is not provided, the latest available SO2 samples are retrieved If `start` is provided but `interval` is not, then `interval` defaults to the maximum extent, which is: `year` :param lat: the location's latitude, must be between -90.0 and 90.0 :type lat: int/float :param lon: the location's longitude, must be between -180.0 and 180.0 :type lon: int/float :param start: the object conveying the start value of the search time window start (defaults to ``None``). If not provided, the latest available SO2 samples value are retrieved :type start: int, ``datetime.datetime`` or ISO8601-formatted string :param interval: the length of the search time window starting at `start` (defaults to ``None``). If not provided, 'year' is used :type interval: str among: 'minute', 'hour', 'day', 'month, 'year' :return: a *SO2Index* instance or ``None`` if data is not available :raises: *ParseResponseException* when OWM Weather API responses' data cannot be parsed, *APICallException* when OWM Weather API can not be reached, *ValueError* for wrong input values
4.24832
3.977256
1.068153
if target_temperature_unit == 'kelvin': return d elif target_temperature_unit == 'celsius': return {key: kelvin_to_celsius(d[key]) for key in d} elif target_temperature_unit == 'fahrenheit': return {key: kelvin_to_fahrenheit(d[key]) for key in d} else: raise ValueError("Invalid value for target temperature conversion \ unit")
def kelvin_dict_to(d, target_temperature_unit)
Converts all the values in a dict from Kelvin temperatures to the specified temperature format. :param d: the dictionary containing Kelvin temperature values :type d: dict :param target_temperature_unit: the target temperature unit, may be: 'celsius' or 'fahrenheit' :type target_temperature_unit: str :returns: a dict with the same keys as the input dict and converted temperature values as values :raises: *ValueError* when unknown target temperature units are provided
1.93612
2.093343
0.924894
if kelvintemp < 0: raise ValueError(__name__ + \ ": negative temperature values not allowed") celsiustemp = kelvintemp - KELVIN_OFFSET return float("{0:.2f}".format(celsiustemp))
def kelvin_to_celsius(kelvintemp)
Converts a numeric temperature from Kelvin degrees to Celsius degrees :param kelvintemp: the Kelvin temperature :type kelvintemp: int/long/float :returns: the float Celsius temperature :raises: *TypeError* when bad argument types are provided
3.485575
4.255861
0.819006
if kelvintemp < 0: raise ValueError(__name__ + \ ": negative temperature values not allowed") fahrenheittemp = (kelvintemp - KELVIN_OFFSET) * \ FAHRENHEIT_DEGREE_SCALE + FAHRENHEIT_OFFSET return float("{0:.2f}".format(fahrenheittemp))
def kelvin_to_fahrenheit(kelvintemp)
Converts a numeric temperature from Kelvin degrees to Fahrenheit degrees :param kelvintemp: the Kelvin temperature :type kelvintemp: int/long/float :returns: the float Fahrenheit temperature :raises: *TypeError* when bad argument types are provided
3.278682
4.076133
0.804361
result = dict() for key, value in d.items(): if key != 'deg': # do not convert wind degree result[key] = value * MILES_PER_HOUR_FOR_ONE_METER_PER_SEC else: result[key] = value return result
def metric_wind_dict_to_imperial(d)
Converts all the wind values in a dict from meters/sec (metric measurement system) to miles/hour (imperial measurement system) . :param d: the dictionary containing metric values :type d: dict :returns: a dict with the same keys as the input dict and values converted to miles/hour
4.416522
4.014349
1.100184
if version == '2.5': if config_module is None: config_module = "pyowm.weatherapi25.configuration25" cfg_module = __import__(config_module, fromlist=['']) from pyowm.weatherapi25.owm25 import OWM25 if language is None: language = cfg_module.language if subscription_type is None: subscription_type = cfg_module.API_SUBSCRIPTION_TYPE if subscription_type not in ['free', 'pro']: subscription_type = 'free' if use_ssl is None: use_ssl = cfg_module.USE_SSL return OWM25(cfg_module.parsers, API_key, cfg_module.cache, language, subscription_type, use_ssl) raise ValueError("Unsupported OWM Weather API version")
def OWM(API_key=constants.DEFAULT_API_KEY, version=constants.LATEST_OWM_API_VERSION, config_module=None, language=None, subscription_type=None, use_ssl=None)
A parametrized factory method returning a global OWM instance that represents the desired OWM Weather API version (or the currently supported one if no version number is specified) :param API_key: the OWM Weather API key (defaults to a test value) :type API_key: str :param version: the OWM Weather API version. Defaults to ``None``, which means use the latest web API version :type version: str :param config_module: the Python path of the configuration module you want to provide for instantiating the library. Defaults to ``None``, which means use the default configuration values for the web API version support you are currently requesting. Please be aware that malformed user-defined configuration modules can lead to unwanted behaviour! :type config_module: str (eg: 'mypackage.mysubpackage.myconfigmodule') :param language: the language in which you want text results to be returned. It's a two-characters string, eg: "en", "ru", "it". Defaults to: ``None``, which means use the default language. :type language: str :param subscription_type: the type of OWM Weather API subscription to be wrapped. Can be 'free' (free subscription) or 'pro' (paid subscription), Defaults to: 'free' :type subscription_type: str :param use_ssl: whether API calls should be made via SSL or not. Defaults to: False :type use_ssl: bool :returns: an instance of a proper *OWM* subclass :raises: *ValueError* when unsupported OWM API versions are provided
2.349636
2.496488
0.941177
if JSON_string is None: raise parse_response_error.ParseResponseError('JSON data is None') d = loads(JSON_string) # Check if server returned errors: this check overcomes the lack of use # of HTTP error status codes by the OWM API 2.5. This mechanism is # supposed to be deprecated as soon as the API fully adopts HTTP for # conveying errors to the clients if 'message' in d and 'cod' in d: if d['cod'] == "404": print("OWM API: observation data not available - response " \ "payload: " + dumps(d)) return None else: raise api_response_error.APIResponseError( "OWM API: error - response payload: " + dumps(d), d['cod']) try: place = location.location_from_dictionary(d) except KeyError: raise parse_response_error.ParseResponseError( ''.join([__name__, ': impossible to ' \ 'read location info from JSON data'])) try: w = weather.weather_from_dictionary(d) except KeyError: raise parse_response_error.ParseResponseError( ''.join([__name__, ': impossible to ' \ 'read weather info from JSON data'])) current_time = int(round(time())) return observation.Observation(current_time, place, w)
def parse_JSON(self, JSON_string)
Parses an *Observation* instance out of raw JSON data. Only certain properties of the data are used: if these properties are not found or cannot be parsed, an error is issued. :param JSON_string: a raw JSON string :type JSON_string: str :returns: an *Observation* instance or ``None`` if no data is available :raises: *ParseResponseError* if it is impossible to find or parse the data needed to build the result, *APIResponseError* if the JSON string embeds an HTTP status error
4.77311
4.482226
1.064897
return json.dumps({"reference_time": self._reference_time, "location": json.loads(self._location.to_JSON()), "interval": self._interval, "co_samples": self._co_samples, "reception_time": self._reception_time, })
def to_JSON(self)
Dumps object fields into a JSON formatted string :returns: the JSON string
4.504335
5.383577
0.836681
root_node = self._to_DOM() if xmlns: xmlutils.annotate_with_XMLNS(root_node, COINDEX_XMLNS_PREFIX, COINDEX_XMLNS_URL) return xmlutils.DOM_node_to_XML(root_node, xml_declaration)
def to_XML(self, xml_declaration=True, xmlns=True)
Dumps object fields to an XML-formatted string. The 'xml_declaration' switch enables printing of a leading standard XML line containing XML version and encoding. The 'xmlns' switch enables printing of qualified XMLNS prefixes. :param XML_declaration: if ``True`` (default) prints a leading XML declaration line :type XML_declaration: bool :param xmlns: if ``True`` (default) prints full XMLNS prefixes :type xmlns: bool :returns: an XML-formatted string
5.020782
6.372631
0.787867
if JSON_string is None: raise ParseResponseError('JSON data is None') d = json.loads(JSON_string) station_parser = StationParser() return [station_parser.parse_JSON(json.dumps(item)) for item in d]
def parse_JSON(self, JSON_string)
Parses a list of *Station* instances out of raw JSON data. Only certain properties of the data are used: if these properties are not found or cannot be parsed, an error is issued. :param JSON_string: a raw JSON string :type JSON_string: str :returns: a list of *Station* instances or ``None`` if no data is available :raises: *ParseResponseError* if it is impossible to find or parse the data needed to build the result, *APIResponseError* if the OWM API returns a HTTP status error
4.366109
4.120854
1.059515
line = self._lookup_line_by_city_name(city_name) return int(line.split(",")[1]) if line is not None else None
def id_for(self, city_name)
Returns the long ID corresponding to the first city found that matches the provided city name. The lookup is case insensitive. .. deprecated:: 3.0.0 Use :func:`ids_for` instead. :param city_name: the city name whose ID is looked up :type city_name: str :returns: a long or ``None`` if the lookup fails
4.910871
5.504406
0.892171
if not city_name: return [] if matching not in self.MATCHINGS: raise ValueError("Unknown type of matching: " "allowed values are %s" % ", ".join(self.MATCHINGS)) if country is not None and len(country) != 2: raise ValueError("Country must be a 2-char string") splits = self._filter_matching_lines(city_name, country, matching) return [(int(item[1]), item[0], item[4]) for item in splits]
def ids_for(self, city_name, country=None, matching='nocase')
Returns a list of tuples in the form (long, str, str) corresponding to the int IDs and relative toponyms and 2-chars country of the cities matching the provided city name. The rule for identifying matchings is according to the provided `matching` parameter value. If `country` is provided, the search is restricted to the cities of the specified country. :param country: two character str representing the country where to search for the city. Defaults to `None`, which means: search in all countries. :param matching: str among `exact` (literal, case-sensitive matching), `nocase` (literal, case-insensitive matching) and `like` (matches cities whose name contains as a substring the string fed to the function, no matter the case). Defaults to `nocase`. :raises ValueError if the value for `matching` is unknown :return: list of tuples
3.852996
3.753771
1.026433
line = self._lookup_line_by_city_name(city_name) if line is None: return None tokens = line.split(",") return Location(tokens[0], float(tokens[3]), float(tokens[2]), int(tokens[1]), tokens[4])
def location_for(self, city_name)
Returns the *Location* object corresponding to the first city found that matches the provided city name. The lookup is case insensitive. :param city_name: the city name you want a *Location* for :type city_name: str :returns: a *Location* instance or ``None`` if the lookup fails .. deprecated:: 3.0.0 Use :func:`locations_for` instead.
3.363481
3.794102
0.886502
if not city_name: return [] if matching not in self.MATCHINGS: raise ValueError("Unknown type of matching: " "allowed values are %s" % ", ".join(self.MATCHINGS)) if country is not None and len(country) != 2: raise ValueError("Country must be a 2-char string") splits = self._filter_matching_lines(city_name, country, matching) return [Location(item[0], float(item[3]), float(item[2]), int(item[1]), item[4]) for item in splits]
def locations_for(self, city_name, country=None, matching='nocase')
Returns a list of Location objects corresponding to the int IDs and relative toponyms and 2-chars country of the cities matching the provided city name. The rule for identifying matchings is according to the provided `matching` parameter value. If `country` is provided, the search is restricted to the cities of the specified country. :param country: two character str representing the country where to search for the city. Defaults to `None`, which means: search in all countries. :param matching: str among `exact` (literal, case-sensitive matching), `nocase` (literal, case-insensitive matching) and `like` (matches cities whose name contains as a substring the string fed to the function, no matter the case). Defaults to `nocase`. :raises ValueError if the value for `matching` is unknown :return: list of `weatherapi25.location.Location` objects
3.469671
3.64614
0.951601
locations = self.locations_for(city_name, country, matching=matching) return [loc.to_geopoint() for loc in locations]
def geopoints_for(self, city_name, country=None, matching='nocase')
Returns a list of ``pyowm.utils.geo.Point`` objects corresponding to the int IDs and relative toponyms and 2-chars country of the cities matching the provided city name. The rule for identifying matchings is according to the provided `matching` parameter value. If `country` is provided, the search is restricted to the cities of the specified country. :param country: two character str representing the country where to search for the city. Defaults to `None`, which means: search in all countries. :param matching: str among `exact` (literal, case-sensitive matching), `nocase` (literal, case-insensitive matching) and `like` (matches cities whose name contains as a substring the string fed to the function, no matter the case). Defaults to `nocase`. :raises ValueError if the value for `matching` is unknown :return: list of `pyowm.utils.geo.Point` objects
3.306795
5.625445
0.587828
result = list() # find the right file to scan and extract its lines. Upon "like" # matchings, just read all files if matching == 'like': lines = [l.strip() for l in self._get_all_lines()] else: filename = self._assess_subfile_from(city_name) lines = [l.strip() for l in self._get_lines(filename)] # look for toponyms matching the specified city_name and according to # the specified matching style for line in lines: tokens = line.split(",") # sometimes city names have an inner comma... if len(tokens) == 6: tokens = [tokens[0]+','+tokens[1], tokens[2], tokens[3], tokens[4], tokens[5]] # check country if country is not None: if tokens[4] != country: continue # check city_name if self._city_name_matches(city_name, tokens[0], matching): result.append(tokens) return result
def _filter_matching_lines(self, city_name, country, matching)
Returns an iterable whose items are the lists of split tokens of every text line matched against the city ID files according to the provided combination of city_name, country and matching style :param city_name: str :param country: str or `None` :param matching: str :return: list of lists
4.836483
4.687316
1.031823
for line in lines: toponym = line.split(',')[0] if toponym.lower() == city_name.lower(): return line.strip() return None
def _match_line(self, city_name, lines)
The lookup is case insensitive and returns the first matching line, stripped. :param city_name: str :param lines: list of str :return: str
3.767594
3.432869
1.097506
for alert in self.alerts: if alert.id == alert_id: return alert return None
def get_alert(self, alert_id)
Returns the `Alert` of this `Trigger` having the specified ID :param alert_id: str, the ID of the alert :return: `Alert` instance
2.844926
3.620301
0.785826
unix_timestamp = timeformatutils.to_UNIXtime(timestamp) result = [] for alert in self.alerts: if alert.last_update >= unix_timestamp: result.append(alert) return result
def get_alerts_since(self, timestamp)
Returns all the `Alert` objects of this `Trigger` that were fired since the specified timestamp. :param timestamp: time object representing the point in time since when alerts have to be fetched :type timestamp: int, ``datetime.datetime`` or ISO8601-formatted string :return: list of `Alert` instances
4.441138
4.760667
0.932881
result = [] for alert in self.alerts: for met_condition in alert.met_conditions: if met_condition['condition'].weather_param == weather_param: result.append(alert) break return result
def get_alerts_on(self, weather_param)
Returns all the `Alert` objects of this `Trigger` that refer to the specified weather parameter (eg. 'temp', 'pressure', etc.). The allowed weather params are the ones enumerated by class `pyowm.alertapi30.enums.WeatherParametersEnum` :param weather_param: str, values in `pyowm.alertapi30.enums.WeatherParametersEnum` :return: list of `Alert` instances
3.346812
3.406092
0.982596
start_coverage = min([item.get_reference_time() \ for item in self._forecast]) return timeformatutils.timeformat(start_coverage, timeformat)
def when_starts(self, timeformat='unix')
Returns the GMT time of the start of the forecast coverage, which is the time of the most ancient *Weather* item in the forecast :param timeformat: the format for the time value. May be: '*unix*' (default) for UNIX time '*iso*' for ISO8601-formatted string in the format ``YYYY-MM-DD HH:MM:SS+00`` '*date* for ``datetime.datetime`` object instance :type timeformat: str :returns: a long or a str :raises: *ValueError* when invalid time format values are provided
12.634533
12.290118
1.028024
end_coverage = max([item.get_reference_time() \ for item in self._forecast]) return timeformatutils.timeformat(end_coverage, timeformat)
def when_ends(self, timeformat='unix')
Returns the GMT time of the end of the forecast coverage, which is the time of the most recent *Weather* item in the forecast :param timeformat: the format for the time value. May be: '*unix*' (default) for UNIX time '*iso*' for ISO8601-formatted string in the format ``YYYY-MM-DD HH:MM:SS+00`` '*date* for ``datetime.datetime`` object instance :type timeformat: str :returns: a long or a str :raises: *ValueError* when invalid time format values are provided
12.648083
12.109378
1.044487
time_value = timeformatutils.to_UNIXtime(timeobject) closest_weather = weatherutils.find_closest_weather( self._forecast.get_weathers(), time_value) return weatherutils.status_is(closest_weather, weather_condition, weather_code_registry)
def _will_be(self, timeobject, weather_condition)
Tells if at the specified weather condition will occur at the specified time. The check is performed on the *Weather* item of the forecast which is closest to the time value conveyed by the parameter :param timeobject: may be a UNIX time, a ``datetime.datetime`` object or an ISO8601-formatted string in the format ``YYYY-MM-DD HH:MM:SS+00`` :type timeobject: long/int, ``datetime.datetime`` or str) :param weather_condition: the weather condition to be looked up :type weather_condition: str :returns: boolean
7.918919
8.684731
0.911821
return weatherutils. \ find_closest_weather(self._forecast.get_weathers(), timeformatutils.to_UNIXtime(timeobject))
def get_weather_at(self, timeobject)
Gives the *Weather* item in the forecast that is closest in time to the time value conveyed by the parameter :param timeobject: may be a UNIX time, a ``datetime.datetime`` object or an ISO8601-formatted string in the format ``YYYY-MM-DD HH:MM:SS+00`` :type timeobject: long/int, ``datetime.datetime`` or str) :returns: a *Weather* object
14.68655
20.515402
0.715879
maxtemp = -270.0 # No one would survive that... hottest = None for weather in self._forecast.get_weathers(): d = weather.get_temperature() if 'temp_max' in d: if d['temp_max'] > maxtemp: maxtemp = d['temp_max'] hottest = weather return hottest
def most_hot(self)
Returns the *Weather* object in the forecast having the highest max temperature. The temperature is retrieved using the ``get_temperature['temp_max']`` call; was 'temp_max' key missing for every *Weather* instance in the forecast, ``None`` would be returned. :returns: a *Weather* object or ``None`` if no item in the forecast is eligible
4.787859
4.363805
1.097175
mintemp = 1000.0 # No one would survive that... coldest = None for weather in self._forecast.get_weathers(): d = weather.get_temperature() if 'temp_min' in d: if d['temp_min'] < mintemp: mintemp = d['temp_min'] coldest = weather return coldest
def most_cold(self)
Returns the *Weather* object in the forecast having the lowest min temperature. The temperature is retrieved using the ``get_temperature['temp_min']`` call; was 'temp_min' key missing for every *Weather* instance in the forecast, ``None`` would be returned. :returns: a *Weather* object or ``None`` if no item in the forecast is eligible
4.71249
4.377017
1.076644
max_humidity = 0 most_humid = None for weather in self._forecast.get_weathers(): h = weather.get_humidity() if h > max_humidity: max_humidity = h most_humid = weather return most_humid
def most_humid(self)
Returns the *Weather* object in the forecast having the highest humidty. :returns: a *Weather* object or ``None`` if no item in the forecast is eligible
2.640442
2.745134
0.961863
max_rain = 0 most_rainy = None for weather in self._forecast.get_weathers(): d = weather.get_rain() if 'all' in d: if d['all'] > max_rain: max_rain = d['all'] most_rainy = weather return most_rainy
def most_rainy(self)
Returns the *Weather* object in the forecast having the highest precipitation volume. The rain amount is retrieved via the ``get_rain['all']`` call; was the 'all' key missing for every *Weather* instance in the forecast,``None`` would be returned. :returns: a *Weather* object or ``None`` if no item in the forecast is eligible
2.882353
2.733065
1.054623
max_snow = 0 most_snowy = None for weather in self._forecast.get_weathers(): d = weather.get_snow() if 'all' in d: if d['all'] > max_snow: max_snow = d['all'] most_snowy = weather return most_snowy
def most_snowy(self)
Returns the *Weather* object in the forecast having the highest snow volume. The snow amount is retrieved via the ``get_snow['all']`` call; was the 'all' key missing for every *Weather* instance in the forecast, ``None`` would be returned. :returns: a *Weather* object or ``None`` if no item in the forecast is eligible
3.035513
2.695076
1.126318
max_wind_speed = 0 most_windy = None for weather in self._forecast.get_weathers(): d = weather.get_wind() if 'speed' in d: if d['speed'] > max_wind_speed: max_wind_speed = d['speed'] most_windy = weather return most_windy
def most_windy(self)
Returns the *Weather* object in the forecast having the highest wind speed. The snow amount is retrieved via the ``get_wind['speed']`` call; was the 'speed' key missing for every *Weather* instance in the forecast, ``None`` would be returned. :returns: a *Weather* object or ``None`` if no item in the forecast is eligible
2.662765
2.50543
1.062798
weather_status = weather_code_registry. \ status_for(weather.get_weather_code()).lower() return weather_status == status
def status_is(weather, status, weather_code_registry)
Checks if the weather status code of a *Weather* object corresponds to the detailed status indicated. The lookup is performed against the provided *WeatherCodeRegistry* object. :param weather: the *Weather* object whose status code is to be checked :type weather: *Weather* :param status: a string indicating a detailed weather status :type status: str :param weather_code_registry: a *WeatherCodeRegistry* object :type weather_code_registry: *WeatherCodeRegistry* :returns: ``True`` if the check is positive, ``False`` otherwise
5.624602
7.188505
0.782444
for weather in weather_list: if status_is(weather, status, weather_code_registry): return True return False
def any_status_is(weather_list, status, weather_code_registry)
Checks if the weather status code of any of the *Weather* objects in the provided list corresponds to the detailed status indicated. The lookup is performed against the provided *WeatherCodeRegistry* object. :param weathers: a list of *Weather* objects :type weathers: list :param status: a string indicating a detailed weather status :type status: str :param weather_code_registry: a *WeatherCodeRegistry* object :type weather_code_registry: *WeatherCodeRegistry* :returns: ``True`` if the check is positive, ``False`` otherwise
2.294809
3.698648
0.620445
result = [] for weather in weather_list: if status_is(weather, status, weather_code_registry): result.append(weather) return result
def filter_by_status(weather_list, status, weather_code_registry)
Filters out from the provided list of *Weather* objects a sublist of items having a status corresponding to the provided one. The lookup is performed against the provided *WeatherCodeRegistry* object. :param weathers: a list of *Weather* objects :type weathers: list :param status: a string indicating a detailed weather status :type status: str :param weather_code_registry: a *WeatherCodeRegistry* object :type weather_code_registry: *WeatherCodeRegistry* :returns: ``True`` if the check is positive, ``False`` otherwise
2.571124
3.521925
0.730034
if not weathers_list: return False else: min_of_coverage = min([weather.get_reference_time() \ for weather in weathers_list]) max_of_coverage = max([weather.get_reference_time() \ for weather in weathers_list]) if unixtime < min_of_coverage or unixtime > max_of_coverage: return False return True
def is_in_coverage(unixtime, weathers_list)
Checks if the supplied UNIX time is contained into the time range (coverage) defined by the most ancient and most recent *Weather* objects in the supplied list :param unixtime: the UNIX time to be searched in the time range :type unixtime: int :param weathers_list: the list of *Weather* objects to be scanned for global time coverage :type weathers_list: list :returns: ``True`` if the UNIX time is contained into the time range, ``False`` otherwise
2.15575
2.197031
0.98121
if not weathers_list: return None if not is_in_coverage(unixtime, weathers_list): raise api_response_error.NotFoundError('Error: the specified time is ' + \ 'not included in the weather coverage range') closest_weather = weathers_list[0] time_distance = abs(closest_weather.get_reference_time() - unixtime) for weather in weathers_list: if abs(weather.get_reference_time() - unixtime) < time_distance: time_distance = abs(weather.get_reference_time() - unixtime) closest_weather = weather return closest_weather
def find_closest_weather(weathers_list, unixtime)
Extracts from the provided list of Weather objects the item which is closest in time to the provided UNIXtime. :param weathers_list: a list of *Weather* objects :type weathers_list: list :param unixtime: a UNIX time :type unixtime: int :returns: the *Weather* object which is closest in time or ``None`` if the list is empty
2.73457
2.878805
0.949898
return [ cls.PRECIPITATION, cls.WIND, cls.TEMPERATURE, cls.PRESSURE ]
def items(cls)
All values for this enum :return: list of tuples
6.153445
6.727978
0.914605
with open(path_to_file, 'wb') as f: f.write(self.data)
def persist(self, path_to_file)
Saves the image to disk on a file :param path_to_file: path to the target file :type path_to_file: str :return: `None`
2.84881
3.191953
0.892497
import mimetypes mimetypes.init() mime = mimetypes.guess_type('file://%s' % path_to_file)[0] img_type = ImageTypeEnum.lookup_by_mime_type(mime) with open(path_to_file, 'rb') as f: data = f.read() return Image(data, image_type=img_type)
def load(cls, path_to_file)
Loads the image data from a file on disk and tries to guess the image MIME type :param path_to_file: path to the source file :type path_to_file: str :return: a `pyowm.image.Image` instance
3.109393
2.97654
1.044633
root_node = self._to_DOM() if xmlns: xmlutils.annotate_with_XMLNS(root_node, SO2INDEX_XMLNS_PREFIX, SO2INDEX_XMLNS_URL) return xmlutils.DOM_node_to_XML(root_node, xml_declaration)
def to_XML(self, xml_declaration=True, xmlns=True)
Dumps object fields to an XML-formatted string. The 'xml_declaration' switch enables printing of a leading standard XML line containing XML version and encoding. The 'xmlns' switch enables printing of qualified XMLNS prefixes. :param XML_declaration: if ``True`` (default) prints a leading XML declaration line :type XML_declaration: bool :param xmlns: if ``True`` (default) prints full XMLNS prefixes :type xmlns: bool :returns: an XML-formatted string
5.418154
6.954012
0.779141
if timeformat == "unix": return to_UNIXtime(timeobject) elif timeformat == "iso": return to_ISO8601(timeobject) elif timeformat == "date": return to_date(timeobject) else: raise ValueError("Invalid value for timeformat parameter")
def timeformat(timeobject, timeformat)
Formats the specified time object to the target format type. :param timeobject: the object conveying the time value :type timeobject: int, ``datetime.datetime`` or ISO8601-formatted string with pattern ``YYYY-MM-DD HH:MM:SS+00`` :param timeformat: the target format for the time conversion. May be: '*unix*' (outputs an int UNIXtime), '*date*' (outputs a ``datetime.datetime`` object) or '*iso*' (outputs an ISO8601-formatted string with pattern ``YYYY-MM-DD HH:MM:SS+00``) :type timeformat: str :returns: the formatted time :raises: ValueError when unknown timeformat switches are provided or when negative time values are provided
2.376117
2.541407
0.934961
if isinstance(timeobject, int): if timeobject < 0: raise ValueError("The time value is a negative number") return datetime.utcfromtimestamp(timeobject).replace(tzinfo=UTC()) elif isinstance(timeobject, datetime): return timeobject.replace(tzinfo=UTC()) elif isinstance(timeobject, str): return datetime.strptime(timeobject, '%Y-%m-%d %H:%M:%S+00').replace(tzinfo=UTC()) else: raise TypeError('The time value must be expressed either by an int ' \ 'UNIX time, a datetime.datetime object or an ' \ 'ISO8601-formatted string')
def to_date(timeobject)
Returns the ``datetime.datetime`` object corresponding to the time value conveyed by the specified object, which can be either a UNIXtime, a ``datetime.datetime`` object or an ISO8601-formatted string in the format `YYYY-MM-DD HH:MM:SS+00``. :param timeobject: the object conveying the time value :type timeobject: int, ``datetime.datetime`` or ISO8601-formatted string :returns: a ``datetime.datetime`` object :raises: *TypeError* when bad argument types are provided, *ValueError* when negative UNIXtimes are provided
2.701818
2.272702
1.188813
if isinstance(timeobject, int): if timeobject < 0: raise ValueError("The time value is a negative number") return datetime.utcfromtimestamp(timeobject). \ strftime('%Y-%m-%d %H:%M:%S+00') elif isinstance(timeobject, datetime): return timeobject.strftime('%Y-%m-%d %H:%M:%S+00') elif isinstance(timeobject, str): return timeobject else: raise TypeError('The time value must be expressed either by an int ' \ 'UNIX time, a datetime.datetime object or an ' \ 'ISO8601-formatted string')
def to_ISO8601(timeobject)
Returns the ISO8601-formatted string corresponding to the time value conveyed by the specified object, which can be either a UNIXtime, a ``datetime.datetime`` object or an ISO8601-formatted string in the format `YYYY-MM-DD HH:MM:SS+00``. :param timeobject: the object conveying the time value :type timeobject: int, ``datetime.datetime`` or ISO8601-formatted string :returns: an ISO8601-formatted string with pattern `YYYY-MM-DD HH:MM:SS+00`` :raises: *TypeError* when bad argument types are provided, *ValueError* when negative UNIXtimes are provided
2.55901
2.194636
1.166029
if isinstance(timeobject, int): if timeobject < 0: raise ValueError("The time value is a negative number") return timeobject elif isinstance(timeobject, datetime): return _datetime_to_UNIXtime(timeobject) elif isinstance(timeobject, str): return _ISO8601_to_UNIXtime(timeobject) else: raise TypeError('The time value must be expressed either by an int ' \ 'UNIX time, a datetime.datetime object or an ' \ 'ISO8601-formatted string')
def to_UNIXtime(timeobject)
Returns the UNIXtime corresponding to the time value conveyed by the specified object, which can be either a UNIXtime, a ``datetime.datetime`` object or an ISO8601-formatted string in the format `YYYY-MM-DD HH:MM:SS+00``. :param timeobject: the object conveying the time value :type timeobject: int, ``datetime.datetime`` or ISO8601-formatted string :returns: an int UNIXtime :raises: *TypeError* when bad argument types are provided, *ValueError* when negative UNIXtimes are provided
2.916155
2.472606
1.179385
try: d = datetime.strptime(iso, '%Y-%m-%d %H:%M:%S+00') except ValueError: raise ValueError(__name__ + ": bad format for input ISO8601 string, ' \ 'should have been: YYYY-MM-DD HH:MM:SS+00") return _datetime_to_UNIXtime(d)
def _ISO8601_to_UNIXtime(iso)
Converts an ISO8601-formatted string in the format ``YYYY-MM-DD HH:MM:SS+00`` to the correspondant UNIXtime :param iso: the ISO8601-formatted string :type iso: string :returns: an int UNIXtime :raises: *TypeError* when bad argument types are provided, *ValueError* when the ISO8601 string is badly formatted
4.008657
3.601305
1.113112
current_time = timeutils.now(timeformat='unix') for w in self._weathers: if w.get_reference_time(timeformat='unix') < current_time: self._weathers.remove(w)
def actualize(self)
Removes from this forecast all the *Weather* objects having a reference timestamp in the past with respect to the current timestamp
6.060599
3.539243
1.7124
return json.dumps({"interval": self._interval, "reception_time": self._reception_time, "Location": json.loads(self._location.to_JSON()), "weathers": json.loads("[" + \ ",".join([w.to_JSON() for w in self]) + "]") })
def to_JSON(self)
Dumps object fields into a JSON formatted string :returns: the JSON string
4.904456
5.886424
0.833181
root_node = self._to_DOM() if xmlns: xmlutils.annotate_with_XMLNS(root_node, FORECAST_XMLNS_PREFIX, FORECAST_XMLNS_URL) return xmlutils.DOM_node_to_XML(root_node, xml_declaration)
def to_XML(self, xml_declaration=True, xmlns=True)
Dumps object fields to an XML-formatted string. The 'xml_declaration' switch enables printing of a leading standard XML line containing XML version and encoding. The 'xmlns' switch enables printing of qualified XMLNS prefixes. :param XML_declaration: if ``True`` (default) prints a leading XML declaration line :type XML_declaration: bool :param xmlns: if ``True`` (default) prints full XMLNS prefixes :type xmlns: bool :returns: an XML-formatted string
4.681363
5.880202
0.796123
root_node = ET.Element("forecast") interval_node = ET.SubElement(root_node, "interval") interval_node.text = self._interval reception_time_node = ET.SubElement(root_node, "reception_time") reception_time_node.text = str(self._reception_time) root_node.append(self._location._to_DOM()) weathers_node = ET.SubElement(root_node, "weathers") for weather in self: weathers_node.append(weather._to_DOM()) return root_node
def _to_DOM(self)
Dumps object data to a fully traversable DOM representation of the object. :returns: a ``xml.etree.Element`` object
2.127892
2.368215
0.898522
if unit not in ('kelvin', 'celsius', 'fahrenheit'): raise ValueError("Invalid value for parameter 'unit'") result = [] for tstamp in self._station_history.get_measurements(): t = self._station_history.get_measurements()[tstamp]['temperature'] if unit == 'kelvin': temp = t if unit == 'celsius': temp = temputils.kelvin_to_celsius(t) if unit == 'fahrenheit': temp = temputils.kelvin_to_fahrenheit(t) result.append((tstamp, temp)) return result
def temperature_series(self, unit='kelvin')
Returns the temperature time series relative to the meteostation, in the form of a list of tuples, each one containing the couple timestamp-value :param unit: the unit of measure for the temperature values. May be among: '*kelvin*' (default), '*celsius*' or '*fahrenheit*' :type unit: str :returns: a list of tuples :raises: ValueError when invalid values are provided for the unit of measure
2.408048
2.320795
1.037596
return [(tstamp, \ self._station_history.get_measurements()[tstamp]['humidity']) \ for tstamp in self._station_history.get_measurements()]
def humidity_series(self)
Returns the humidity time series relative to the meteostation, in the form of a list of tuples, each one containing the couple timestamp-value :returns: a list of tuples
7.610885
7.687322
0.990057
return [(tstamp, \ self._station_history.get_measurements()[tstamp]['pressure']) \ for tstamp in self._station_history.get_measurements()]
def pressure_series(self)
Returns the atmospheric pressure time series relative to the meteostation, in the form of a list of tuples, each one containing the couple timestamp-value :returns: a list of tuples
8.583457
8.112516
1.058051
return [(tstamp, \ self._station_history.get_measurements()[tstamp]['rain']) \ for tstamp in self._station_history.get_measurements()]
def rain_series(self)
Returns the precipitation time series relative to the meteostation, in the form of a list of tuples, each one containing the couple timestamp-value :returns: a list of tuples
8.283868
7.934155
1.044077
return [(timestamp, \ self._station_history.get_measurements()[timestamp]['wind']) \ for timestamp in self._station_history.get_measurements()]
def wind_series(self)
Returns the wind speed time series relative to the meteostation, in the form of a list of tuples, each one containing the couple timestamp-value :returns: a list of tuples
9.173052
8.249951
1.111892
if unit not in ('kelvin', 'celsius', 'fahrenheit'): raise ValueError("Invalid value for parameter 'unit'") maximum = max(self._purge_none_samples(self.temperature_series()), key=itemgetter(1)) if unit == 'kelvin': result = maximum if unit == 'celsius': result = (maximum[0], temputils.kelvin_to_celsius(maximum[1])) if unit == 'fahrenheit': result = (maximum[0], temputils.kelvin_to_fahrenheit(maximum[1])) return result
def max_temperature(self, unit='kelvin')
Returns a tuple containing the max value in the temperature series preceeded by its timestamp :param unit: the unit of measure for the temperature values. May be among: '*kelvin*' (default), '*celsius*' or '*fahrenheit*' :type unit: str :returns: a tuple :raises: ValueError when invalid values are provided for the unit of measure or the measurement series is empty
2.997316
2.658521
1.127437