code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
return db.cypher_query("MATCH (aNode) " "WHERE id(aNode)={nodeid} " "RETURN aNode".format(nodeid=self._start_node_id), resolve_objects = True)[0][0][0]
def start_node(self)
Get start node :return: StructuredNode
6.717791
6.681395
1.005447
return db.cypher_query("MATCH (aNode) " "WHERE id(aNode)={nodeid} " "RETURN aNode".format(nodeid=self._end_node_id), resolve_objects = True)[0][0][0]
def end_node(self)
Get end node :return: StructuredNode
6.486357
6.677622
0.971357
props = {} for key, prop in cls.defined_properties(aliases=False, rels=False).items(): if key in rel: props[key] = prop.inflate(rel[key], obj=rel) elif prop.has_default: props[key] = prop.default_value() else: props[key] = None srel = cls(**props) srel._start_node_id = rel.start_node.id srel._end_node_id = rel.end_node.id srel.id = rel.id return srel
def inflate(cls, rel)
Inflate a neo4j_driver relationship object to a neomodel object :param rel: :return: StructuredRel
2.980307
2.803663
1.063005
if JSON_string is None: raise parse_response_error.ParseResponseError('JSON data is None') d = json.loads(JSON_string) # Check if server returned errors: this check overcomes the lack of use # of HTTP error status codes by the OWM API but it's supposed to be # deprecated as soon as the API implements a correct HTTP mechanism for # communicating errors to the clients. In addition, in this specific # case the OWM API responses are the very same either when no results # are found for a station and when the station does not exist! measurements = {} try: if 'cod' in d: if d['cod'] != "200": raise api_response_error.APIResponseError( "OWM API: error - response payload: " + str(d), d['cod']) if str(d['cnt']) == "0": return None else: for item in d['list']: if 'temp' not in item: temp = None elif isinstance(item['temp'], dict): temp = item['temp']['v'] else: temp = item['temp'] if 'humidity' not in item: hum = None elif isinstance(item['humidity'], dict): hum = item['humidity']['v'] else: hum = item['humidity'] if 'pressure' not in item: pres = None elif isinstance(item['pressure'], dict): pres = item['pressure']['v'] else: pres = item['pressure'] if 'rain' in item and isinstance(item['rain']['today'], dict): rain = item['rain']['today']['v'] else: rain = None if 'wind' in item and isinstance(item['wind']['speed'], dict): wind = item['wind']['speed']['v'] else: wind = None measurements[item['dt']] = {"temperature": temp, "humidity": hum, "pressure": pres, "rain": rain, "wind": wind } except KeyError: raise parse_response_error.ParseResponseError(__name__ + \ ': impossible to read JSON data') current_time = round(time.time()) return stationhistory.StationHistory(None, None, current_time, measurements)
def parse_JSON(self, JSON_string)
Parses a *StationHistory* 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: a *StationHistory* 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
3.423432
3.281968
1.043103
lat = str(params_dict['lat']) lon = str(params_dict['lon']) start = params_dict['start'] interval = params_dict['interval'] # build request URL if start is None: timeref = 'current' else: if interval is None: timeref = self._trim_to(timeformatutils.to_date(start), 'year') else: timeref = self._trim_to(timeformatutils.to_date(start), interval) fixed_url = '%s/%s,%s/%s.json' % (CO_INDEX_URL, lat, lon, timeref) uri = http_client.HttpClient.to_url(fixed_url, self._API_key, None) _, json_data = self._client.cacheable_get_json(uri) return json_data
def get_coi(self, params_dict)
Invokes the CO Index endpoint :param params_dict: dict of parameters :returns: a string containing raw JSON data :raises: *ValueError*, *APICallError*
4.366384
4.41007
0.990094
root_node = self._to_DOM() if xmlns: xmlutils.annotate_with_XMLNS(root_node, NO2INDEX_XMLNS_PREFIX, NO2INDEX_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.152886
6.630287
0.777174
root_node = ET.Element("no2index") 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) no2_samples_node = ET.SubElement(root_node, "no2_samples") for smpl in self._no2_samples: s = smpl.copy() # turn values to 12 decimal digits-formatted strings s['label'] = s['label'] s['value'] = '{:.12e}'.format(s['value']) s['precision'] = '{:.12e}'.format(s['precision']) xmlutils.create_DOM_node_from_dict(s, "no2_sample", no2_samples_node) 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.757875
2.884122
0.956227
return [ cls.TRUE_COLOR, cls.FALSE_COLOR, cls.NDVI, cls.EVI ]
def items(cls)
All values for this enum :return: list of str
9.484385
8.97245
1.057056
return [ cls.GREEN, cls.BLACK_AND_WHITE, cls.CONTRAST_SHIFTED, cls.CONTRAST_CONTINUOUS ]
def items(cls)
All values for this enum :return: list of str
7.916665
8.00385
0.989107
assert isinstance(data_dict, dict) string_repr = json.dumps(data_dict) return self.parse_JSON(string_repr)
def parse_dict(self, data_dict)
Parses a dictionary representing the attributes of a `pyowm.alertapi30.trigger.Trigger` entity :param data_dict: dict :return: `pyowm.alertapi30.trigger.Trigger`
4.578779
5.14206
0.890456
if JSON_string is None: raise parse_response_error.ParseResponseError('JSON data is None') d = json.loads(JSON_string) try: # trigger id trigger_id = d.get('_id', None) # start timestamp start_dict = d['time_period']['start'] expr = start_dict['expression'] if expr != 'after': raise ValueError('Invalid time expression: "%s" on start timestamp. Only: "after" is supported' % expr) start = start_dict['amount'] # end timestamp end_dict = d['time_period']['end'] expr = end_dict['expression'] if expr != 'after': raise ValueError('Invalid time expression: "%s" on end timestamp. Only: "after" is supported' % expr) end = end_dict['amount'] # conditions conditions = [Condition.from_dict(c) for c in d['conditions']] # alerts alerts_dict = d['alerts'] alerts = list() for key in alerts_dict: alert_id = key alert_data = alerts_dict[alert_id] alert_last_update = alert_data['last_update'] alert_met_conds = [ dict(current_value=c['current_value']['min'], condition=Condition.from_dict(c['condition'])) for c in alert_data['conditions'] ] alert_coords = alert_data['coordinates'] alert = Alert(alert_id, trigger_id, alert_met_conds, alert_coords, last_update=alert_last_update) alerts.append(alert) # area area_list = d['area'] area = [GeometryBuilder.build(a_dict) for a_dict in area_list] # alert channels alert_channels = None # defaulting except ValueError as e: raise parse_response_error.ParseResponseError('Impossible to parse JSON: %s' % e) except KeyError as e: raise parse_response_error.ParseResponseError('Impossible to parse JSON: %s' % e) return Trigger(start, end, conditions, area=area, alerts=alerts, alert_channels=alert_channels, id=trigger_id)
def parse_JSON(self, JSON_string)
Parses a `pyowm.alertapi30.trigger.Trigger` instance out of raw JSON data. As per OWM documentation, start and end times are expressed with respect to the moment when you create/update the Trigger. By design, PyOWM will only allow users to specify *absolute* datetimes - which is, with the `exact` expression - for start/end timestamps (will otherwise result in a `ParseResponseError` be raised) :param JSON_string: a raw JSON string :type JSON_string: str :return: a `pyowm.alertapi30.trigger.Trigger` 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
2.756654
2.575422
1.07037
if JSON_string is None: raise parse_response_error.ParseResponseError('JSON data is None') d = json.loads(JSON_string) try: alert_id = d['_id'] t = d['last_update'].split('.')[0].replace('T', ' ') + '+00' alert_last_update = timeformatutils._ISO8601_to_UNIXtime(t) alert_trigger_id = d['triggerId'] alert_met_conds = [ dict(current_value=c['current_value']['min'], condition=Condition.from_dict(c['condition'])) for c in d['conditions'] ] alert_coords = d['coordinates'] return Alert(alert_id, alert_trigger_id, alert_met_conds, alert_coords, last_update=alert_last_update) except ValueError as e: raise parse_response_error.ParseResponseError('Impossible to parse JSON: %s' % e) except KeyError as e: raise parse_response_error.ParseResponseError('Impossible to parse JSON: %s' % e)
def parse_JSON(self, JSON_string)
Parses a `pyowm.alertapi30.alert.Alert` instance out of raw JSON data. :param JSON_string: a raw JSON string :type JSON_string: str :return: a `pyowm.alertapi30.alert.Alert` 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
3.781912
3.483415
1.085691
node = LinkedListNode(data, None) if self._size == 0: self._first_node = node self._last_node = node else: second_node = self._first_node self._first_node = node self._first_node.update_next(second_node) self._size += 1
def add(self, data)
Adds a new data node to the front list. The provided data will be encapsulated into a new instance of LinkedListNode class and linked list pointers will be updated, as well as list's size. :param data: the data to be inserted in the new list node :type data: object
2.380574
2.465666
0.965489
current_node = self._first_node deleted = False if self._size == 0: return if data == current_node.data(): # case 1: the list has only one item if current_node.next() is None: self._first_node = LinkedListNode(None, None) self._last_node = self._first_node self._size = 0 return # case 2: the list has more than one item current_node = current_node.next() self._first_node = current_node self._size -= 1 return while True: if current_node is None: deleted = False break # Check next element's data next_node = current_node.next() if next_node is not None: if data == next_node.data(): next_next_node = next_node.next() current_node.update_next(next_next_node) next_node = None deleted = True break current_node = current_node.next() if deleted: self._size -= 1
def remove(self, data)
Removes a data node from the list. If the list contains more than one node having the same data that shall be removed, then the node having the first occurrency of the data is removed. :param data: the data to be removed in the new list node :type data: object
2.365439
2.373343
0.99667
for item in self: if item.data() == data: return True return False
def contains(self, data)
Checks if the provided data is stored in at least one node of the list. :param data: the seeked data :type data: object :returns: a boolean
4.429804
6.152028
0.720056
current_node = self._first_node pos = 0 while current_node: if current_node.data() == data: return pos else: current_node = current_node.next() pos += 1 return -1
def index_of(self, data)
Finds the position of a node in the list. The index of the first occurrence of the data is returned (indexes start at 0) :param data: data of the seeked node :type: object :returns: the int index or -1 if the node is not in the list
2.477668
2.644129
0.937045
popped = False result = None current_node = self._first_node while not popped: next_node = current_node.next() next_next_node = next_node.next() if not next_next_node: self._last_node = current_node self._last_node.update_next(None) self._size -= 1 result = next_node.data() popped = True current_node = next_node return result
def pop(self)
Removes the last node from the list
2.542912
2.528227
1.005808
if self._sunset_time is None: return None return timeformatutils.timeformat(self._sunset_time, timeformat)
def get_sunset_time(self, timeformat='unix')
Returns the GMT time of sunset :param timeformat: the format for the time value. May be: '*unix*' (default) for UNIX time or '*iso*' for ISO8601-formatted string in the format ``YYYY-MM-DD HH:MM:SS+00`` :type timeformat: str :returns: an int or a str or None :raises: ValueError
4.284092
6.110891
0.701058
if self._sunrise_time is None: return None return timeformatutils.timeformat(self._sunrise_time, timeformat)
def get_sunrise_time(self, timeformat='unix')
Returns the GMT time of sunrise :param timeformat: the format for the time value. May be: '*unix*' (default) for UNIX time or '*iso*' for ISO8601-formatted string in the format ``YYYY-MM-DD HH:MM:SS+00`` :type timeformat: str :returns: an int or a str or None :raises: ValueError
4.228084
6.204246
0.681482
if unit == 'meters_sec': return self._wind elif unit == 'miles_hour': wind_dict = {k: self._wind[k] for k in self._wind if self._wind[k] is not None} return temputils.metric_wind_dict_to_imperial(wind_dict) else: raise ValueError("Invalid value for target wind conversion unit")
def get_wind(self, unit='meters_sec')
Returns a dict containing wind info :param unit: the unit of measure for the wind values. May be: '*meters_sec*' (default) or '*miles_hour*' :type unit: str :returns: a dict containing wind info
3.619109
4.004405
0.903782
# This is due to the fact that the OWM Weather API responses are mixing # absolute temperatures and temperature deltas together to_be_converted = dict() not_to_be_converted = dict() for label, temp in self._temperature.items(): if temp is None or temp < 0: not_to_be_converted[label] = temp else: to_be_converted[label] = temp converted = temputils.kelvin_dict_to(to_be_converted, unit) return dict(list(converted.items()) + \ list(not_to_be_converted.items()))
def get_temperature(self, unit='kelvin')
Returns a dict with temperature info :param unit: the unit of measure for the temperature values. May be: '*kelvin*' (default), '*celsius*' or '*fahrenheit*' :type unit: str :returns: a dict containing temperature values. :raises: ValueError when unknown temperature units are provided
4.671427
4.992286
0.935729
return json.dumps({'reference_time': self._reference_time, 'sunset_time': self._sunset_time, 'sunrise_time': self._sunrise_time, 'clouds': self._clouds, 'rain': self._rain, 'snow': self._snow, 'wind': self._wind, 'humidity': self._humidity, 'pressure': self._pressure, 'temperature': self._temperature, 'status': self._status, 'detailed_status': self._detailed_status, 'weather_code': self._weather_code, 'weather_icon_name': self._weather_icon_name, 'visibility_distance': self._visibility_distance, 'dewpoint': self._dewpoint, 'humidex': self._humidex, 'heat_index': self._heat_index})
def to_JSON(self)
Dumps object fields into a JSON formatted string :returns: the JSON string
1.959955
2.075714
0.944232
root_node = self._to_DOM() if xmlns: xmlutils.annotate_with_XMLNS(root_node, WEATHER_XMLNS_PREFIX, WEATHER_XMLNS_URL) return xmlutils.DOM_node_to_XML(root_node, xml_declaration). \ encode('utf-8')
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.777596
5.82975
0.81952
root_node = ET.Element("weather") status_node = ET.SubElement(root_node, "status") status_node.text = self._status weather_code_node = ET.SubElement(root_node, "weather_code") weather_code_node.text = str(self._weather_code) xmlutils.create_DOM_node_from_dict(self._rain, "rain", root_node) xmlutils.create_DOM_node_from_dict(self._snow, "snow", root_node) xmlutils.create_DOM_node_from_dict(self._pressure, "pressure", root_node) node_sunrise_time = ET.SubElement(root_node, "sunrise_time") node_sunrise_time.text = str(self._sunrise_time) if self._sunrise_time is not None else 'null' weather_icon_name_node = ET.SubElement(root_node, "weather_icon_name") weather_icon_name_node.text = self._weather_icon_name clouds_node = ET.SubElement(root_node, "clouds") clouds_node.text = str(self._clouds) xmlutils.create_DOM_node_from_dict(self._temperature, "temperature", root_node) detailed_status_node = ET.SubElement(root_node, "detailed_status") detailed_status_node.text = self._detailed_status reference_time_node = ET.SubElement(root_node, "reference_time") reference_time_node.text = str(self._reference_time) sunset_time_node = ET.SubElement(root_node, "sunset_time") sunset_time_node.text = str(self._sunset_time) if self._sunset_time is not None else 'null' humidity_node = ET.SubElement(root_node, "humidity") humidity_node.text = str(self._humidity) xmlutils.create_DOM_node_from_dict(self._wind, "wind", root_node) visibility_distance_node = ET.SubElement(root_node, "visibility_distance") visibility_distance_node.text = str(self._visibility_distance) dewpoint_node = ET.SubElement(root_node, "dewpoint") dewpoint_node.text = str(self._dewpoint) humidex_node = ET.SubElement(root_node, "humidex") humidex_node.text = str(self._humidex) heat_index_node = ET.SubElement(root_node, "heat_index") heat_index_node.text = str(self._heat_index) 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.572464
1.604706
0.979908
if self.created_at is None: return None return timeformatutils.timeformat(self.created_at, timeformat)
def creation_time(self, timeformat='unix')
Returns the UTC time of creation of this station :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`` or `date` for a ``datetime.datetime`` object :type timeformat: str :returns: an int or a str or a ``datetime.datetime`` object or None :raises: ValueError
4.01291
6.768444
0.592885
if self.updated_at is None: return None return timeformatutils.timeformat(self.updated_at, timeformat)
def last_update_time(self, timeformat='unix')
Returns the UTC time of the last update on this station's metadata :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`` or `date` for a ``datetime.datetime`` object :type timeformat: str :returns: an int or a str or a ``datetime.datetime`` object or None :raises: ValueError
4.195396
6.904659
0.607618
return json.dumps({'id': self.id, 'external_id': self.external_id, 'name': self.name, 'created_at': timeformatutils.to_ISO8601(self.created_at), 'updated_at': timeformatutils.to_ISO8601(self.updated_at), 'lat': self.lat, 'lon': self.lon, 'alt': self.alt if self.alt is not None else 'None', 'rank': self.rank})
def to_JSON(self)
Dumps object fields into a JSON formatted string :returns: the JSON string
2.548225
2.804739
0.908543
root_node = self._to_DOM() if xmlns: xmlutils.annotate_with_XMLNS(root_node, STATION_XMLNS_PREFIX, STATION_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.514576
5.653774
0.798507
root_node = ET.Element('station') created_at_node = ET.SubElement(root_node, "created_at") created_at_node.text = \ timeformatutils.to_ISO8601(self.created_at)if self.created_at is not None else 'null' updated_at_node = ET.SubElement(root_node, "updated_at") updated_at_node.text = \ timeformatutils.to_ISO8601(self.updated_at)if self.updated_at is not None else 'null' station_id_node = ET.SubElement(root_node, 'id') station_id_node.text = str(self.id) station_id_node = ET.SubElement(root_node, 'external_id') station_id_node.text = str(self.external_id) station_name_node = ET.SubElement(root_node, 'name') station_name_node.text = str(self.name) if self.name is not None else 'null' lat_node = ET.SubElement(root_node, 'lat') lat_node.text = str(self.lat) lon_node = ET.SubElement(root_node, 'lon') lon_node.text = str(self.lon) alt_node = ET.SubElement(root_node, 'alt') alt_node.text = str(self.alt) if self.alt is not None else 'null' rank_node = ET.SubElement(root_node, 'rank') rank_node.text = str(self.rank) if self.rank is not None else 'null' 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.535387
1.566532
0.980119
return json.dumps({"station_ID": self._station_ID, "interval": self._interval, "reception_time": self._reception_time, "measurements": self._measurements })
def to_JSON(self)
Dumps object fields into a JSON formatted string :returns: the JSON string
4.700984
6.028489
0.779795
root_node = self._to_DOM() if xmlns: xmlutils.annotate_with_XMLNS(root_node, STATION_HISTORY_XMLNS_PREFIX, STATION_HISTORY_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.78919
5.876059
0.815034
root_node = ET.Element("station_history") station_id_node = ET.SubElement(root_node, "station_id") station_id_node.text = str(self._station_ID) 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) measurements_node = ET.SubElement(root_node, "measurements") for m in self._measurements: d = self._measurements[m].copy() d['reference_time'] = m xmlutils.create_DOM_node_from_dict(d, "measurement", measurements_node) 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.479338
2.595318
0.955312
if JSON_string is None: raise parse_response_error.ParseResponseError('JSON data is None') d = json.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: data not found - response payload: " + \ json.dumps(d)) return None elif d['cod'] != "200": raise api_response_error.APIResponseError( "OWM API: error - response payload: " + json.dumps(d), d['cod']) # Handle the case when no results are found if 'cnt' in d and d['cnt'] == "0": return [] else: if 'list' in d: try: return [weather.weather_from_dictionary(item) \ for item in d['list']] except KeyError: raise parse_response_error.ParseResponseError( ''.join([__name__, ': impossible to read ' \ 'weather info from JSON data']) ) else: raise parse_response_error.ParseResponseError( ''.join([__name__, ': impossible to read ' \ 'weather list from JSON data']) )
def parse_JSON(self, JSON_string)
Parses a list of *Weather* 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 *Weather* 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 JSON string embeds an HTTP status error
4.377111
4.124517
1.061242
if hour is None: hour = datetime.now().hour if minute is None: minute = datetime.now().minute tomorrow_date = date.today() + timedelta(days=1) return datetime(tomorrow_date.year, tomorrow_date.month, tomorrow_date.day, hour, minute, 0)
def tomorrow(hour=None, minute=None)
Gives the ``datetime.datetime`` object corresponding to tomorrow. The default value for optional parameters is the current value of hour and minute. I.e: when called without specifying values for parameters, the resulting object will refer to the time = now + 24 hours; when called with only hour specified, the resulting object will refer to tomorrow at the specified hour and at the current minute. :param hour: the hour for tomorrow, in the format *0-23* (defaults to ``None``) :type hour: int :param minute: the minute for tomorrow, in the format *0-59* (defaults to ``None``) :type minute: int :returns: a ``datetime.datetime`` object :raises: *ValueError* when hour or minute have bad values
1.776893
2.37359
0.74861
if hour is None: hour = datetime.now().hour if minute is None: minute = datetime.now().minute yesterday_date = date.today() + timedelta(days=-1) return datetime(yesterday_date.year, yesterday_date.month, yesterday_date.day, hour, minute, 0)
def yesterday(hour=None, minute=None)
Gives the ``datetime.datetime`` object corresponding to yesterday. The default value for optional parameters is the current value of hour and minute. I.e: when called without specifying values for parameters, the resulting object will refer to the time = now - 24 hours; when called with only hour specified, the resulting object will refer to yesterday at the specified hour and at the current minute. :param hour: the hour for yesterday, in the format *0-23* (defaults to ``None``) :type hour: int :param minute: the minute for yesterday, in the format *0-59* (defaults to ``None``) :type minute: int :returns: a ``datetime.datetime`` object :raises: *ValueError* when hour or minute have bad values
1.852391
2.419587
0.765581
assert isinstance(reference_epoch, int) assert isinstance(target_epoch, int) return (target_epoch - reference_epoch)*1000
def millis_offset_between_epochs(reference_epoch, target_epoch)
Calculates the signed milliseconds delta between the reference unix epoch and the provided target unix epoch :param reference_epoch: the unix epoch that the millis offset has to be calculated with respect to :type reference_epoch: int :param target_epoch: the unix epoch for which the millis offset has to be calculated :type target_epoch: int :return: int
2.272156
2.665379
0.85247
lon_left, lat_bottom, lon_right, lat_top = Tile.tile_coords_to_bbox(self.x, self.y, self.zoom) print(lon_left, lat_bottom, lon_right, lat_top) return Polygon([[[lon_left, lat_top], [lon_right, lat_top], [lon_right, lat_bottom], [lon_left, lat_bottom], [lon_left, lat_top]]])
def bounding_polygon(self)
Returns the bounding box polygon for this tile :return: `pywom.utils.geo.Polygon` instance
2.228078
2.288989
0.973389
return Tile.geoocoords_to_tile_coords(geopoint.lon, geopoint.lat, zoom)
def tile_coords_for_point(cls, geopoint, zoom)
Returns the coordinates of the tile containing the specified geopoint at the specified zoom level :param geopoint: the input geopoint instance :type geopoint: `pywom.utils.geo.Point` :param zoom: zoom level :type zoom: int :return: a tuple (x, y) containing the tile-coordinates
6.63089
9.856503
0.672743
n = 2.0 ** zoom x = int((lon + 180.0) / 360.0 * n) y = int((1.0 - math.log(math.tan(math.radians(lat)) + (1 / math.cos(math.radians(lat)))) / math.pi) / 2.0 * n) return x, y
def geoocoords_to_tile_coords(cls, lon, lat, zoom)
Calculates the tile numbers corresponding to the specified geocoordinates at the specified zoom level Coordinates shall be provided in degrees and using the Mercator Projection (http://en.wikipedia.org/wiki/Mercator_projection) :param lon: longitude :type lon: int or float :param lat: latitude :type lat: int or float :param zoom: zoom level :type zoom: int :return: a tuple (x, y) containing the tile-coordinates
1.477874
1.65449
0.893251
def tile_to_geocoords(x, y, zoom): n = 2. ** zoom lon = x / n * 360. - 180. lat = math.degrees(math.atan(math.sinh(math.pi * (1 - 2 * y / n)))) return lat, lon north_west_corner = tile_to_geocoords(x, y, zoom) south_east_corner = tile_to_geocoords(x+1, y+1, zoom) return north_west_corner[1], south_east_corner[0], south_east_corner[1], north_west_corner[0]
def tile_coords_to_bbox(cls, x, y, zoom)
Calculates the lon/lat estrema of the bounding box corresponding to specific tile coordinates. Output coodinates are in degrees and in the Mercator Projection (http://en.wikipedia.org/wiki/Mercator_projection) :param x: the x tile coordinates :param y: the y tile coordinates :param zoom: the zoom level :return: tuple with (lon_left, lat_bottom, lon_right, lat_top)
1.858102
1.97787
0.939446
status, data = self.http_client.get_png( ROOT_TILE_URL % self.map_layer + '/%s/%s/%s.png' % (zoom, x, y), params={'appid': self.API_key}) img = Image(data, ImageTypeEnum.PNG) return Tile(x, y, zoom, self.map_layer, img)
def get_tile(self, x, y, zoom)
Retrieves the tile having the specified coordinates and zoom level :param x: horizontal tile number in OWM tile reference system :type x: int :param y: vertical tile number in OWM tile reference system :type y: int :param zoom: zoom level for the tile :type zoom: int :returns: a `pyowm.tiles.Tile` instance
5.411642
5.681003
0.952586
if JSON_string is None: raise parse_response_error.ParseResponseError('JSON data is None') d = json.loads(JSON_string) try: id = d.get('ID', None) or d.get('id', None) external_id = d.get('external_id', None) lon = d.get('longitude', None) lat = d.get('latitude', None) alt = d.get('altitude', None) except KeyError as e: raise parse_response_error.ParseResponseError('Impossible to parse JSON: %s' % e) name = d.get('name', None) rank = d.get('rank', None) created_at = d.get('created_at', None) updated_at = d.get('updated_at', None) return Station(id, created_at, updated_at, external_id, name, lon, lat, alt, rank)
def parse_JSON(self, JSON_string)
Parses a *pyowm.stationsapi30.station.Station* instance out of raw JSON data. :param JSON_string: a raw JSON string :type JSON_string: str :return: a *pyowm.stationsapi30.station.Station** 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
2.376915
2.204857
1.078036
last = None if self._last_weather: last = self._last_weather.to_JSON() return json.dumps({'name': self._name, 'station_ID': self._station_ID, 'station_type': self._station_type, 'status': self._status, 'lat': self._lat, 'lon': self._lon, 'distance': self._distance, 'weather': json.loads(last), })
def to_JSON(self)
Dumps object fields into a JSON formatted string :returns: the JSON string
2.893874
3.177669
0.910691
root_node = self._to_DOM() if xmlns: xmlutils.annotate_with_XMLNS(root_node, LIST_STATION_XMLNS_PREFIX, LIST_STATION_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.809377
6.280364
0.76578
last_weather = None if (self._last_weather and isinstance(self._last_weather, weather.Weather)): last_weather = self._last_weather._to_DOM() root_node = ET.Element('station') station_name_node = ET.SubElement(root_node, 'name') station_name_node.text = str(self._name) station_id_node = ET.SubElement(root_node, 'station_id') station_id_node.text = str(self._station_ID) station_type_node = ET.SubElement(root_node, 'station_type') station_type_node.text = str(self._station_type) status_node = ET.SubElement(root_node, 'status') status_node.text = str(self._status) coords_node = ET.SubElement(root_node, 'coords') lat_node = ET.SubElement(coords_node, 'lat') lat_node.text = str(self._lat) lon_node = ET.SubElement(coords_node, 'lon') lon_node.text = str(self._lon) distance_node = ET.SubElement(root_node, 'distance') distance_node.text = str(self._distance) root_node.append(last_weather) 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.668383
1.655944
1.007512
assert start is not None assert end is not None # prepare time period unix_start = timeformatutils.to_UNIXtime(start) unix_end = timeformatutils.to_UNIXtime(end) unix_current = timeutils.now(timeformat='unix') if unix_start >= unix_end: raise ValueError("The start timestamp must precede the end timestamp") delta_millis_start = timeutils.millis_offset_between_epochs(unix_current, unix_start) delta_millis_end = timeutils.millis_offset_between_epochs(unix_current, unix_end) the_time_period = { "start": { "expression": "after", "amount": delta_millis_start }, "end": { "expression": "after", "amount": delta_millis_end } } assert conditions is not None if len(conditions) == 0: raise ValueError('A trigger must contain at least one condition: you provided none') the_conditions = [dict(name=c.weather_param, expression=c.operator, amount=c.amount) for c in conditions] assert area is not None if len(area) == 0: raise ValueError('The area for a trigger must contain at least one geoJSON type: you provided none') the_area = [a.as_dict() for a in area] # >>> for the moment, no specific handling for alert channels status, payload = self.http_client.post( TRIGGERS_URI, params={'appid': self.API_key}, data=dict(time_period=the_time_period, conditions=the_conditions, area=the_area), headers={'Content-Type': 'application/json'}) return self.trigger_parser.parse_dict(payload)
def create_trigger(self, start, end, conditions, area, alert_channels=None)
Create a new trigger on the Alert API with the given parameters :param start: time object representing the time when the trigger begins to be checked :type start: int, ``datetime.datetime`` or ISO8601-formatted string :param end: time object representing the time when the trigger ends to be checked :type end: int, ``datetime.datetime`` or ISO8601-formatted string :param conditions: the `Condition` objects representing the set of checks to be done on weather variables :type conditions: list of `pyowm.utils.alertapi30.Condition` instances :param area: the geographic are over which conditions are checked: it can be composed by multiple geoJSON types :type area: list of geoJSON types :param alert_channels: the alert channels through which alerts originating from this `Trigger` can be consumed. Defaults to OWM API polling :type alert_channels: list of `pyowm.utils.alertapi30.AlertChannel` instances :returns: a *Trigger* instance :raises: *ValueError* when start or end epochs are `None` or when end precedes start or when conditions or area are empty collections
3.603763
3.240638
1.112054
status, data = self.http_client.get_json( TRIGGERS_URI, params={'appid': self.API_key}, headers={'Content-Type': 'application/json'}) return [self.trigger_parser.parse_dict(item) for item in data]
def get_triggers(self)
Retrieves all of the user's triggers that are set on the Weather Alert API. :returns: list of `pyowm.alertapi30.trigger.Trigger` objects
5.283504
5.461668
0.967379
assert isinstance(trigger_id, str), "Value must be a string" status, data = self.http_client.get_json( NAMED_TRIGGER_URI % trigger_id, params={'appid': self.API_key}, headers={'Content-Type': 'application/json'}) return self.trigger_parser.parse_dict(data)
def get_trigger(self, trigger_id)
Retrieves the named trigger from the Weather Alert API. :param trigger_id: the ID of the trigger :type trigger_id: str :return: a `pyowm.alertapi30.trigger.Trigger` instance
4.997049
4.537672
1.101236
assert trigger is not None assert isinstance(trigger.id, str), "Value must be a string" the_time_period = { "start": { "expression": "after", "amount": trigger.start_after_millis }, "end": { "expression": "after", "amount": trigger.end_after_millis } } the_conditions = [dict(name=c.weather_param, expression=c.operator, amount=c.amount) for c in trigger.conditions] the_area = [a.as_dict() for a in trigger.area] status, _ = self.http_client.put( NAMED_TRIGGER_URI % trigger.id, params={'appid': self.API_key}, data=dict(time_period=the_time_period, conditions=the_conditions, area=the_area), headers={'Content-Type': 'application/json'})
def update_trigger(self, trigger)
Updates on the Alert API the trigger record having the ID of the specified Trigger object: the remote record is updated with data from the local Trigger object. :param trigger: the Trigger with updated data :type trigger: `pyowm.alertapi30.trigger.Trigger` :return: ``None`` if update is successful, an error otherwise
4.100368
3.948747
1.038397
assert trigger is not None assert isinstance(trigger.id, str), "Value must be a string" status, _ = self.http_client.delete( NAMED_TRIGGER_URI % trigger.id, params={'appid': self.API_key}, headers={'Content-Type': 'application/json'})
def delete_trigger(self, trigger)
Deletes from the Alert API the trigger record identified by the ID of the provided `pyowm.alertapi30.trigger.Trigger`, along with all related alerts :param trigger: the `pyowm.alertapi30.trigger.Trigger` object to be deleted :type trigger: `pyowm.alertapi30.trigger.Trigger` :returns: `None` if deletion is successful, an exception otherwise
5.863205
6.18619
0.947789
assert trigger is not None assert isinstance(trigger.id, str), "Value must be a string" status, data = self.http_client.get_json( ALERTS_URI % trigger.id, params={'appid': self.API_key}, headers={'Content-Type': 'application/json'}) return [self.alert_parser.parse_dict(item) for item in data]
def get_alerts_for(self, trigger)
Retrieves all of the alerts that were fired for the specified Trigger :param trigger: the trigger :type trigger: `pyowm.alertapi30.trigger.Trigger` :return: list of `pyowm.alertapi30.alert.Alert` objects
4.892848
4.81251
1.016693
assert trigger is not None assert alert_id is not None assert isinstance(alert_id, str), "Value must be a string" assert isinstance(trigger.id, str), "Value must be a string" status, data = self.http_client.get_json( NAMED_ALERT_URI % (trigger.id, alert_id), params={'appid': self.API_key}, headers={'Content-Type': 'application/json'}) return self.alert_parser.parse_dict(data)
def get_alert(self, alert_id, trigger)
Retrieves info about the alert record on the Alert API that has the specified ID and belongs to the specified parent Trigger object :param trigger: the parent trigger :type trigger: `pyowm.alertapi30.trigger.Trigger` :param alert_id: the ID of the alert :type alert_id `pyowm.alertapi30.alert.Alert` :return: an `pyowm.alertapi30.alert.Alert` instance
3.992162
3.735358
1.06875
assert trigger is not None assert isinstance(trigger.id, str), "Value must be a string" status, _ = self.http_client.delete( ALERTS_URI % trigger.id, params={'appid': self.API_key}, headers={'Content-Type': 'application/json'})
def delete_all_alerts_for(self, trigger)
Deletes all of the alert that were fired for the specified Trigger :param trigger: the trigger whose alerts are to be cleared :type trigger: `pyowm.alertapi30.trigger.Trigger` :return: `None` if deletion is successful, an exception otherwise
5.57644
5.629395
0.990593
assert alert is not None assert isinstance(alert.id, str), "Value must be a string" assert isinstance(alert.trigger_id, str), "Value must be a string" status, _ = self.http_client.delete( NAMED_ALERT_URI % (alert.trigger_id, alert.id), params={'appid': self.API_key}, headers={'Content-Type': 'application/json'})
def delete_alert(self, alert)
Deletes the specified alert from the Alert API :param alert: the alert to be deleted :type alert: pyowm.alertapi30.alert.Alert` :return: ``None`` if the deletion was successful, an error otherwise
4.27257
4.399083
0.971241
if JSON_string is None: raise parse_response_error.ParseResponseError('JSON data is None') d = json.loads(JSON_string) try: # -- reference time reference_time = d['date'] # -- reception time (now) reception_time = timeutils.now('unix') # -- location lon = float(d['lon']) lat = float(d['lat']) place = location.Location(None, lon, lat, None) # -- UV intensity uv_intensity = float(d['value']) except KeyError: raise parse_response_error.ParseResponseError( ''.join([__name__, ': impossible to parse UV Index'])) return uvindex.UVIndex(reference_time, place, uv_intensity, reception_time)
def parse_JSON(self, JSON_string)
Parses an *UVIndex* 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 *UVIndex* 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.530408
4.066703
1.114025
if JSON_string is None: raise parse_response_error.ParseResponseError('JSON data is None') d = json.loads(JSON_string) uvindex_parser = UVIndexParser() return [uvindex_parser.parse_JSON(json.dumps(item)) for item in d]
def parse_JSON(self, JSON_string)
Parses a list of *UVIndex* 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 *UVIndex* instances or an empty list 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.187877
4.13769
1.25381
status, data = self.http_client.get_json( STATIONS_URI, params={'appid': self.API_key}, headers={'Content-Type': 'application/json'}) return [self.stations_parser.parse_dict(item) for item in data]
def get_stations(self)
Retrieves all of the user's stations registered on the Stations API. :returns: list of *pyowm.stationsapi30.station.Station* objects
5.554132
5.491751
1.011359
status, data = self.http_client.get_json( NAMED_STATION_URI % str(id), params={'appid': self.API_key}, headers={'Content-Type': 'application/json'}) return self.stations_parser.parse_dict(data)
def get_station(self, id)
Retrieves a named station registered on the Stations API. :param id: the ID of the station :type id: str :returns: a *pyowm.stationsapi30.station.Station* object
5.549533
5.955983
0.931758
assert external_id is not None assert name is not None assert lon is not None assert lat is not None if lon < -180.0 or lon > 180.0: raise ValueError("'lon' value must be between -180 and 180") if lat < -90.0 or lat > 90.0: raise ValueError("'lat' value must be between -90 and 90") if alt is not None: if alt < 0.0: raise ValueError("'alt' value must not be negative") status, payload = self.http_client.post( STATIONS_URI, params={'appid': self.API_key}, data=dict(external_id=external_id, name=name, lat=lat, lon=lon, alt=alt), headers={'Content-Type': 'application/json'}) return self.stations_parser.parse_dict(payload)
def create_station(self, external_id, name, lat, lon, alt=None)
Create a new station on the Station API with the given parameters :param external_id: the user-given ID of the station :type external_id: str :param name: the name of the station :type name: str :param lat: latitude of the station :type lat: float :param lon: longitude of the station :type lon: float :param alt: altitude of the station :type alt: float :returns: the new *pyowm.stationsapi30.station.Station* object
2.101914
2.020064
1.040518
assert station.id is not None status, _ = self.http_client.put( NAMED_STATION_URI % str(station.id), params={'appid': self.API_key}, data=dict(external_id=station.external_id, name=station.name, lat=station.lat, lon=station.lon, alt=station.alt), headers={'Content-Type': 'application/json'})
def update_station(self, station)
Updates the Station API record identified by the ID of the provided *pyowm.stationsapi30.station.Station* object with all of its fields :param station: the *pyowm.stationsapi30.station.Station* object to be updated :type station: *pyowm.stationsapi30.station.Station* :returns: `None` if update is successful, an exception otherwise
3.894876
3.848848
1.011959
assert station.id is not None status, _ = self.http_client.delete( NAMED_STATION_URI % str(station.id), params={'appid': self.API_key}, headers={'Content-Type': 'application/json'})
def delete_station(self, station)
Deletes the Station API record identified by the ID of the provided *pyowm.stationsapi30.station.Station*, along with all its related measurements :param station: the *pyowm.stationsapi30.station.Station* object to be deleted :type station: *pyowm.stationsapi30.station.Station* :returns: `None` if deletion is successful, an exception otherwise
5.843763
5.779819
1.011063
assert measurement is not None assert measurement.station_id is not None status, _ = self.http_client.post( MEASUREMENTS_URI, params={'appid': self.API_key}, data=[self._structure_dict(measurement)], headers={'Content-Type': 'application/json'})
def send_measurement(self, measurement)
Posts the provided Measurement object's data to the Station API. :param measurement: the *pyowm.stationsapi30.measurement.Measurement* object to be posted :type measurement: *pyowm.stationsapi30.measurement.Measurement* instance :returns: `None` if creation is successful, an exception otherwise
6.050927
5.57933
1.084526
assert list_of_measurements is not None assert all([m.station_id is not None for m in list_of_measurements]) msmts = [self._structure_dict(m) for m in list_of_measurements] status, _ = self.http_client.post( MEASUREMENTS_URI, params={'appid': self.API_key}, data=msmts, headers={'Content-Type': 'application/json'})
def send_measurements(self, list_of_measurements)
Posts data about the provided list of Measurement objects to the Station API. The objects may be related to different station IDs. :param list_of_measurements: list of *pyowm.stationsapi30.measurement.Measurement* objects to be posted :type list_of_measurements: list of *pyowm.stationsapi30.measurement.Measurement* instances :returns: `None` if creation is successful, an exception otherwise
4.055199
3.727454
1.087927
assert station_id is not None assert aggregated_on is not None assert from_timestamp is not None assert from_timestamp > 0 assert to_timestamp is not None assert to_timestamp > 0 if to_timestamp < from_timestamp: raise ValueError("End timestamp can't be earlier than begin timestamp") assert isinstance(limit, int) assert limit >= 0 query = {'appid': self.API_key, 'station_id': station_id, 'type': aggregated_on, 'from': from_timestamp, 'to': to_timestamp, 'limit': limit} status, data = self.http_client.get_json( MEASUREMENTS_URI, params=query, headers={'Content-Type': 'application/json'}) return [self.aggregated_measurements_parser.parse_dict(item) for item in data]
def get_measurements(self, station_id, aggregated_on, from_timestamp, to_timestamp, limit=100)
Reads measurements of a specified station recorded in the specified time window and aggregated on minute, hour or day. Optionally, the number of resulting measurements can be limited. :param station_id: unique station identifier :type station_id: str :param aggregated_on: aggregation time-frame for this measurement :type aggregated_on: string between 'm','h' and 'd' :param from_timestamp: Unix timestamp corresponding to the beginning of the time window :type from_timestamp: int :param to_timestamp: Unix timestamp corresponding to the end of the time window :type to_timestamp: int :param limit: max number of items to be returned. Defaults to 100 :type limit: int :returns: list of *pyowm.stationsapi30.measurement.AggregatedMeasurement* objects
2.503349
2.513046
0.996141
assert buffer is not None msmts = [self._structure_dict(m) for m in buffer.measurements] status, _ = self.http_client.post( MEASUREMENTS_URI, params={'appid': self.API_key}, data=msmts, headers={'Content-Type': 'application/json'})
def send_buffer(self, buffer)
Posts to the Stations API data about the Measurement objects contained into the provided Buffer instance. :param buffer: the *pyowm.stationsapi30.buffer.Buffer* instance whose measurements are to be posted :type buffer: *pyowm.stationsapi30.buffer.Buffer* instance :returns: `None` if creation is successful, an exception otherwise
7.286992
5.392336
1.351361
if d is not None: root_dict_node = ET.SubElement(parent_node, name) for key, value in d.items(): if value is not None: node = ET.SubElement(root_dict_node, key) node.text = str(value) return root_dict_node
def create_DOM_node_from_dict(d, name, parent_node)
Dumps dict data to an ``xml.etree.ElementTree.SubElement`` DOM subtree object and attaches it to the specified DOM parent node. The created subtree object is named after the specified name. If the supplied dict is ``None`` no DOM node is created for it as well as no DOM subnodes are generated for eventual ``None`` values found inside the dict :param d: the input dictionary :type d: dict :param name: the name for the DOM subtree to be created :type name: str :param parent_node: the parent DOM node the newly created subtree must be attached to :type parent_node: ``xml.etree.ElementTree.Element`` or derivative objects :returns: ``xml.etree.ElementTree.SubElementTree`` object
2.112586
2.370032
0.891375
result = ET.tostring(tree, encoding='utf8', method='xml').decode('utf-8') if not xml_declaration: result = result.split("<?xml version='1.0' encoding='utf8'?>\n")[1] return result
def DOM_node_to_XML(tree, xml_declaration=True)
Prints a DOM tree to its Unicode representation. :param tree: the input DOM tree :type tree: an ``xml.etree.ElementTree.Element`` object :param xml_declaration: if ``True`` (default) prints a leading XML declaration line :type xml_declaration: bool :returns: Unicode object
2.333877
3.143666
0.742406
if not ET.iselement(tree): tree = tree.getroot() tree.attrib['xmlns:' + prefix] = URI iterator = tree.iter() next(iterator) # Don't add XMLNS prefix to the root node for e in iterator: e.tag = prefix + ":" + e.tag
def annotate_with_XMLNS(tree, prefix, URI)
Annotates the provided DOM tree with XMLNS attributes and adds XMLNS prefixes to the tags of the tree nodes. :param tree: the input DOM tree :type tree: an ``xml.etree.ElementTree.ElementTree`` or ``xml.etree.ElementTree.Element`` object :param prefix: XMLNS prefix for tree nodes' tags :type prefix: str :param URI: the URI for the XMLNS definition file :type URI: str
3.541057
3.9554
0.895246
assert isinstance(image_type, ImageType) return list(filter(lambda x: x.image_type == image_type, self.metaimages))
def with_img_type(self, image_type)
Returns the search results having the specified image type :param image_type: the desired image type (valid values are provided by the `pyowm.commons.enums.ImageTypeEnum` enum) :type image_type: `pyowm.commons.databoxes.ImageType` instance :returns: a list of `pyowm.agroapi10.imagery.MetaImage` instances
4.689122
4.429917
1.058512
assert isinstance(preset, str) return list(filter(lambda x: x.preset == preset, self.metaimages))
def with_preset(self, preset)
Returns the seach results having the specified preset :param preset: the desired image preset (valid values are provided by the `pyowm.agroapi10.enums.PresetEnum` enum) :type preset: str :returns: a list of `pyowm.agroapi10.imagery.MetaImage` instances
8.071764
5.991807
1.347133
assert isinstance(image_type, ImageType) assert isinstance(preset, str) return list(filter(lambda x: x.image_type == image_type and x.preset == preset, self.metaimages))
def with_img_type_and_preset(self, image_type, preset)
Returns the search results having both the specified image type and preset :param image_type: the desired image type (valid values are provided by the `pyowm.commons.enums.ImageTypeEnum` enum) :type image_type: `pyowm.commons.databoxes.ImageType` instance :param preset: the desired image preset (valid values are provided by the `pyowm.agroapi10.enums.PresetEnum` enum) :type preset: str :returns: a list of `pyowm.agroapi10.imagery.MetaImage` instances
3.462392
2.927654
1.182651
is_in = lambda start, end, n: True if start <= n <= end else False for status in self._code_ranges_dict: for _range in self._code_ranges_dict[status]: if is_in(_range['start'],_range['end'],code): return status return None
def status_for(self, code)
Returns the weather status related to the specified weather status code, if any is stored, ``None`` otherwise. :param code: the weather status code whose status is to be looked up :type code: int :returns: the weather status str or ``None`` if the code is not mapped
4.293581
4.975342
0.862972
if JSON_string is None: raise parse_response_error.ParseResponseError('JSON data is None') d = json.loads(JSON_string) station_id = d.get('station_id', None) ts = d.get('date', None) if ts is not None: ts = int(ts) aggregated_on = d.get('type', None) temp = d.get('temp', dict()) humidity = d.get('humidity', dict()) wind = d.get('wind', dict()) pressure = d.get('pressure', dict()) precipitation = d.get('precipitation', dict()) return AggregatedMeasurement(station_id, ts, aggregated_on, temp=temp, humidity=humidity, wind=wind, pressure=pressure, precipitation=precipitation)
def parse_JSON(self, JSON_string)
Parses a *pyowm.stationsapi30.measurement.AggregatedMeasurement* instance out of raw JSON data. :param JSON_string: a raw JSON string :type JSON_string: str :return: a *pyowm.stationsapi30.measurement.AggregatedMeasurement* 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
2.662884
2.287532
1.164086
if self.timestamp is None: return None return timeformatutils.timeformat(self.timestamp, timeformat)
def creation_time(self, timeformat='unix')
Returns the UTC time of creation of this aggregated measurement :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`` or `date` for a ``datetime.datetime`` object :type timeformat: str :returns: an int or a str or a ``datetime.datetime`` object or None :raises: ValueError
4.984743
8.739951
0.57034
return {'station_id': self.station_id, 'timestamp': self.timestamp, 'aggregated_on': self.aggregated_on, 'temp': self.temp, 'humidity': self.humidity, 'wind': self.wind, 'pressure': self.pressure, 'precipitation': self.precipitation}
def to_dict(self)
Dumps object fields into a dict :returns: a dict
2.600106
2.778842
0.935679
return { 'station_id': self.station_id, 'timestamp': self.timestamp, 'temperature': self.temperature, 'wind_speed': self.wind_speed, 'wind_gust': self.wind_gust, 'wind_deg': self.wind_deg, 'pressure': self.pressure, 'humidity': self.humidity, 'rain_1h': self.rain_1h, 'rain_6h': self.rain_6h, 'rain_24h': self.rain_24h, 'snow_1h': self.snow_1h, 'snow_6h': self.snow_6h, 'snow_24h': self.snow_24h, 'dew_point': self.dew_point, 'humidex': self.humidex, 'heat_index': self.heat_index, 'visibility_distance': self.visibility_distance, 'visibility_prefix': self.visibility_prefix, 'clouds_distance': self.clouds_distance, 'clouds_condition': self.clouds_condition, 'clouds_cumulus': self.clouds_cumulus, 'weather_precipitation': self.weather_precipitation, 'weather_descriptor': self.weather_descriptor, 'weather_intensity': self.weather_intensity, 'weather_proximity': self.weather_proximity, 'weather_obscuration': self.weather_obscuration, 'weather_other': self.weather_other}
def to_dict(self)
Dumps object fields into a dictionary :returns: a dict
1.712124
1.72757
0.991059
country = None if 'sys' in d and 'country' in d['sys']: country = d['sys']['country'] if 'city' in d: data = d['city'] else: data = d if 'name' in data: name = data['name'] else: name = None if 'id' in data: ID = int(data['id']) else: ID = None if 'coord' in data: lon = data['coord'].get('lon', 0.0) lat = data['coord'].get('lat', 0.0) elif 'coord' in data['station']: if 'lon' in data['station']['coord']: lon = data['station']['coord'].get('lon', 0.0) elif 'lng' in data['station']['coord']: lon = data['station']['coord'].get('lng', 0.0) else: lon = 0.0 lat = data['station']['coord'].get('lat', 0.0) else: raise KeyError("Impossible to read geographical coordinates from JSON") if 'country' in data: country = data['country'] return Location(name, lon, lat, ID, country)
def location_from_dictionary(d)
Builds a *Location* object out of a data dictionary. Only certain properties of the dictionary are used: if these properties are not found or cannot be read, an error is issued. :param d: a data dictionary :type d: dict :returns: a *Location* instance :raises: *KeyError* if it is impossible to find or read the data needed to build the instance
1.912141
2.015761
0.948595
if self._lon is None or self._lat is None: return None return geo.Point(self._lon, self._lat)
def to_geopoint(self)
Returns the geoJSON compliant representation of this location :returns: a ``pyowm.utils.geo.Point`` instance
3.323753
4.163973
0.798217
return json.dumps({'name': self._name, 'coordinates': {'lon': self._lon, 'lat': self._lat }, 'ID': self._ID, 'country': self._country})
def to_JSON(self)
Dumps object fields into a JSON formatted string :returns: the JSON string
4.629291
5.709274
0.810837
root_node = self._to_DOM() if xmlns: xmlutils.annotate_with_XMLNS(root_node, LOCATION_XMLNS_PREFIX, LOCATION_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.442907
5.754435
0.772084
root_node = ET.Element("location") name_node = ET.SubElement(root_node, "name") name_node.text = self._name coords_node = ET.SubElement(root_node, "coordinates") lon_node = ET.SubElement(coords_node, "lon") lon_node.text = str(self._lon) lat_node = ET.SubElement(coords_node, "lat") lat_node.text = str(self._lat) id_node = ET.SubElement(root_node, "ID") id_node.text = str(self._ID) country_node = ET.SubElement(root_node, "country") country_node.text = self._country 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.588636
1.710044
0.929003
if JSON_string is None: raise parse_response_error.ParseResponseError('JSON data is None') d = json.loads(JSON_string) try: name = d['station']['name'] station_ID = d['station']['id'] station_type = d['station']['type'] status = d['station']['status'] lat = d['station']['coord']['lat'] if 'lon' in d['station']['coord']: lon = d['station']['coord']['lon'] elif 'lng' in d['station']['coord']: lon = d['station']['coord']['lng'] else: lon = None if 'distance' in d: distance = d['distance'] else: distance = None except KeyError as e: error_msg = ''.join((__name__, ': unable to read JSON data', )) raise parse_response_error.ParseResponseError(error_msg) else: if 'last' in d: last_weather = weather.weather_from_dictionary(d['last']) else: last_weather = None return station.Station(name, station_ID, station_type, status, lat, lon, distance, last_weather)
def parse_JSON(self, JSON_string)
Parses a *Station* 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: a *Station* 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
2.599176
2.531633
1.02668
try: cached_item = self._table[request_url] cur_time = timeutils.now('unix') if cur_time - cached_item['insertion_time'] > self._item_lifetime: # Cache item has expired self._clean_item(request_url) return None cached_item['insertion_time'] = cur_time # Update insertion time self._promote(request_url) return cached_item['data'] except: return None
def get(self, request_url)
In case of a hit, returns the JSON string which represents the OWM web API response to the request being identified by a specific string URL and updates the recency of this request. :param request_url: an URL that uniquely identifies the request whose response is to be looked up :type request_url: str :returns: a JSON str in case of cache hit or ``None`` otherwise
4.284215
4.218284
1.01563
if self.size() == self._max_size: popped = self._usage_recency.pop() del self._table[popped] current_time = timeutils.now('unix') if request_url not in self._table: self._table[request_url] = {'data': response_json, 'insertion_time': current_time} self._usage_recency.add(request_url) else: self._table[request_url]['insertion_time'] = current_time self._promote(request_url)
def set(self, request_url, response_json)
Checks if the maximum size of the cache has been reached and in case discards the least recently used item from 'usage_recency' and 'table'; then adds the response_json to be cached to the 'table' dict using as a lookup key the request_url of the request that generated the value; finally adds it at the front of 'usage_recency' :param request_url: the request URL that uniquely identifies the request whose response is to be cached :type request_url: str :param response_json: the response JSON to be cached :type response_json: str
3.576427
2.812903
1.271437
self._usage_recency.remove(request_url) self._usage_recency.add(request_url)
def _promote(self, request_url)
Moves the cache item specified by request_url to the front of the 'usage_recency' list
7.717955
3.224768
2.393337
del self._table[request_url] self._usage_recency.remove(request_url)
def _clean_item(self, request_url)
Removes the specified item from the cache's datastructures :param request_url: the request URL :type request_url: str
12.831895
11.587452
1.107396
self._table.clear() for item in self._usage_recency: self._usage_recency.remove(item)
def clean(self)
Empties the cache
10.942462
8.098631
1.35115
assert isinstance(measurement, Measurement) assert measurement.station_id == self.station_id self.measurements.append(measurement)
def append(self, measurement)
Appends the specified ``Measurement`` object to the buffer :param measurement: a ``measurement.Measurement`` instance
3.205849
3.801759
0.843254
m = Measurement.from_dict(the_dict) self.append(m)
def append_from_dict(self, the_dict)
Creates a ``measurement.Measurement`` object from the supplied dict and then appends it to the buffer :param the_dict: dict
5.677454
4.463217
1.272054
a_dict = json.loads(json_string) self.append_from_dict(a_dict)
def append_from_json(self, json_string)
Creates a ``measurement.Measurement`` object from the supplied JSON string and then appends it to the buffer :param json_string: the JSON formatted string
3.129045
4.443901
0.704121
self.measurements.sort(key=lambda m: m.timestamp, reverse=True)
def sort_reverse_chronologically(self)
Sorts the measurements of this buffer in reverse chronological order
4.995943
3.060447
1.632423
if unit == 'kelvin': return self._surface_temp if unit == 'celsius': return temputils.kelvin_to_celsius(self._surface_temp) if unit == 'fahrenheit': return temputils.kelvin_to_fahrenheit(self._surface_temp) else: raise ValueError('Wrong temperature unit')
def surface_temp(self, unit='kelvin')
Returns the soil surface temperature :param unit: the unit of measure for the temperature value. May be: '*kelvin*' (default), '*celsius*' or '*fahrenheit*' :type unit: str :returns: a float :raises: ValueError when unknown temperature units are provided
1.895337
2.137527
0.886696
if unit == 'kelvin': return self._ten_cm_temp if unit == 'celsius': return temputils.kelvin_to_celsius(self._ten_cm_temp) if unit == 'fahrenheit': return temputils.kelvin_to_fahrenheit(self._ten_cm_temp) else: raise ValueError('Wrong temperature unit')
def ten_cm_temp(self, unit='kelvin')
Returns the soil temperature measured 10 cm below surface :param unit: the unit of measure for the temperature value. May be: '*kelvin*' (default), '*celsius*' or '*fahrenheit*' :type unit: str :returns: a float :raises: ValueError when unknown temperature units are provided
1.872492
2.102057
0.890791
assert type(val) is float or type(val) is int, "Value must be a number" if val < -90.0 or val > 90.0: raise ValueError("Latitude value must be between -90 and 90")
def assert_is_lat(val)
Checks it the given value is a feasible decimal latitude :param val: value to be checked :type val: int of float :returns: `None` :raises: *ValueError* if value is out of latitude boundaries, *AssertionError* if type is wrong
2.287433
2.884949
0.792885
assert type(val) is float or type(val) is int, "Value must be a number" if val < -180.0 or val > 180.0: raise ValueError("Longitude value must be between -180 and 180")
def assert_is_lon(val)
Checks it the given value is a feasible decimal longitude :param val: value to be checked :type val: int of float :returns: `None` :raises: *ValueError* if value is out of longitude boundaries, *AssertionError* if type is wrong
2.12286
2.720302
0.780377
assert isinstance(inscribed_circle_radius_km, int) or isinstance(inscribed_circle_radius_km, float) assert inscribed_circle_radius_km > 0., 'Radius must be greater than zero' # turn metric distance to radians on the approximated local sphere rad_distance = float(inscribed_circle_radius_km) / EARTH_RADIUS_KM # calculating min/max lat for bounding box bb_min_lat_deg = self.lat * math.pi/180. - rad_distance bb_max_lat_deg = self.lat * math.pi/180. + rad_distance # now checking for poles... if bb_min_lat_deg > math.radians(-90) and bb_max_lat_deg < math.radians(90): # no poles in the bounding box delta_lon = math.asin(math.sin(rad_distance) / math.cos(math.radians(self.lat))) bb_min_lon_deg = math.radians(self.lon) - delta_lon if bb_min_lon_deg < math.radians(-180): bb_min_lon_deg += 2 * math.pi bb_max_lon_deg = math.radians(self.lon) + delta_lon if bb_max_lon_deg > math.radians(180): bb_max_lon_deg -= 2 * math.pi else: # a pole is contained in the bounding box bb_min_lat_deg = max(bb_min_lat_deg, math.radians(-90)) bb_max_lat_deg = min(bb_max_lat_deg, math.radians(90)) bb_min_lon_deg = math.radians(-180) bb_max_lon_deg = math.radians(180) # turn back from radians to decimal bb_min_lat = bb_min_lat_deg * 180./math.pi bb_max_lat = bb_max_lat_deg * 180./math.pi bb_min_lon = bb_min_lon_deg * 180./math.pi bb_max_lon = bb_max_lon_deg * 180./math.pi return Polygon([[ [bb_min_lon, bb_max_lat], [bb_max_lon, bb_max_lat], [bb_max_lon, bb_min_lat], [bb_min_lon, bb_min_lat], [bb_min_lon, bb_max_lat] ]])
def bounding_square_polygon(self, inscribed_circle_radius_km=10.0)
Returns a square polygon (bounding box) that circumscribes the circle having this geopoint as centre and having the specified radius in kilometers. The polygon's points calculation is based on theory exposed by: http://janmatuschek.de/LatitudeLongitudeBoundingCoordinates by Jan Philip Matuschek, owner of the intellectual property of such material. In short: - locally to the geopoint, the Earth's surface is approximated to a sphere with radius = Earth's radius - the calculation works fine also when the bounding box contains the Earth's poles and the 180 deg meridian :param inscribed_circle_radius_km: the radius of the inscribed circle, defaults to 10 kms :type inscribed_circle_radius_km: int or float :return: a `pyowm.utils.geo.Polygon` instance
1.824829
1.763942
1.034517
return MultiPoint([(p.lon, p.lat) for p in iterable_of_points])
def from_points(cls, iterable_of_points)
Creates a MultiPoint from an iterable collection of `pyowm.utils.geo.Point` instances :param iterable_of_points: iterable whose items are `pyowm.utils.geo.Point` instances :type iterable_of_points: iterable :return: a *MultiPoint* instance
4.815954
4.852565
0.992455
feature = geojson.Feature(geometry=self._geom) points_coords = list(geojson.utils.coords(feature)) return [Point(p[0], p[1]) for p in points_coords]
def points(self)
Returns the list of *Point* instances representing the points of the polygon :return: list of *Point* objects
4.524666
4.886304
0.925989
result = [] for l in list_of_lists: curve = [] for point in l: curve.append((point.lon, point.lat)) result.append(curve) return Polygon(result)
def from_points(cls, list_of_lists)
Creates a *Polygon* instance out of a list of lists, each sublist being populated with `pyowm.utils.geo.Point` instances :param list_of_lists: list :type: list_of_lists: iterable_of_polygons :returns: a *Polygon* instance
3.1542
3.033473
1.039798
geom = geojson.loads(json.dumps(the_dict)) result = MultiPolygon([ [[[0, 0], [0, 0]]], [[[1, 1], [1, 1]]] ]) result._geom = geom return result
def from_dict(self, the_dict)
Builds a MultiPolygoninstance out of a geoJSON compliant dict :param the_dict: the geoJSON dict :return: `pyowm.utils.geo.MultiPolygon` instance
4.037701
3.849819
1.048803