repo
stringlengths
7
55
path
stringlengths
4
223
func_name
stringlengths
1
134
original_string
stringlengths
75
104k
language
stringclasses
1 value
code
stringlengths
75
104k
code_tokens
listlengths
19
28.4k
docstring
stringlengths
1
46.9k
docstring_tokens
listlengths
1
1.97k
sha
stringlengths
40
40
url
stringlengths
87
315
partition
stringclasses
1 value
rbuffat/pyepw
pyepw/epw.py
DataPeriod.data_period_name_or_description
def data_period_name_or_description(self, value=None): """Corresponds to IDD Field `data_period_name_or_description` Args: value (str): value for IDD Field `data_period_name_or_description` if `value` is None it will not be checked against the specification and is assumed to be a missing value Raises: ValueError: if `value` is not a valid value """ if value is not None: try: value = str(value) except ValueError: raise ValueError( 'value {} need to be of type str ' 'for field `data_period_name_or_description`'.format(value)) if ',' in value: raise ValueError('value should not contain a comma ' 'for field `data_period_name_or_description`') self._data_period_name_or_description = value
python
def data_period_name_or_description(self, value=None): """Corresponds to IDD Field `data_period_name_or_description` Args: value (str): value for IDD Field `data_period_name_or_description` if `value` is None it will not be checked against the specification and is assumed to be a missing value Raises: ValueError: if `value` is not a valid value """ if value is not None: try: value = str(value) except ValueError: raise ValueError( 'value {} need to be of type str ' 'for field `data_period_name_or_description`'.format(value)) if ',' in value: raise ValueError('value should not contain a comma ' 'for field `data_period_name_or_description`') self._data_period_name_or_description = value
[ "def", "data_period_name_or_description", "(", "self", ",", "value", "=", "None", ")", ":", "if", "value", "is", "not", "None", ":", "try", ":", "value", "=", "str", "(", "value", ")", "except", "ValueError", ":", "raise", "ValueError", "(", "'value {} need to be of type str '", "'for field `data_period_name_or_description`'", ".", "format", "(", "value", ")", ")", "if", "','", "in", "value", ":", "raise", "ValueError", "(", "'value should not contain a comma '", "'for field `data_period_name_or_description`'", ")", "self", ".", "_data_period_name_or_description", "=", "value" ]
Corresponds to IDD Field `data_period_name_or_description` Args: value (str): value for IDD Field `data_period_name_or_description` if `value` is None it will not be checked against the specification and is assumed to be a missing value Raises: ValueError: if `value` is not a valid value
[ "Corresponds", "to", "IDD", "Field", "data_period_name_or_description" ]
373d4d3c8386c8d35789f086ac5f6018c2711745
https://github.com/rbuffat/pyepw/blob/373d4d3c8386c8d35789f086ac5f6018c2711745/pyepw/epw.py#L5178-L5201
train
rbuffat/pyepw
pyepw/epw.py
DataPeriod.data_period_start_day_of_week
def data_period_start_day_of_week(self, value=None): """Corresponds to IDD Field `data_period_start_day_of_week` Args: value (str): value for IDD Field `data_period_start_day_of_week` Accepted values are: - Sunday - Monday - Tuesday - Wednesday - Thursday - Friday - Saturday if `value` is None it will not be checked against the specification and is assumed to be a missing value Raises: ValueError: if `value` is not a valid value """ if value is not None: try: value = str(value) except ValueError: raise ValueError( 'value {} need to be of type str ' 'for field `data_period_start_day_of_week`'.format(value)) if ',' in value: raise ValueError('value should not contain a comma ' 'for field `data_period_start_day_of_week`') vals = set() vals.add("Sunday") vals.add("Monday") vals.add("Tuesday") vals.add("Wednesday") vals.add("Thursday") vals.add("Friday") vals.add("Saturday") if value not in vals: raise ValueError( 'value {} is not an accepted value for ' 'field `data_period_start_day_of_week`'.format(value)) self._data_period_start_day_of_week = value
python
def data_period_start_day_of_week(self, value=None): """Corresponds to IDD Field `data_period_start_day_of_week` Args: value (str): value for IDD Field `data_period_start_day_of_week` Accepted values are: - Sunday - Monday - Tuesday - Wednesday - Thursday - Friday - Saturday if `value` is None it will not be checked against the specification and is assumed to be a missing value Raises: ValueError: if `value` is not a valid value """ if value is not None: try: value = str(value) except ValueError: raise ValueError( 'value {} need to be of type str ' 'for field `data_period_start_day_of_week`'.format(value)) if ',' in value: raise ValueError('value should not contain a comma ' 'for field `data_period_start_day_of_week`') vals = set() vals.add("Sunday") vals.add("Monday") vals.add("Tuesday") vals.add("Wednesday") vals.add("Thursday") vals.add("Friday") vals.add("Saturday") if value not in vals: raise ValueError( 'value {} is not an accepted value for ' 'field `data_period_start_day_of_week`'.format(value)) self._data_period_start_day_of_week = value
[ "def", "data_period_start_day_of_week", "(", "self", ",", "value", "=", "None", ")", ":", "if", "value", "is", "not", "None", ":", "try", ":", "value", "=", "str", "(", "value", ")", "except", "ValueError", ":", "raise", "ValueError", "(", "'value {} need to be of type str '", "'for field `data_period_start_day_of_week`'", ".", "format", "(", "value", ")", ")", "if", "','", "in", "value", ":", "raise", "ValueError", "(", "'value should not contain a comma '", "'for field `data_period_start_day_of_week`'", ")", "vals", "=", "set", "(", ")", "vals", ".", "add", "(", "\"Sunday\"", ")", "vals", ".", "add", "(", "\"Monday\"", ")", "vals", ".", "add", "(", "\"Tuesday\"", ")", "vals", ".", "add", "(", "\"Wednesday\"", ")", "vals", ".", "add", "(", "\"Thursday\"", ")", "vals", ".", "add", "(", "\"Friday\"", ")", "vals", ".", "add", "(", "\"Saturday\"", ")", "if", "value", "not", "in", "vals", ":", "raise", "ValueError", "(", "'value {} is not an accepted value for '", "'field `data_period_start_day_of_week`'", ".", "format", "(", "value", ")", ")", "self", ".", "_data_period_start_day_of_week", "=", "value" ]
Corresponds to IDD Field `data_period_start_day_of_week` Args: value (str): value for IDD Field `data_period_start_day_of_week` Accepted values are: - Sunday - Monday - Tuesday - Wednesday - Thursday - Friday - Saturday if `value` is None it will not be checked against the specification and is assumed to be a missing value Raises: ValueError: if `value` is not a valid value
[ "Corresponds", "to", "IDD", "Field", "data_period_start_day_of_week" ]
373d4d3c8386c8d35789f086ac5f6018c2711745
https://github.com/rbuffat/pyepw/blob/373d4d3c8386c8d35789f086ac5f6018c2711745/pyepw/epw.py#L5214-L5257
train
rbuffat/pyepw
pyepw/epw.py
DataPeriod.data_period_start_day
def data_period_start_day(self, value=None): """Corresponds to IDD Field `data_period_start_day` Args: value (str): value for IDD Field `data_period_start_day` if `value` is None it will not be checked against the specification and is assumed to be a missing value Raises: ValueError: if `value` is not a valid value """ if value is not None: try: value = str(value) except ValueError: raise ValueError( 'value {} need to be of type str ' 'for field `data_period_start_day`'.format(value)) if ',' in value: raise ValueError('value should not contain a comma ' 'for field `data_period_start_day`') self._data_period_start_day = value
python
def data_period_start_day(self, value=None): """Corresponds to IDD Field `data_period_start_day` Args: value (str): value for IDD Field `data_period_start_day` if `value` is None it will not be checked against the specification and is assumed to be a missing value Raises: ValueError: if `value` is not a valid value """ if value is not None: try: value = str(value) except ValueError: raise ValueError( 'value {} need to be of type str ' 'for field `data_period_start_day`'.format(value)) if ',' in value: raise ValueError('value should not contain a comma ' 'for field `data_period_start_day`') self._data_period_start_day = value
[ "def", "data_period_start_day", "(", "self", ",", "value", "=", "None", ")", ":", "if", "value", "is", "not", "None", ":", "try", ":", "value", "=", "str", "(", "value", ")", "except", "ValueError", ":", "raise", "ValueError", "(", "'value {} need to be of type str '", "'for field `data_period_start_day`'", ".", "format", "(", "value", ")", ")", "if", "','", "in", "value", ":", "raise", "ValueError", "(", "'value should not contain a comma '", "'for field `data_period_start_day`'", ")", "self", ".", "_data_period_start_day", "=", "value" ]
Corresponds to IDD Field `data_period_start_day` Args: value (str): value for IDD Field `data_period_start_day` if `value` is None it will not be checked against the specification and is assumed to be a missing value Raises: ValueError: if `value` is not a valid value
[ "Corresponds", "to", "IDD", "Field", "data_period_start_day" ]
373d4d3c8386c8d35789f086ac5f6018c2711745
https://github.com/rbuffat/pyepw/blob/373d4d3c8386c8d35789f086ac5f6018c2711745/pyepw/epw.py#L5270-L5293
train
rbuffat/pyepw
pyepw/epw.py
DataPeriod.data_period_end_day
def data_period_end_day(self, value=None): """Corresponds to IDD Field `data_period_end_day` Args: value (str): value for IDD Field `data_period_end_day` if `value` is None it will not be checked against the specification and is assumed to be a missing value Raises: ValueError: if `value` is not a valid value """ if value is not None: try: value = str(value) except ValueError: raise ValueError( 'value {} need to be of type str ' 'for field `data_period_end_day`'.format(value)) if ',' in value: raise ValueError('value should not contain a comma ' 'for field `data_period_end_day`') self._data_period_end_day = value
python
def data_period_end_day(self, value=None): """Corresponds to IDD Field `data_period_end_day` Args: value (str): value for IDD Field `data_period_end_day` if `value` is None it will not be checked against the specification and is assumed to be a missing value Raises: ValueError: if `value` is not a valid value """ if value is not None: try: value = str(value) except ValueError: raise ValueError( 'value {} need to be of type str ' 'for field `data_period_end_day`'.format(value)) if ',' in value: raise ValueError('value should not contain a comma ' 'for field `data_period_end_day`') self._data_period_end_day = value
[ "def", "data_period_end_day", "(", "self", ",", "value", "=", "None", ")", ":", "if", "value", "is", "not", "None", ":", "try", ":", "value", "=", "str", "(", "value", ")", "except", "ValueError", ":", "raise", "ValueError", "(", "'value {} need to be of type str '", "'for field `data_period_end_day`'", ".", "format", "(", "value", ")", ")", "if", "','", "in", "value", ":", "raise", "ValueError", "(", "'value should not contain a comma '", "'for field `data_period_end_day`'", ")", "self", ".", "_data_period_end_day", "=", "value" ]
Corresponds to IDD Field `data_period_end_day` Args: value (str): value for IDD Field `data_period_end_day` if `value` is None it will not be checked against the specification and is assumed to be a missing value Raises: ValueError: if `value` is not a valid value
[ "Corresponds", "to", "IDD", "Field", "data_period_end_day" ]
373d4d3c8386c8d35789f086ac5f6018c2711745
https://github.com/rbuffat/pyepw/blob/373d4d3c8386c8d35789f086ac5f6018c2711745/pyepw/epw.py#L5306-L5329
train
rbuffat/pyepw
pyepw/epw.py
DataPeriod.export
def export(self, top=True): """Exports object to its string representation. Args: top (bool): if True appends `internal_name` before values. All non list objects should be exported with value top=True, all list objects, that are embedded in as fields inlist objects should be exported with `top`=False Returns: str: The objects string representation """ out = [] if top: out.append(self._internal_name) out.append(self._to_str(self.number_of_records_per_hour)) out.append(self._to_str(self.data_period_name_or_description)) out.append(self._to_str(self.data_period_start_day_of_week)) out.append(self._to_str(self.data_period_start_day)) out.append(self._to_str(self.data_period_end_day)) return ",".join(out)
python
def export(self, top=True): """Exports object to its string representation. Args: top (bool): if True appends `internal_name` before values. All non list objects should be exported with value top=True, all list objects, that are embedded in as fields inlist objects should be exported with `top`=False Returns: str: The objects string representation """ out = [] if top: out.append(self._internal_name) out.append(self._to_str(self.number_of_records_per_hour)) out.append(self._to_str(self.data_period_name_or_description)) out.append(self._to_str(self.data_period_start_day_of_week)) out.append(self._to_str(self.data_period_start_day)) out.append(self._to_str(self.data_period_end_day)) return ",".join(out)
[ "def", "export", "(", "self", ",", "top", "=", "True", ")", ":", "out", "=", "[", "]", "if", "top", ":", "out", ".", "append", "(", "self", ".", "_internal_name", ")", "out", ".", "append", "(", "self", ".", "_to_str", "(", "self", ".", "number_of_records_per_hour", ")", ")", "out", ".", "append", "(", "self", ".", "_to_str", "(", "self", ".", "data_period_name_or_description", ")", ")", "out", ".", "append", "(", "self", ".", "_to_str", "(", "self", ".", "data_period_start_day_of_week", ")", ")", "out", ".", "append", "(", "self", ".", "_to_str", "(", "self", ".", "data_period_start_day", ")", ")", "out", ".", "append", "(", "self", ".", "_to_str", "(", "self", ".", "data_period_end_day", ")", ")", "return", "\",\"", ".", "join", "(", "out", ")" ]
Exports object to its string representation. Args: top (bool): if True appends `internal_name` before values. All non list objects should be exported with value top=True, all list objects, that are embedded in as fields inlist objects should be exported with `top`=False Returns: str: The objects string representation
[ "Exports", "object", "to", "its", "string", "representation", "." ]
373d4d3c8386c8d35789f086ac5f6018c2711745
https://github.com/rbuffat/pyepw/blob/373d4d3c8386c8d35789f086ac5f6018c2711745/pyepw/epw.py#L5344-L5365
train
rbuffat/pyepw
pyepw/epw.py
DataPeriods.read
def read(self, vals): """Read values. Args: vals (list): list of strings representing values """ i = 0 count = int(vals[i]) i += 1 for _ in range(count): obj = DataPeriod() obj.read(vals[i:i + obj.field_count]) self.add_data_period(obj) i += obj.field_count
python
def read(self, vals): """Read values. Args: vals (list): list of strings representing values """ i = 0 count = int(vals[i]) i += 1 for _ in range(count): obj = DataPeriod() obj.read(vals[i:i + obj.field_count]) self.add_data_period(obj) i += obj.field_count
[ "def", "read", "(", "self", ",", "vals", ")", ":", "i", "=", "0", "count", "=", "int", "(", "vals", "[", "i", "]", ")", "i", "+=", "1", "for", "_", "in", "range", "(", "count", ")", ":", "obj", "=", "DataPeriod", "(", ")", "obj", ".", "read", "(", "vals", "[", "i", ":", "i", "+", "obj", ".", "field_count", "]", ")", "self", ".", "add_data_period", "(", "obj", ")", "i", "+=", "obj", ".", "field_count" ]
Read values. Args: vals (list): list of strings representing values
[ "Read", "values", "." ]
373d4d3c8386c8d35789f086ac5f6018c2711745
https://github.com/rbuffat/pyepw/blob/373d4d3c8386c8d35789f086ac5f6018c2711745/pyepw/epw.py#L5381-L5395
train
rbuffat/pyepw
pyepw/epw.py
WeatherData.read
def read(self, vals): """Read values. Args: vals (list): list of strings representing values """ i = 0 if len(vals[i]) == 0: self.year = None else: self.year = vals[i] i += 1 if len(vals[i]) == 0: self.month = None else: self.month = vals[i] i += 1 if len(vals[i]) == 0: self.day = None else: self.day = vals[i] i += 1 if len(vals[i]) == 0: self.hour = None else: self.hour = vals[i] i += 1 if len(vals[i]) == 0: self.minute = None else: self.minute = vals[i] i += 1 if len(vals[i]) == 0: self.data_source_and_uncertainty_flags = None else: self.data_source_and_uncertainty_flags = vals[i] i += 1 if len(vals[i]) == 0: self.dry_bulb_temperature = None else: self.dry_bulb_temperature = vals[i] i += 1 if len(vals[i]) == 0: self.dew_point_temperature = None else: self.dew_point_temperature = vals[i] i += 1 if len(vals[i]) == 0: self.relative_humidity = None else: self.relative_humidity = vals[i] i += 1 if len(vals[i]) == 0: self.atmospheric_station_pressure = None else: self.atmospheric_station_pressure = vals[i] i += 1 if len(vals[i]) == 0: self.extraterrestrial_horizontal_radiation = None else: self.extraterrestrial_horizontal_radiation = vals[i] i += 1 if len(vals[i]) == 0: self.extraterrestrial_direct_normal_radiation = None else: self.extraterrestrial_direct_normal_radiation = vals[i] i += 1 if len(vals[i]) == 0: self.horizontal_infrared_radiation_intensity = None else: self.horizontal_infrared_radiation_intensity = vals[i] i += 1 if len(vals[i]) == 0: self.global_horizontal_radiation = None else: self.global_horizontal_radiation = vals[i] i += 1 if len(vals[i]) == 0: self.direct_normal_radiation = None else: self.direct_normal_radiation = vals[i] i += 1 if len(vals[i]) == 0: self.diffuse_horizontal_radiation = None else: self.diffuse_horizontal_radiation = vals[i] i += 1 if len(vals[i]) == 0: self.global_horizontal_illuminance = None else: self.global_horizontal_illuminance = vals[i] i += 1 if len(vals[i]) == 0: self.direct_normal_illuminance = None else: self.direct_normal_illuminance = vals[i] i += 1 if len(vals[i]) == 0: self.diffuse_horizontal_illuminance = None else: self.diffuse_horizontal_illuminance = vals[i] i += 1 if len(vals[i]) == 0: self.zenith_luminance = None else: self.zenith_luminance = vals[i] i += 1 if len(vals[i]) == 0: self.wind_direction = None else: self.wind_direction = vals[i] i += 1 if len(vals[i]) == 0: self.wind_speed = None else: self.wind_speed = vals[i] i += 1 if len(vals[i]) == 0: self.total_sky_cover = None else: self.total_sky_cover = vals[i] i += 1 if len(vals[i]) == 0: self.opaque_sky_cover = None else: self.opaque_sky_cover = vals[i] i += 1 if len(vals[i]) == 0: self.visibility = None else: self.visibility = vals[i] i += 1 if len(vals[i]) == 0: self.ceiling_height = None else: self.ceiling_height = vals[i] i += 1 if len(vals[i]) == 0: self.present_weather_observation = None else: self.present_weather_observation = vals[i] i += 1 if len(vals[i]) == 0: self.present_weather_codes = None else: self.present_weather_codes = vals[i] i += 1 if len(vals[i]) == 0: self.precipitable_water = None else: self.precipitable_water = vals[i] i += 1 if len(vals[i]) == 0: self.aerosol_optical_depth = None else: self.aerosol_optical_depth = vals[i] i += 1 if len(vals[i]) == 0: self.snow_depth = None else: self.snow_depth = vals[i] i += 1 if len(vals[i]) == 0: self.days_since_last_snowfall = None else: self.days_since_last_snowfall = vals[i] i += 1 if len(vals[i]) == 0: self.albedo = None else: self.albedo = vals[i] i += 1 if len(vals[i]) == 0: self.liquid_precipitation_depth = None else: self.liquid_precipitation_depth = vals[i] i += 1 if len(vals[i]) == 0: self.liquid_precipitation_quantity = None else: self.liquid_precipitation_quantity = vals[i] i += 1
python
def read(self, vals): """Read values. Args: vals (list): list of strings representing values """ i = 0 if len(vals[i]) == 0: self.year = None else: self.year = vals[i] i += 1 if len(vals[i]) == 0: self.month = None else: self.month = vals[i] i += 1 if len(vals[i]) == 0: self.day = None else: self.day = vals[i] i += 1 if len(vals[i]) == 0: self.hour = None else: self.hour = vals[i] i += 1 if len(vals[i]) == 0: self.minute = None else: self.minute = vals[i] i += 1 if len(vals[i]) == 0: self.data_source_and_uncertainty_flags = None else: self.data_source_and_uncertainty_flags = vals[i] i += 1 if len(vals[i]) == 0: self.dry_bulb_temperature = None else: self.dry_bulb_temperature = vals[i] i += 1 if len(vals[i]) == 0: self.dew_point_temperature = None else: self.dew_point_temperature = vals[i] i += 1 if len(vals[i]) == 0: self.relative_humidity = None else: self.relative_humidity = vals[i] i += 1 if len(vals[i]) == 0: self.atmospheric_station_pressure = None else: self.atmospheric_station_pressure = vals[i] i += 1 if len(vals[i]) == 0: self.extraterrestrial_horizontal_radiation = None else: self.extraterrestrial_horizontal_radiation = vals[i] i += 1 if len(vals[i]) == 0: self.extraterrestrial_direct_normal_radiation = None else: self.extraterrestrial_direct_normal_radiation = vals[i] i += 1 if len(vals[i]) == 0: self.horizontal_infrared_radiation_intensity = None else: self.horizontal_infrared_radiation_intensity = vals[i] i += 1 if len(vals[i]) == 0: self.global_horizontal_radiation = None else: self.global_horizontal_radiation = vals[i] i += 1 if len(vals[i]) == 0: self.direct_normal_radiation = None else: self.direct_normal_radiation = vals[i] i += 1 if len(vals[i]) == 0: self.diffuse_horizontal_radiation = None else: self.diffuse_horizontal_radiation = vals[i] i += 1 if len(vals[i]) == 0: self.global_horizontal_illuminance = None else: self.global_horizontal_illuminance = vals[i] i += 1 if len(vals[i]) == 0: self.direct_normal_illuminance = None else: self.direct_normal_illuminance = vals[i] i += 1 if len(vals[i]) == 0: self.diffuse_horizontal_illuminance = None else: self.diffuse_horizontal_illuminance = vals[i] i += 1 if len(vals[i]) == 0: self.zenith_luminance = None else: self.zenith_luminance = vals[i] i += 1 if len(vals[i]) == 0: self.wind_direction = None else: self.wind_direction = vals[i] i += 1 if len(vals[i]) == 0: self.wind_speed = None else: self.wind_speed = vals[i] i += 1 if len(vals[i]) == 0: self.total_sky_cover = None else: self.total_sky_cover = vals[i] i += 1 if len(vals[i]) == 0: self.opaque_sky_cover = None else: self.opaque_sky_cover = vals[i] i += 1 if len(vals[i]) == 0: self.visibility = None else: self.visibility = vals[i] i += 1 if len(vals[i]) == 0: self.ceiling_height = None else: self.ceiling_height = vals[i] i += 1 if len(vals[i]) == 0: self.present_weather_observation = None else: self.present_weather_observation = vals[i] i += 1 if len(vals[i]) == 0: self.present_weather_codes = None else: self.present_weather_codes = vals[i] i += 1 if len(vals[i]) == 0: self.precipitable_water = None else: self.precipitable_water = vals[i] i += 1 if len(vals[i]) == 0: self.aerosol_optical_depth = None else: self.aerosol_optical_depth = vals[i] i += 1 if len(vals[i]) == 0: self.snow_depth = None else: self.snow_depth = vals[i] i += 1 if len(vals[i]) == 0: self.days_since_last_snowfall = None else: self.days_since_last_snowfall = vals[i] i += 1 if len(vals[i]) == 0: self.albedo = None else: self.albedo = vals[i] i += 1 if len(vals[i]) == 0: self.liquid_precipitation_depth = None else: self.liquid_precipitation_depth = vals[i] i += 1 if len(vals[i]) == 0: self.liquid_precipitation_quantity = None else: self.liquid_precipitation_quantity = vals[i] i += 1
[ "def", "read", "(", "self", ",", "vals", ")", ":", "i", "=", "0", "if", "len", "(", "vals", "[", "i", "]", ")", "==", "0", ":", "self", ".", "year", "=", "None", "else", ":", "self", ".", "year", "=", "vals", "[", "i", "]", "i", "+=", "1", "if", "len", "(", "vals", "[", "i", "]", ")", "==", "0", ":", "self", ".", "month", "=", "None", "else", ":", "self", ".", "month", "=", "vals", "[", "i", "]", "i", "+=", "1", "if", "len", "(", "vals", "[", "i", "]", ")", "==", "0", ":", "self", ".", "day", "=", "None", "else", ":", "self", ".", "day", "=", "vals", "[", "i", "]", "i", "+=", "1", "if", "len", "(", "vals", "[", "i", "]", ")", "==", "0", ":", "self", ".", "hour", "=", "None", "else", ":", "self", ".", "hour", "=", "vals", "[", "i", "]", "i", "+=", "1", "if", "len", "(", "vals", "[", "i", "]", ")", "==", "0", ":", "self", ".", "minute", "=", "None", "else", ":", "self", ".", "minute", "=", "vals", "[", "i", "]", "i", "+=", "1", "if", "len", "(", "vals", "[", "i", "]", ")", "==", "0", ":", "self", ".", "data_source_and_uncertainty_flags", "=", "None", "else", ":", "self", ".", "data_source_and_uncertainty_flags", "=", "vals", "[", "i", "]", "i", "+=", "1", "if", "len", "(", "vals", "[", "i", "]", ")", "==", "0", ":", "self", ".", "dry_bulb_temperature", "=", "None", "else", ":", "self", ".", "dry_bulb_temperature", "=", "vals", "[", "i", "]", "i", "+=", "1", "if", "len", "(", "vals", "[", "i", "]", ")", "==", "0", ":", "self", ".", "dew_point_temperature", "=", "None", "else", ":", "self", ".", "dew_point_temperature", "=", "vals", "[", "i", "]", "i", "+=", "1", "if", "len", "(", "vals", "[", "i", "]", ")", "==", "0", ":", "self", ".", "relative_humidity", "=", "None", "else", ":", "self", ".", "relative_humidity", "=", "vals", "[", "i", "]", "i", "+=", "1", "if", "len", "(", "vals", "[", "i", "]", ")", "==", "0", ":", "self", ".", "atmospheric_station_pressure", "=", "None", "else", ":", "self", ".", "atmospheric_station_pressure", "=", "vals", "[", "i", "]", "i", "+=", "1", "if", "len", "(", "vals", "[", "i", "]", ")", "==", "0", ":", "self", ".", "extraterrestrial_horizontal_radiation", "=", "None", "else", ":", "self", ".", "extraterrestrial_horizontal_radiation", "=", "vals", "[", "i", "]", "i", "+=", "1", "if", "len", "(", "vals", "[", "i", "]", ")", "==", "0", ":", "self", ".", "extraterrestrial_direct_normal_radiation", "=", "None", "else", ":", "self", ".", "extraterrestrial_direct_normal_radiation", "=", "vals", "[", "i", "]", "i", "+=", "1", "if", "len", "(", "vals", "[", "i", "]", ")", "==", "0", ":", "self", ".", "horizontal_infrared_radiation_intensity", "=", "None", "else", ":", "self", ".", "horizontal_infrared_radiation_intensity", "=", "vals", "[", "i", "]", "i", "+=", "1", "if", "len", "(", "vals", "[", "i", "]", ")", "==", "0", ":", "self", ".", "global_horizontal_radiation", "=", "None", "else", ":", "self", ".", "global_horizontal_radiation", "=", "vals", "[", "i", "]", "i", "+=", "1", "if", "len", "(", "vals", "[", "i", "]", ")", "==", "0", ":", "self", ".", "direct_normal_radiation", "=", "None", "else", ":", "self", ".", "direct_normal_radiation", "=", "vals", "[", "i", "]", "i", "+=", "1", "if", "len", "(", "vals", "[", "i", "]", ")", "==", "0", ":", "self", ".", "diffuse_horizontal_radiation", "=", "None", "else", ":", "self", ".", "diffuse_horizontal_radiation", "=", "vals", "[", "i", "]", "i", "+=", "1", "if", "len", "(", "vals", "[", "i", "]", ")", "==", "0", ":", "self", ".", "global_horizontal_illuminance", "=", "None", "else", ":", "self", ".", "global_horizontal_illuminance", "=", "vals", "[", "i", "]", "i", "+=", "1", "if", "len", "(", "vals", "[", "i", "]", ")", "==", "0", ":", "self", ".", "direct_normal_illuminance", "=", "None", "else", ":", "self", ".", "direct_normal_illuminance", "=", "vals", "[", "i", "]", "i", "+=", "1", "if", "len", "(", "vals", "[", "i", "]", ")", "==", "0", ":", "self", ".", "diffuse_horizontal_illuminance", "=", "None", "else", ":", "self", ".", "diffuse_horizontal_illuminance", "=", "vals", "[", "i", "]", "i", "+=", "1", "if", "len", "(", "vals", "[", "i", "]", ")", "==", "0", ":", "self", ".", "zenith_luminance", "=", "None", "else", ":", "self", ".", "zenith_luminance", "=", "vals", "[", "i", "]", "i", "+=", "1", "if", "len", "(", "vals", "[", "i", "]", ")", "==", "0", ":", "self", ".", "wind_direction", "=", "None", "else", ":", "self", ".", "wind_direction", "=", "vals", "[", "i", "]", "i", "+=", "1", "if", "len", "(", "vals", "[", "i", "]", ")", "==", "0", ":", "self", ".", "wind_speed", "=", "None", "else", ":", "self", ".", "wind_speed", "=", "vals", "[", "i", "]", "i", "+=", "1", "if", "len", "(", "vals", "[", "i", "]", ")", "==", "0", ":", "self", ".", "total_sky_cover", "=", "None", "else", ":", "self", ".", "total_sky_cover", "=", "vals", "[", "i", "]", "i", "+=", "1", "if", "len", "(", "vals", "[", "i", "]", ")", "==", "0", ":", "self", ".", "opaque_sky_cover", "=", "None", "else", ":", "self", ".", "opaque_sky_cover", "=", "vals", "[", "i", "]", "i", "+=", "1", "if", "len", "(", "vals", "[", "i", "]", ")", "==", "0", ":", "self", ".", "visibility", "=", "None", "else", ":", "self", ".", "visibility", "=", "vals", "[", "i", "]", "i", "+=", "1", "if", "len", "(", "vals", "[", "i", "]", ")", "==", "0", ":", "self", ".", "ceiling_height", "=", "None", "else", ":", "self", ".", "ceiling_height", "=", "vals", "[", "i", "]", "i", "+=", "1", "if", "len", "(", "vals", "[", "i", "]", ")", "==", "0", ":", "self", ".", "present_weather_observation", "=", "None", "else", ":", "self", ".", "present_weather_observation", "=", "vals", "[", "i", "]", "i", "+=", "1", "if", "len", "(", "vals", "[", "i", "]", ")", "==", "0", ":", "self", ".", "present_weather_codes", "=", "None", "else", ":", "self", ".", "present_weather_codes", "=", "vals", "[", "i", "]", "i", "+=", "1", "if", "len", "(", "vals", "[", "i", "]", ")", "==", "0", ":", "self", ".", "precipitable_water", "=", "None", "else", ":", "self", ".", "precipitable_water", "=", "vals", "[", "i", "]", "i", "+=", "1", "if", "len", "(", "vals", "[", "i", "]", ")", "==", "0", ":", "self", ".", "aerosol_optical_depth", "=", "None", "else", ":", "self", ".", "aerosol_optical_depth", "=", "vals", "[", "i", "]", "i", "+=", "1", "if", "len", "(", "vals", "[", "i", "]", ")", "==", "0", ":", "self", ".", "snow_depth", "=", "None", "else", ":", "self", ".", "snow_depth", "=", "vals", "[", "i", "]", "i", "+=", "1", "if", "len", "(", "vals", "[", "i", "]", ")", "==", "0", ":", "self", ".", "days_since_last_snowfall", "=", "None", "else", ":", "self", ".", "days_since_last_snowfall", "=", "vals", "[", "i", "]", "i", "+=", "1", "if", "len", "(", "vals", "[", "i", "]", ")", "==", "0", ":", "self", ".", "albedo", "=", "None", "else", ":", "self", ".", "albedo", "=", "vals", "[", "i", "]", "i", "+=", "1", "if", "len", "(", "vals", "[", "i", "]", ")", "==", "0", ":", "self", ".", "liquid_precipitation_depth", "=", "None", "else", ":", "self", ".", "liquid_precipitation_depth", "=", "vals", "[", "i", "]", "i", "+=", "1", "if", "len", "(", "vals", "[", "i", "]", ")", "==", "0", ":", "self", ".", "liquid_precipitation_quantity", "=", "None", "else", ":", "self", ".", "liquid_precipitation_quantity", "=", "vals", "[", "i", "]", "i", "+=", "1" ]
Read values. Args: vals (list): list of strings representing values
[ "Read", "values", "." ]
373d4d3c8386c8d35789f086ac5f6018c2711745
https://github.com/rbuffat/pyepw/blob/373d4d3c8386c8d35789f086ac5f6018c2711745/pyepw/epw.py#L5498-L5680
train
rbuffat/pyepw
pyepw/epw.py
WeatherData.year
def year(self, value=None): """Corresponds to IDD Field `year` Args: value (int): value for IDD Field `year` if `value` is None it will not be checked against the specification and is assumed to be a missing value Raises: ValueError: if `value` is not a valid value """ if value is not None: try: value = int(value) except ValueError: raise ValueError('value {} need to be of type int ' 'for field `year`'.format(value)) self._year = value
python
def year(self, value=None): """Corresponds to IDD Field `year` Args: value (int): value for IDD Field `year` if `value` is None it will not be checked against the specification and is assumed to be a missing value Raises: ValueError: if `value` is not a valid value """ if value is not None: try: value = int(value) except ValueError: raise ValueError('value {} need to be of type int ' 'for field `year`'.format(value)) self._year = value
[ "def", "year", "(", "self", ",", "value", "=", "None", ")", ":", "if", "value", "is", "not", "None", ":", "try", ":", "value", "=", "int", "(", "value", ")", "except", "ValueError", ":", "raise", "ValueError", "(", "'value {} need to be of type int '", "'for field `year`'", ".", "format", "(", "value", ")", ")", "self", ".", "_year", "=", "value" ]
Corresponds to IDD Field `year` Args: value (int): value for IDD Field `year` if `value` is None it will not be checked against the specification and is assumed to be a missing value Raises: ValueError: if `value` is not a valid value
[ "Corresponds", "to", "IDD", "Field", "year" ]
373d4d3c8386c8d35789f086ac5f6018c2711745
https://github.com/rbuffat/pyepw/blob/373d4d3c8386c8d35789f086ac5f6018c2711745/pyepw/epw.py#L5693-L5712
train
rbuffat/pyepw
pyepw/epw.py
WeatherData.month
def month(self, value=None): """Corresponds to IDD Field `month` Args: value (int): value for IDD Field `month` value >= 1 value <= 12 if `value` is None it will not be checked against the specification and is assumed to be a missing value Raises: ValueError: if `value` is not a valid value """ if value is not None: try: value = int(value) except ValueError: raise ValueError('value {} need to be of type int ' 'for field `month`'.format(value)) if value < 1: raise ValueError('value need to be greater or equal 1 ' 'for field `month`') if value > 12: raise ValueError('value need to be smaller 12 ' 'for field `month`') self._month = value
python
def month(self, value=None): """Corresponds to IDD Field `month` Args: value (int): value for IDD Field `month` value >= 1 value <= 12 if `value` is None it will not be checked against the specification and is assumed to be a missing value Raises: ValueError: if `value` is not a valid value """ if value is not None: try: value = int(value) except ValueError: raise ValueError('value {} need to be of type int ' 'for field `month`'.format(value)) if value < 1: raise ValueError('value need to be greater or equal 1 ' 'for field `month`') if value > 12: raise ValueError('value need to be smaller 12 ' 'for field `month`') self._month = value
[ "def", "month", "(", "self", ",", "value", "=", "None", ")", ":", "if", "value", "is", "not", "None", ":", "try", ":", "value", "=", "int", "(", "value", ")", "except", "ValueError", ":", "raise", "ValueError", "(", "'value {} need to be of type int '", "'for field `month`'", ".", "format", "(", "value", ")", ")", "if", "value", "<", "1", ":", "raise", "ValueError", "(", "'value need to be greater or equal 1 '", "'for field `month`'", ")", "if", "value", ">", "12", ":", "raise", "ValueError", "(", "'value need to be smaller 12 '", "'for field `month`'", ")", "self", ".", "_month", "=", "value" ]
Corresponds to IDD Field `month` Args: value (int): value for IDD Field `month` value >= 1 value <= 12 if `value` is None it will not be checked against the specification and is assumed to be a missing value Raises: ValueError: if `value` is not a valid value
[ "Corresponds", "to", "IDD", "Field", "month" ]
373d4d3c8386c8d35789f086ac5f6018c2711745
https://github.com/rbuffat/pyepw/blob/373d4d3c8386c8d35789f086ac5f6018c2711745/pyepw/epw.py#L5725-L5752
train
rbuffat/pyepw
pyepw/epw.py
WeatherData.day
def day(self, value=None): """Corresponds to IDD Field `day` Args: value (int): value for IDD Field `day` value >= 1 value <= 31 if `value` is None it will not be checked against the specification and is assumed to be a missing value Raises: ValueError: if `value` is not a valid value """ if value is not None: try: value = int(value) except ValueError: raise ValueError('value {} need to be of type int ' 'for field `day`'.format(value)) if value < 1: raise ValueError('value need to be greater or equal 1 ' 'for field `day`') if value > 31: raise ValueError('value need to be smaller 31 ' 'for field `day`') self._day = value
python
def day(self, value=None): """Corresponds to IDD Field `day` Args: value (int): value for IDD Field `day` value >= 1 value <= 31 if `value` is None it will not be checked against the specification and is assumed to be a missing value Raises: ValueError: if `value` is not a valid value """ if value is not None: try: value = int(value) except ValueError: raise ValueError('value {} need to be of type int ' 'for field `day`'.format(value)) if value < 1: raise ValueError('value need to be greater or equal 1 ' 'for field `day`') if value > 31: raise ValueError('value need to be smaller 31 ' 'for field `day`') self._day = value
[ "def", "day", "(", "self", ",", "value", "=", "None", ")", ":", "if", "value", "is", "not", "None", ":", "try", ":", "value", "=", "int", "(", "value", ")", "except", "ValueError", ":", "raise", "ValueError", "(", "'value {} need to be of type int '", "'for field `day`'", ".", "format", "(", "value", ")", ")", "if", "value", "<", "1", ":", "raise", "ValueError", "(", "'value need to be greater or equal 1 '", "'for field `day`'", ")", "if", "value", ">", "31", ":", "raise", "ValueError", "(", "'value need to be smaller 31 '", "'for field `day`'", ")", "self", ".", "_day", "=", "value" ]
Corresponds to IDD Field `day` Args: value (int): value for IDD Field `day` value >= 1 value <= 31 if `value` is None it will not be checked against the specification and is assumed to be a missing value Raises: ValueError: if `value` is not a valid value
[ "Corresponds", "to", "IDD", "Field", "day" ]
373d4d3c8386c8d35789f086ac5f6018c2711745
https://github.com/rbuffat/pyepw/blob/373d4d3c8386c8d35789f086ac5f6018c2711745/pyepw/epw.py#L5765-L5792
train
rbuffat/pyepw
pyepw/epw.py
WeatherData.hour
def hour(self, value=None): """Corresponds to IDD Field `hour` Args: value (int): value for IDD Field `hour` value >= 1 value <= 24 if `value` is None it will not be checked against the specification and is assumed to be a missing value Raises: ValueError: if `value` is not a valid value """ if value is not None: try: value = int(value) except ValueError: raise ValueError('value {} need to be of type int ' 'for field `hour`'.format(value)) if value < 1: raise ValueError('value need to be greater or equal 1 ' 'for field `hour`') if value > 24: raise ValueError('value need to be smaller 24 ' 'for field `hour`') self._hour = value
python
def hour(self, value=None): """Corresponds to IDD Field `hour` Args: value (int): value for IDD Field `hour` value >= 1 value <= 24 if `value` is None it will not be checked against the specification and is assumed to be a missing value Raises: ValueError: if `value` is not a valid value """ if value is not None: try: value = int(value) except ValueError: raise ValueError('value {} need to be of type int ' 'for field `hour`'.format(value)) if value < 1: raise ValueError('value need to be greater or equal 1 ' 'for field `hour`') if value > 24: raise ValueError('value need to be smaller 24 ' 'for field `hour`') self._hour = value
[ "def", "hour", "(", "self", ",", "value", "=", "None", ")", ":", "if", "value", "is", "not", "None", ":", "try", ":", "value", "=", "int", "(", "value", ")", "except", "ValueError", ":", "raise", "ValueError", "(", "'value {} need to be of type int '", "'for field `hour`'", ".", "format", "(", "value", ")", ")", "if", "value", "<", "1", ":", "raise", "ValueError", "(", "'value need to be greater or equal 1 '", "'for field `hour`'", ")", "if", "value", ">", "24", ":", "raise", "ValueError", "(", "'value need to be smaller 24 '", "'for field `hour`'", ")", "self", ".", "_hour", "=", "value" ]
Corresponds to IDD Field `hour` Args: value (int): value for IDD Field `hour` value >= 1 value <= 24 if `value` is None it will not be checked against the specification and is assumed to be a missing value Raises: ValueError: if `value` is not a valid value
[ "Corresponds", "to", "IDD", "Field", "hour" ]
373d4d3c8386c8d35789f086ac5f6018c2711745
https://github.com/rbuffat/pyepw/blob/373d4d3c8386c8d35789f086ac5f6018c2711745/pyepw/epw.py#L5805-L5832
train
rbuffat/pyepw
pyepw/epw.py
WeatherData.minute
def minute(self, value=None): """Corresponds to IDD Field `minute` Args: value (int): value for IDD Field `minute` value >= 0 value <= 60 if `value` is None it will not be checked against the specification and is assumed to be a missing value Raises: ValueError: if `value` is not a valid value """ if value is not None: try: value = int(value) except ValueError: raise ValueError('value {} need to be of type int ' 'for field `minute`'.format(value)) if value < 0: raise ValueError('value need to be greater or equal 0 ' 'for field `minute`') if value > 60: raise ValueError('value need to be smaller 60 ' 'for field `minute`') self._minute = value
python
def minute(self, value=None): """Corresponds to IDD Field `minute` Args: value (int): value for IDD Field `minute` value >= 0 value <= 60 if `value` is None it will not be checked against the specification and is assumed to be a missing value Raises: ValueError: if `value` is not a valid value """ if value is not None: try: value = int(value) except ValueError: raise ValueError('value {} need to be of type int ' 'for field `minute`'.format(value)) if value < 0: raise ValueError('value need to be greater or equal 0 ' 'for field `minute`') if value > 60: raise ValueError('value need to be smaller 60 ' 'for field `minute`') self._minute = value
[ "def", "minute", "(", "self", ",", "value", "=", "None", ")", ":", "if", "value", "is", "not", "None", ":", "try", ":", "value", "=", "int", "(", "value", ")", "except", "ValueError", ":", "raise", "ValueError", "(", "'value {} need to be of type int '", "'for field `minute`'", ".", "format", "(", "value", ")", ")", "if", "value", "<", "0", ":", "raise", "ValueError", "(", "'value need to be greater or equal 0 '", "'for field `minute`'", ")", "if", "value", ">", "60", ":", "raise", "ValueError", "(", "'value need to be smaller 60 '", "'for field `minute`'", ")", "self", ".", "_minute", "=", "value" ]
Corresponds to IDD Field `minute` Args: value (int): value for IDD Field `minute` value >= 0 value <= 60 if `value` is None it will not be checked against the specification and is assumed to be a missing value Raises: ValueError: if `value` is not a valid value
[ "Corresponds", "to", "IDD", "Field", "minute" ]
373d4d3c8386c8d35789f086ac5f6018c2711745
https://github.com/rbuffat/pyepw/blob/373d4d3c8386c8d35789f086ac5f6018c2711745/pyepw/epw.py#L5845-L5872
train
rbuffat/pyepw
pyepw/epw.py
WeatherData.data_source_and_uncertainty_flags
def data_source_and_uncertainty_flags(self, value=None): """Corresponds to IDD Field `data_source_and_uncertainty_flags` Initial day of weather file is checked by EnergyPlus for validity (as shown below) Each field is checked for "missing" as shown below. Reasonable values, calculated values or the last "good" value is substituted. Args: value (str): value for IDD Field `data_source_and_uncertainty_flags` if `value` is None it will not be checked against the specification and is assumed to be a missing value Raises: ValueError: if `value` is not a valid value """ if value is not None: try: value = str(value) except ValueError: raise ValueError( 'value {} need to be of type str ' 'for field `data_source_and_uncertainty_flags`'.format(value)) if ',' in value: raise ValueError( 'value should not contain a comma ' 'for field `data_source_and_uncertainty_flags`') self._data_source_and_uncertainty_flags = value
python
def data_source_and_uncertainty_flags(self, value=None): """Corresponds to IDD Field `data_source_and_uncertainty_flags` Initial day of weather file is checked by EnergyPlus for validity (as shown below) Each field is checked for "missing" as shown below. Reasonable values, calculated values or the last "good" value is substituted. Args: value (str): value for IDD Field `data_source_and_uncertainty_flags` if `value` is None it will not be checked against the specification and is assumed to be a missing value Raises: ValueError: if `value` is not a valid value """ if value is not None: try: value = str(value) except ValueError: raise ValueError( 'value {} need to be of type str ' 'for field `data_source_and_uncertainty_flags`'.format(value)) if ',' in value: raise ValueError( 'value should not contain a comma ' 'for field `data_source_and_uncertainty_flags`') self._data_source_and_uncertainty_flags = value
[ "def", "data_source_and_uncertainty_flags", "(", "self", ",", "value", "=", "None", ")", ":", "if", "value", "is", "not", "None", ":", "try", ":", "value", "=", "str", "(", "value", ")", "except", "ValueError", ":", "raise", "ValueError", "(", "'value {} need to be of type str '", "'for field `data_source_and_uncertainty_flags`'", ".", "format", "(", "value", ")", ")", "if", "','", "in", "value", ":", "raise", "ValueError", "(", "'value should not contain a comma '", "'for field `data_source_and_uncertainty_flags`'", ")", "self", ".", "_data_source_and_uncertainty_flags", "=", "value" ]
Corresponds to IDD Field `data_source_and_uncertainty_flags` Initial day of weather file is checked by EnergyPlus for validity (as shown below) Each field is checked for "missing" as shown below. Reasonable values, calculated values or the last "good" value is substituted. Args: value (str): value for IDD Field `data_source_and_uncertainty_flags` if `value` is None it will not be checked against the specification and is assumed to be a missing value Raises: ValueError: if `value` is not a valid value
[ "Corresponds", "to", "IDD", "Field", "data_source_and_uncertainty_flags", "Initial", "day", "of", "weather", "file", "is", "checked", "by", "EnergyPlus", "for", "validity", "(", "as", "shown", "below", ")", "Each", "field", "is", "checked", "for", "missing", "as", "shown", "below", ".", "Reasonable", "values", "calculated", "values", "or", "the", "last", "good", "value", "is", "substituted", "." ]
373d4d3c8386c8d35789f086ac5f6018c2711745
https://github.com/rbuffat/pyepw/blob/373d4d3c8386c8d35789f086ac5f6018c2711745/pyepw/epw.py#L5885-L5912
train
rbuffat/pyepw
pyepw/epw.py
WeatherData.dry_bulb_temperature
def dry_bulb_temperature(self, value=99.9): """Corresponds to IDD Field `dry_bulb_temperature` Args: value (float): value for IDD Field `dry_bulb_temperature` Unit: C value > -70.0 value < 70.0 Missing value: 99.9 if `value` is None it will not be checked against the specification and is assumed to be a missing value Raises: ValueError: if `value` is not a valid value """ if value is not None: try: value = float(value) except ValueError: raise ValueError( 'value {} need to be of type float ' 'for field `dry_bulb_temperature`'.format(value)) if value <= -70.0: raise ValueError('value need to be greater -70.0 ' 'for field `dry_bulb_temperature`') if value >= 70.0: raise ValueError('value need to be smaller 70.0 ' 'for field `dry_bulb_temperature`') self._dry_bulb_temperature = value
python
def dry_bulb_temperature(self, value=99.9): """Corresponds to IDD Field `dry_bulb_temperature` Args: value (float): value for IDD Field `dry_bulb_temperature` Unit: C value > -70.0 value < 70.0 Missing value: 99.9 if `value` is None it will not be checked against the specification and is assumed to be a missing value Raises: ValueError: if `value` is not a valid value """ if value is not None: try: value = float(value) except ValueError: raise ValueError( 'value {} need to be of type float ' 'for field `dry_bulb_temperature`'.format(value)) if value <= -70.0: raise ValueError('value need to be greater -70.0 ' 'for field `dry_bulb_temperature`') if value >= 70.0: raise ValueError('value need to be smaller 70.0 ' 'for field `dry_bulb_temperature`') self._dry_bulb_temperature = value
[ "def", "dry_bulb_temperature", "(", "self", ",", "value", "=", "99.9", ")", ":", "if", "value", "is", "not", "None", ":", "try", ":", "value", "=", "float", "(", "value", ")", "except", "ValueError", ":", "raise", "ValueError", "(", "'value {} need to be of type float '", "'for field `dry_bulb_temperature`'", ".", "format", "(", "value", ")", ")", "if", "value", "<=", "-", "70.0", ":", "raise", "ValueError", "(", "'value need to be greater -70.0 '", "'for field `dry_bulb_temperature`'", ")", "if", "value", ">=", "70.0", ":", "raise", "ValueError", "(", "'value need to be smaller 70.0 '", "'for field `dry_bulb_temperature`'", ")", "self", ".", "_dry_bulb_temperature", "=", "value" ]
Corresponds to IDD Field `dry_bulb_temperature` Args: value (float): value for IDD Field `dry_bulb_temperature` Unit: C value > -70.0 value < 70.0 Missing value: 99.9 if `value` is None it will not be checked against the specification and is assumed to be a missing value Raises: ValueError: if `value` is not a valid value
[ "Corresponds", "to", "IDD", "Field", "dry_bulb_temperature" ]
373d4d3c8386c8d35789f086ac5f6018c2711745
https://github.com/rbuffat/pyepw/blob/373d4d3c8386c8d35789f086ac5f6018c2711745/pyepw/epw.py#L5925-L5955
train
rbuffat/pyepw
pyepw/epw.py
WeatherData.dew_point_temperature
def dew_point_temperature(self, value=99.9): """Corresponds to IDD Field `dew_point_temperature` Args: value (float): value for IDD Field `dew_point_temperature` Unit: C value > -70.0 value < 70.0 Missing value: 99.9 if `value` is None it will not be checked against the specification and is assumed to be a missing value Raises: ValueError: if `value` is not a valid value """ if value is not None: try: value = float(value) except ValueError: raise ValueError( 'value {} need to be of type float ' 'for field `dew_point_temperature`'.format(value)) if value <= -70.0: raise ValueError('value need to be greater -70.0 ' 'for field `dew_point_temperature`') if value >= 70.0: raise ValueError('value need to be smaller 70.0 ' 'for field `dew_point_temperature`') self._dew_point_temperature = value
python
def dew_point_temperature(self, value=99.9): """Corresponds to IDD Field `dew_point_temperature` Args: value (float): value for IDD Field `dew_point_temperature` Unit: C value > -70.0 value < 70.0 Missing value: 99.9 if `value` is None it will not be checked against the specification and is assumed to be a missing value Raises: ValueError: if `value` is not a valid value """ if value is not None: try: value = float(value) except ValueError: raise ValueError( 'value {} need to be of type float ' 'for field `dew_point_temperature`'.format(value)) if value <= -70.0: raise ValueError('value need to be greater -70.0 ' 'for field `dew_point_temperature`') if value >= 70.0: raise ValueError('value need to be smaller 70.0 ' 'for field `dew_point_temperature`') self._dew_point_temperature = value
[ "def", "dew_point_temperature", "(", "self", ",", "value", "=", "99.9", ")", ":", "if", "value", "is", "not", "None", ":", "try", ":", "value", "=", "float", "(", "value", ")", "except", "ValueError", ":", "raise", "ValueError", "(", "'value {} need to be of type float '", "'for field `dew_point_temperature`'", ".", "format", "(", "value", ")", ")", "if", "value", "<=", "-", "70.0", ":", "raise", "ValueError", "(", "'value need to be greater -70.0 '", "'for field `dew_point_temperature`'", ")", "if", "value", ">=", "70.0", ":", "raise", "ValueError", "(", "'value need to be smaller 70.0 '", "'for field `dew_point_temperature`'", ")", "self", ".", "_dew_point_temperature", "=", "value" ]
Corresponds to IDD Field `dew_point_temperature` Args: value (float): value for IDD Field `dew_point_temperature` Unit: C value > -70.0 value < 70.0 Missing value: 99.9 if `value` is None it will not be checked against the specification and is assumed to be a missing value Raises: ValueError: if `value` is not a valid value
[ "Corresponds", "to", "IDD", "Field", "dew_point_temperature" ]
373d4d3c8386c8d35789f086ac5f6018c2711745
https://github.com/rbuffat/pyepw/blob/373d4d3c8386c8d35789f086ac5f6018c2711745/pyepw/epw.py#L5968-L5998
train
rbuffat/pyepw
pyepw/epw.py
WeatherData.relative_humidity
def relative_humidity(self, value=999): """Corresponds to IDD Field `relative_humidity` Args: value (int): value for IDD Field `relative_humidity` value >= 0 value <= 110 Missing value: 999 if `value` is None it will not be checked against the specification and is assumed to be a missing value Raises: ValueError: if `value` is not a valid value """ if value is not None: try: value = int(value) except ValueError: raise ValueError('value {} need to be of type int ' 'for field `relative_humidity`'.format(value)) if value < 0: raise ValueError('value need to be greater or equal 0 ' 'for field `relative_humidity`') if value > 110: raise ValueError('value need to be smaller 110 ' 'for field `relative_humidity`') self._relative_humidity = value
python
def relative_humidity(self, value=999): """Corresponds to IDD Field `relative_humidity` Args: value (int): value for IDD Field `relative_humidity` value >= 0 value <= 110 Missing value: 999 if `value` is None it will not be checked against the specification and is assumed to be a missing value Raises: ValueError: if `value` is not a valid value """ if value is not None: try: value = int(value) except ValueError: raise ValueError('value {} need to be of type int ' 'for field `relative_humidity`'.format(value)) if value < 0: raise ValueError('value need to be greater or equal 0 ' 'for field `relative_humidity`') if value > 110: raise ValueError('value need to be smaller 110 ' 'for field `relative_humidity`') self._relative_humidity = value
[ "def", "relative_humidity", "(", "self", ",", "value", "=", "999", ")", ":", "if", "value", "is", "not", "None", ":", "try", ":", "value", "=", "int", "(", "value", ")", "except", "ValueError", ":", "raise", "ValueError", "(", "'value {} need to be of type int '", "'for field `relative_humidity`'", ".", "format", "(", "value", ")", ")", "if", "value", "<", "0", ":", "raise", "ValueError", "(", "'value need to be greater or equal 0 '", "'for field `relative_humidity`'", ")", "if", "value", ">", "110", ":", "raise", "ValueError", "(", "'value need to be smaller 110 '", "'for field `relative_humidity`'", ")", "self", ".", "_relative_humidity", "=", "value" ]
Corresponds to IDD Field `relative_humidity` Args: value (int): value for IDD Field `relative_humidity` value >= 0 value <= 110 Missing value: 999 if `value` is None it will not be checked against the specification and is assumed to be a missing value Raises: ValueError: if `value` is not a valid value
[ "Corresponds", "to", "IDD", "Field", "relative_humidity" ]
373d4d3c8386c8d35789f086ac5f6018c2711745
https://github.com/rbuffat/pyepw/blob/373d4d3c8386c8d35789f086ac5f6018c2711745/pyepw/epw.py#L6011-L6039
train
rbuffat/pyepw
pyepw/epw.py
WeatherData.atmospheric_station_pressure
def atmospheric_station_pressure(self, value=999999): """Corresponds to IDD Field `atmospheric_station_pressure` Args: value (int): value for IDD Field `atmospheric_station_pressure` Unit: Pa value > 31000 value < 120000 Missing value: 999999 if `value` is None it will not be checked against the specification and is assumed to be a missing value Raises: ValueError: if `value` is not a valid value """ if value is not None: try: value = int(value) except ValueError: raise ValueError( 'value {} need to be of type int ' 'for field `atmospheric_station_pressure`'.format(value)) if value <= 31000: raise ValueError('value need to be greater 31000 ' 'for field `atmospheric_station_pressure`') if value >= 120000: raise ValueError('value need to be smaller 120000 ' 'for field `atmospheric_station_pressure`') self._atmospheric_station_pressure = value
python
def atmospheric_station_pressure(self, value=999999): """Corresponds to IDD Field `atmospheric_station_pressure` Args: value (int): value for IDD Field `atmospheric_station_pressure` Unit: Pa value > 31000 value < 120000 Missing value: 999999 if `value` is None it will not be checked against the specification and is assumed to be a missing value Raises: ValueError: if `value` is not a valid value """ if value is not None: try: value = int(value) except ValueError: raise ValueError( 'value {} need to be of type int ' 'for field `atmospheric_station_pressure`'.format(value)) if value <= 31000: raise ValueError('value need to be greater 31000 ' 'for field `atmospheric_station_pressure`') if value >= 120000: raise ValueError('value need to be smaller 120000 ' 'for field `atmospheric_station_pressure`') self._atmospheric_station_pressure = value
[ "def", "atmospheric_station_pressure", "(", "self", ",", "value", "=", "999999", ")", ":", "if", "value", "is", "not", "None", ":", "try", ":", "value", "=", "int", "(", "value", ")", "except", "ValueError", ":", "raise", "ValueError", "(", "'value {} need to be of type int '", "'for field `atmospheric_station_pressure`'", ".", "format", "(", "value", ")", ")", "if", "value", "<=", "31000", ":", "raise", "ValueError", "(", "'value need to be greater 31000 '", "'for field `atmospheric_station_pressure`'", ")", "if", "value", ">=", "120000", ":", "raise", "ValueError", "(", "'value need to be smaller 120000 '", "'for field `atmospheric_station_pressure`'", ")", "self", ".", "_atmospheric_station_pressure", "=", "value" ]
Corresponds to IDD Field `atmospheric_station_pressure` Args: value (int): value for IDD Field `atmospheric_station_pressure` Unit: Pa value > 31000 value < 120000 Missing value: 999999 if `value` is None it will not be checked against the specification and is assumed to be a missing value Raises: ValueError: if `value` is not a valid value
[ "Corresponds", "to", "IDD", "Field", "atmospheric_station_pressure" ]
373d4d3c8386c8d35789f086ac5f6018c2711745
https://github.com/rbuffat/pyepw/blob/373d4d3c8386c8d35789f086ac5f6018c2711745/pyepw/epw.py#L6052-L6082
train
rbuffat/pyepw
pyepw/epw.py
WeatherData.extraterrestrial_horizontal_radiation
def extraterrestrial_horizontal_radiation(self, value=9999.0): """Corresponds to IDD Field `extraterrestrial_horizontal_radiation` Args: value (float): value for IDD Field `extraterrestrial_horizontal_radiation` Unit: Wh/m2 value >= 0.0 Missing value: 9999.0 if `value` is None it will not be checked against the specification and is assumed to be a missing value Raises: ValueError: if `value` is not a valid value """ if value is not None: try: value = float(value) except ValueError: raise ValueError( 'value {} need to be of type float ' 'for field `extraterrestrial_horizontal_radiation`'.format(value)) if value < 0.0: raise ValueError( 'value need to be greater or equal 0.0 ' 'for field `extraterrestrial_horizontal_radiation`') self._extraterrestrial_horizontal_radiation = value
python
def extraterrestrial_horizontal_radiation(self, value=9999.0): """Corresponds to IDD Field `extraterrestrial_horizontal_radiation` Args: value (float): value for IDD Field `extraterrestrial_horizontal_radiation` Unit: Wh/m2 value >= 0.0 Missing value: 9999.0 if `value` is None it will not be checked against the specification and is assumed to be a missing value Raises: ValueError: if `value` is not a valid value """ if value is not None: try: value = float(value) except ValueError: raise ValueError( 'value {} need to be of type float ' 'for field `extraterrestrial_horizontal_radiation`'.format(value)) if value < 0.0: raise ValueError( 'value need to be greater or equal 0.0 ' 'for field `extraterrestrial_horizontal_radiation`') self._extraterrestrial_horizontal_radiation = value
[ "def", "extraterrestrial_horizontal_radiation", "(", "self", ",", "value", "=", "9999.0", ")", ":", "if", "value", "is", "not", "None", ":", "try", ":", "value", "=", "float", "(", "value", ")", "except", "ValueError", ":", "raise", "ValueError", "(", "'value {} need to be of type float '", "'for field `extraterrestrial_horizontal_radiation`'", ".", "format", "(", "value", ")", ")", "if", "value", "<", "0.0", ":", "raise", "ValueError", "(", "'value need to be greater or equal 0.0 '", "'for field `extraterrestrial_horizontal_radiation`'", ")", "self", ".", "_extraterrestrial_horizontal_radiation", "=", "value" ]
Corresponds to IDD Field `extraterrestrial_horizontal_radiation` Args: value (float): value for IDD Field `extraterrestrial_horizontal_radiation` Unit: Wh/m2 value >= 0.0 Missing value: 9999.0 if `value` is None it will not be checked against the specification and is assumed to be a missing value Raises: ValueError: if `value` is not a valid value
[ "Corresponds", "to", "IDD", "Field", "extraterrestrial_horizontal_radiation" ]
373d4d3c8386c8d35789f086ac5f6018c2711745
https://github.com/rbuffat/pyepw/blob/373d4d3c8386c8d35789f086ac5f6018c2711745/pyepw/epw.py#L6095-L6122
train
rbuffat/pyepw
pyepw/epw.py
WeatherData.extraterrestrial_direct_normal_radiation
def extraterrestrial_direct_normal_radiation(self, value=9999.0): """Corresponds to IDD Field `extraterrestrial_direct_normal_radiation` Args: value (float): value for IDD Field `extraterrestrial_direct_normal_radiation` Unit: Wh/m2 value >= 0.0 Missing value: 9999.0 if `value` is None it will not be checked against the specification and is assumed to be a missing value Raises: ValueError: if `value` is not a valid value """ if value is not None: try: value = float(value) except ValueError: raise ValueError( 'value {} need to be of type float ' 'for field `extraterrestrial_direct_normal_radiation`'.format(value)) if value < 0.0: raise ValueError( 'value need to be greater or equal 0.0 ' 'for field `extraterrestrial_direct_normal_radiation`') self._extraterrestrial_direct_normal_radiation = value
python
def extraterrestrial_direct_normal_radiation(self, value=9999.0): """Corresponds to IDD Field `extraterrestrial_direct_normal_radiation` Args: value (float): value for IDD Field `extraterrestrial_direct_normal_radiation` Unit: Wh/m2 value >= 0.0 Missing value: 9999.0 if `value` is None it will not be checked against the specification and is assumed to be a missing value Raises: ValueError: if `value` is not a valid value """ if value is not None: try: value = float(value) except ValueError: raise ValueError( 'value {} need to be of type float ' 'for field `extraterrestrial_direct_normal_radiation`'.format(value)) if value < 0.0: raise ValueError( 'value need to be greater or equal 0.0 ' 'for field `extraterrestrial_direct_normal_radiation`') self._extraterrestrial_direct_normal_radiation = value
[ "def", "extraterrestrial_direct_normal_radiation", "(", "self", ",", "value", "=", "9999.0", ")", ":", "if", "value", "is", "not", "None", ":", "try", ":", "value", "=", "float", "(", "value", ")", "except", "ValueError", ":", "raise", "ValueError", "(", "'value {} need to be of type float '", "'for field `extraterrestrial_direct_normal_radiation`'", ".", "format", "(", "value", ")", ")", "if", "value", "<", "0.0", ":", "raise", "ValueError", "(", "'value need to be greater or equal 0.0 '", "'for field `extraterrestrial_direct_normal_radiation`'", ")", "self", ".", "_extraterrestrial_direct_normal_radiation", "=", "value" ]
Corresponds to IDD Field `extraterrestrial_direct_normal_radiation` Args: value (float): value for IDD Field `extraterrestrial_direct_normal_radiation` Unit: Wh/m2 value >= 0.0 Missing value: 9999.0 if `value` is None it will not be checked against the specification and is assumed to be a missing value Raises: ValueError: if `value` is not a valid value
[ "Corresponds", "to", "IDD", "Field", "extraterrestrial_direct_normal_radiation" ]
373d4d3c8386c8d35789f086ac5f6018c2711745
https://github.com/rbuffat/pyepw/blob/373d4d3c8386c8d35789f086ac5f6018c2711745/pyepw/epw.py#L6135-L6162
train
rbuffat/pyepw
pyepw/epw.py
WeatherData.horizontal_infrared_radiation_intensity
def horizontal_infrared_radiation_intensity(self, value=9999.0): """Corresponds to IDD Field `horizontal_infrared_radiation_intensity` Args: value (float): value for IDD Field `horizontal_infrared_radiation_intensity` Unit: Wh/m2 value >= 0.0 Missing value: 9999.0 if `value` is None it will not be checked against the specification and is assumed to be a missing value Raises: ValueError: if `value` is not a valid value """ if value is not None: try: value = float(value) except ValueError: raise ValueError( 'value {} need to be of type float ' 'for field `horizontal_infrared_radiation_intensity`'.format(value)) if value < 0.0: raise ValueError( 'value need to be greater or equal 0.0 ' 'for field `horizontal_infrared_radiation_intensity`') self._horizontal_infrared_radiation_intensity = value
python
def horizontal_infrared_radiation_intensity(self, value=9999.0): """Corresponds to IDD Field `horizontal_infrared_radiation_intensity` Args: value (float): value for IDD Field `horizontal_infrared_radiation_intensity` Unit: Wh/m2 value >= 0.0 Missing value: 9999.0 if `value` is None it will not be checked against the specification and is assumed to be a missing value Raises: ValueError: if `value` is not a valid value """ if value is not None: try: value = float(value) except ValueError: raise ValueError( 'value {} need to be of type float ' 'for field `horizontal_infrared_radiation_intensity`'.format(value)) if value < 0.0: raise ValueError( 'value need to be greater or equal 0.0 ' 'for field `horizontal_infrared_radiation_intensity`') self._horizontal_infrared_radiation_intensity = value
[ "def", "horizontal_infrared_radiation_intensity", "(", "self", ",", "value", "=", "9999.0", ")", ":", "if", "value", "is", "not", "None", ":", "try", ":", "value", "=", "float", "(", "value", ")", "except", "ValueError", ":", "raise", "ValueError", "(", "'value {} need to be of type float '", "'for field `horizontal_infrared_radiation_intensity`'", ".", "format", "(", "value", ")", ")", "if", "value", "<", "0.0", ":", "raise", "ValueError", "(", "'value need to be greater or equal 0.0 '", "'for field `horizontal_infrared_radiation_intensity`'", ")", "self", ".", "_horizontal_infrared_radiation_intensity", "=", "value" ]
Corresponds to IDD Field `horizontal_infrared_radiation_intensity` Args: value (float): value for IDD Field `horizontal_infrared_radiation_intensity` Unit: Wh/m2 value >= 0.0 Missing value: 9999.0 if `value` is None it will not be checked against the specification and is assumed to be a missing value Raises: ValueError: if `value` is not a valid value
[ "Corresponds", "to", "IDD", "Field", "horizontal_infrared_radiation_intensity" ]
373d4d3c8386c8d35789f086ac5f6018c2711745
https://github.com/rbuffat/pyepw/blob/373d4d3c8386c8d35789f086ac5f6018c2711745/pyepw/epw.py#L6175-L6202
train
rbuffat/pyepw
pyepw/epw.py
WeatherData.global_horizontal_radiation
def global_horizontal_radiation(self, value=9999.0): """Corresponds to IDD Field `global_horizontal_radiation` Args: value (float): value for IDD Field `global_horizontal_radiation` Unit: Wh/m2 value >= 0.0 Missing value: 9999.0 if `value` is None it will not be checked against the specification and is assumed to be a missing value Raises: ValueError: if `value` is not a valid value """ if value is not None: try: value = float(value) except ValueError: raise ValueError( 'value {} need to be of type float ' 'for field `global_horizontal_radiation`'.format(value)) if value < 0.0: raise ValueError('value need to be greater or equal 0.0 ' 'for field `global_horizontal_radiation`') self._global_horizontal_radiation = value
python
def global_horizontal_radiation(self, value=9999.0): """Corresponds to IDD Field `global_horizontal_radiation` Args: value (float): value for IDD Field `global_horizontal_radiation` Unit: Wh/m2 value >= 0.0 Missing value: 9999.0 if `value` is None it will not be checked against the specification and is assumed to be a missing value Raises: ValueError: if `value` is not a valid value """ if value is not None: try: value = float(value) except ValueError: raise ValueError( 'value {} need to be of type float ' 'for field `global_horizontal_radiation`'.format(value)) if value < 0.0: raise ValueError('value need to be greater or equal 0.0 ' 'for field `global_horizontal_radiation`') self._global_horizontal_radiation = value
[ "def", "global_horizontal_radiation", "(", "self", ",", "value", "=", "9999.0", ")", ":", "if", "value", "is", "not", "None", ":", "try", ":", "value", "=", "float", "(", "value", ")", "except", "ValueError", ":", "raise", "ValueError", "(", "'value {} need to be of type float '", "'for field `global_horizontal_radiation`'", ".", "format", "(", "value", ")", ")", "if", "value", "<", "0.0", ":", "raise", "ValueError", "(", "'value need to be greater or equal 0.0 '", "'for field `global_horizontal_radiation`'", ")", "self", ".", "_global_horizontal_radiation", "=", "value" ]
Corresponds to IDD Field `global_horizontal_radiation` Args: value (float): value for IDD Field `global_horizontal_radiation` Unit: Wh/m2 value >= 0.0 Missing value: 9999.0 if `value` is None it will not be checked against the specification and is assumed to be a missing value Raises: ValueError: if `value` is not a valid value
[ "Corresponds", "to", "IDD", "Field", "global_horizontal_radiation" ]
373d4d3c8386c8d35789f086ac5f6018c2711745
https://github.com/rbuffat/pyepw/blob/373d4d3c8386c8d35789f086ac5f6018c2711745/pyepw/epw.py#L6215-L6241
train
rbuffat/pyepw
pyepw/epw.py
WeatherData.direct_normal_radiation
def direct_normal_radiation(self, value=9999.0): """Corresponds to IDD Field `direct_normal_radiation` Args: value (float): value for IDD Field `direct_normal_radiation` Unit: Wh/m2 value >= 0.0 Missing value: 9999.0 if `value` is None it will not be checked against the specification and is assumed to be a missing value Raises: ValueError: if `value` is not a valid value """ if value is not None: try: value = float(value) except ValueError: raise ValueError( 'value {} need to be of type float ' 'for field `direct_normal_radiation`'.format(value)) if value < 0.0: raise ValueError('value need to be greater or equal 0.0 ' 'for field `direct_normal_radiation`') self._direct_normal_radiation = value
python
def direct_normal_radiation(self, value=9999.0): """Corresponds to IDD Field `direct_normal_radiation` Args: value (float): value for IDD Field `direct_normal_radiation` Unit: Wh/m2 value >= 0.0 Missing value: 9999.0 if `value` is None it will not be checked against the specification and is assumed to be a missing value Raises: ValueError: if `value` is not a valid value """ if value is not None: try: value = float(value) except ValueError: raise ValueError( 'value {} need to be of type float ' 'for field `direct_normal_radiation`'.format(value)) if value < 0.0: raise ValueError('value need to be greater or equal 0.0 ' 'for field `direct_normal_radiation`') self._direct_normal_radiation = value
[ "def", "direct_normal_radiation", "(", "self", ",", "value", "=", "9999.0", ")", ":", "if", "value", "is", "not", "None", ":", "try", ":", "value", "=", "float", "(", "value", ")", "except", "ValueError", ":", "raise", "ValueError", "(", "'value {} need to be of type float '", "'for field `direct_normal_radiation`'", ".", "format", "(", "value", ")", ")", "if", "value", "<", "0.0", ":", "raise", "ValueError", "(", "'value need to be greater or equal 0.0 '", "'for field `direct_normal_radiation`'", ")", "self", ".", "_direct_normal_radiation", "=", "value" ]
Corresponds to IDD Field `direct_normal_radiation` Args: value (float): value for IDD Field `direct_normal_radiation` Unit: Wh/m2 value >= 0.0 Missing value: 9999.0 if `value` is None it will not be checked against the specification and is assumed to be a missing value Raises: ValueError: if `value` is not a valid value
[ "Corresponds", "to", "IDD", "Field", "direct_normal_radiation" ]
373d4d3c8386c8d35789f086ac5f6018c2711745
https://github.com/rbuffat/pyepw/blob/373d4d3c8386c8d35789f086ac5f6018c2711745/pyepw/epw.py#L6254-L6280
train
rbuffat/pyepw
pyepw/epw.py
WeatherData.diffuse_horizontal_radiation
def diffuse_horizontal_radiation(self, value=9999.0): """Corresponds to IDD Field `diffuse_horizontal_radiation` Args: value (float): value for IDD Field `diffuse_horizontal_radiation` Unit: Wh/m2 value >= 0.0 Missing value: 9999.0 if `value` is None it will not be checked against the specification and is assumed to be a missing value Raises: ValueError: if `value` is not a valid value """ if value is not None: try: value = float(value) except ValueError: raise ValueError( 'value {} need to be of type float ' 'for field `diffuse_horizontal_radiation`'.format(value)) if value < 0.0: raise ValueError('value need to be greater or equal 0.0 ' 'for field `diffuse_horizontal_radiation`') self._diffuse_horizontal_radiation = value
python
def diffuse_horizontal_radiation(self, value=9999.0): """Corresponds to IDD Field `diffuse_horizontal_radiation` Args: value (float): value for IDD Field `diffuse_horizontal_radiation` Unit: Wh/m2 value >= 0.0 Missing value: 9999.0 if `value` is None it will not be checked against the specification and is assumed to be a missing value Raises: ValueError: if `value` is not a valid value """ if value is not None: try: value = float(value) except ValueError: raise ValueError( 'value {} need to be of type float ' 'for field `diffuse_horizontal_radiation`'.format(value)) if value < 0.0: raise ValueError('value need to be greater or equal 0.0 ' 'for field `diffuse_horizontal_radiation`') self._diffuse_horizontal_radiation = value
[ "def", "diffuse_horizontal_radiation", "(", "self", ",", "value", "=", "9999.0", ")", ":", "if", "value", "is", "not", "None", ":", "try", ":", "value", "=", "float", "(", "value", ")", "except", "ValueError", ":", "raise", "ValueError", "(", "'value {} need to be of type float '", "'for field `diffuse_horizontal_radiation`'", ".", "format", "(", "value", ")", ")", "if", "value", "<", "0.0", ":", "raise", "ValueError", "(", "'value need to be greater or equal 0.0 '", "'for field `diffuse_horizontal_radiation`'", ")", "self", ".", "_diffuse_horizontal_radiation", "=", "value" ]
Corresponds to IDD Field `diffuse_horizontal_radiation` Args: value (float): value for IDD Field `diffuse_horizontal_radiation` Unit: Wh/m2 value >= 0.0 Missing value: 9999.0 if `value` is None it will not be checked against the specification and is assumed to be a missing value Raises: ValueError: if `value` is not a valid value
[ "Corresponds", "to", "IDD", "Field", "diffuse_horizontal_radiation" ]
373d4d3c8386c8d35789f086ac5f6018c2711745
https://github.com/rbuffat/pyepw/blob/373d4d3c8386c8d35789f086ac5f6018c2711745/pyepw/epw.py#L6293-L6319
train
rbuffat/pyepw
pyepw/epw.py
WeatherData.global_horizontal_illuminance
def global_horizontal_illuminance(self, value=999999.0): """ Corresponds to IDD Field `global_horizontal_illuminance` will be missing if >= 999900 Args: value (float): value for IDD Field `global_horizontal_illuminance` Unit: lux value >= 0.0 Missing value: 999999.0 if `value` is None it will not be checked against the specification and is assumed to be a missing value Raises: ValueError: if `value` is not a valid value """ if value is not None: try: value = float(value) except ValueError: raise ValueError( 'value {} need to be of type float ' 'for field `global_horizontal_illuminance`'.format(value)) if value < 0.0: raise ValueError('value need to be greater or equal 0.0 ' 'for field `global_horizontal_illuminance`') self._global_horizontal_illuminance = value
python
def global_horizontal_illuminance(self, value=999999.0): """ Corresponds to IDD Field `global_horizontal_illuminance` will be missing if >= 999900 Args: value (float): value for IDD Field `global_horizontal_illuminance` Unit: lux value >= 0.0 Missing value: 999999.0 if `value` is None it will not be checked against the specification and is assumed to be a missing value Raises: ValueError: if `value` is not a valid value """ if value is not None: try: value = float(value) except ValueError: raise ValueError( 'value {} need to be of type float ' 'for field `global_horizontal_illuminance`'.format(value)) if value < 0.0: raise ValueError('value need to be greater or equal 0.0 ' 'for field `global_horizontal_illuminance`') self._global_horizontal_illuminance = value
[ "def", "global_horizontal_illuminance", "(", "self", ",", "value", "=", "999999.0", ")", ":", "if", "value", "is", "not", "None", ":", "try", ":", "value", "=", "float", "(", "value", ")", "except", "ValueError", ":", "raise", "ValueError", "(", "'value {} need to be of type float '", "'for field `global_horizontal_illuminance`'", ".", "format", "(", "value", ")", ")", "if", "value", "<", "0.0", ":", "raise", "ValueError", "(", "'value need to be greater or equal 0.0 '", "'for field `global_horizontal_illuminance`'", ")", "self", ".", "_global_horizontal_illuminance", "=", "value" ]
Corresponds to IDD Field `global_horizontal_illuminance` will be missing if >= 999900 Args: value (float): value for IDD Field `global_horizontal_illuminance` Unit: lux value >= 0.0 Missing value: 999999.0 if `value` is None it will not be checked against the specification and is assumed to be a missing value Raises: ValueError: if `value` is not a valid value
[ "Corresponds", "to", "IDD", "Field", "global_horizontal_illuminance", "will", "be", "missing", "if", ">", "=", "999900" ]
373d4d3c8386c8d35789f086ac5f6018c2711745
https://github.com/rbuffat/pyepw/blob/373d4d3c8386c8d35789f086ac5f6018c2711745/pyepw/epw.py#L6332-L6358
train
rbuffat/pyepw
pyepw/epw.py
WeatherData.direct_normal_illuminance
def direct_normal_illuminance(self, value=999999.0): """ Corresponds to IDD Field `direct_normal_illuminance` will be missing if >= 999900 Args: value (float): value for IDD Field `direct_normal_illuminance` Unit: lux value >= 0.0 Missing value: 999999.0 if `value` is None it will not be checked against the specification and is assumed to be a missing value Raises: ValueError: if `value` is not a valid value """ if value is not None: try: value = float(value) except ValueError: raise ValueError( 'value {} need to be of type float ' 'for field `direct_normal_illuminance`'.format(value)) if value < 0.0: raise ValueError('value need to be greater or equal 0.0 ' 'for field `direct_normal_illuminance`') self._direct_normal_illuminance = value
python
def direct_normal_illuminance(self, value=999999.0): """ Corresponds to IDD Field `direct_normal_illuminance` will be missing if >= 999900 Args: value (float): value for IDD Field `direct_normal_illuminance` Unit: lux value >= 0.0 Missing value: 999999.0 if `value` is None it will not be checked against the specification and is assumed to be a missing value Raises: ValueError: if `value` is not a valid value """ if value is not None: try: value = float(value) except ValueError: raise ValueError( 'value {} need to be of type float ' 'for field `direct_normal_illuminance`'.format(value)) if value < 0.0: raise ValueError('value need to be greater or equal 0.0 ' 'for field `direct_normal_illuminance`') self._direct_normal_illuminance = value
[ "def", "direct_normal_illuminance", "(", "self", ",", "value", "=", "999999.0", ")", ":", "if", "value", "is", "not", "None", ":", "try", ":", "value", "=", "float", "(", "value", ")", "except", "ValueError", ":", "raise", "ValueError", "(", "'value {} need to be of type float '", "'for field `direct_normal_illuminance`'", ".", "format", "(", "value", ")", ")", "if", "value", "<", "0.0", ":", "raise", "ValueError", "(", "'value need to be greater or equal 0.0 '", "'for field `direct_normal_illuminance`'", ")", "self", ".", "_direct_normal_illuminance", "=", "value" ]
Corresponds to IDD Field `direct_normal_illuminance` will be missing if >= 999900 Args: value (float): value for IDD Field `direct_normal_illuminance` Unit: lux value >= 0.0 Missing value: 999999.0 if `value` is None it will not be checked against the specification and is assumed to be a missing value Raises: ValueError: if `value` is not a valid value
[ "Corresponds", "to", "IDD", "Field", "direct_normal_illuminance", "will", "be", "missing", "if", ">", "=", "999900" ]
373d4d3c8386c8d35789f086ac5f6018c2711745
https://github.com/rbuffat/pyepw/blob/373d4d3c8386c8d35789f086ac5f6018c2711745/pyepw/epw.py#L6371-L6397
train
rbuffat/pyepw
pyepw/epw.py
WeatherData.diffuse_horizontal_illuminance
def diffuse_horizontal_illuminance(self, value=999999.0): """ Corresponds to IDD Field `diffuse_horizontal_illuminance` will be missing if >= 999900 Args: value (float): value for IDD Field `diffuse_horizontal_illuminance` Unit: lux value >= 0.0 Missing value: 999999.0 if `value` is None it will not be checked against the specification and is assumed to be a missing value Raises: ValueError: if `value` is not a valid value """ if value is not None: try: value = float(value) except ValueError: raise ValueError( 'value {} need to be of type float ' 'for field `diffuse_horizontal_illuminance`'.format(value)) if value < 0.0: raise ValueError('value need to be greater or equal 0.0 ' 'for field `diffuse_horizontal_illuminance`') self._diffuse_horizontal_illuminance = value
python
def diffuse_horizontal_illuminance(self, value=999999.0): """ Corresponds to IDD Field `diffuse_horizontal_illuminance` will be missing if >= 999900 Args: value (float): value for IDD Field `diffuse_horizontal_illuminance` Unit: lux value >= 0.0 Missing value: 999999.0 if `value` is None it will not be checked against the specification and is assumed to be a missing value Raises: ValueError: if `value` is not a valid value """ if value is not None: try: value = float(value) except ValueError: raise ValueError( 'value {} need to be of type float ' 'for field `diffuse_horizontal_illuminance`'.format(value)) if value < 0.0: raise ValueError('value need to be greater or equal 0.0 ' 'for field `diffuse_horizontal_illuminance`') self._diffuse_horizontal_illuminance = value
[ "def", "diffuse_horizontal_illuminance", "(", "self", ",", "value", "=", "999999.0", ")", ":", "if", "value", "is", "not", "None", ":", "try", ":", "value", "=", "float", "(", "value", ")", "except", "ValueError", ":", "raise", "ValueError", "(", "'value {} need to be of type float '", "'for field `diffuse_horizontal_illuminance`'", ".", "format", "(", "value", ")", ")", "if", "value", "<", "0.0", ":", "raise", "ValueError", "(", "'value need to be greater or equal 0.0 '", "'for field `diffuse_horizontal_illuminance`'", ")", "self", ".", "_diffuse_horizontal_illuminance", "=", "value" ]
Corresponds to IDD Field `diffuse_horizontal_illuminance` will be missing if >= 999900 Args: value (float): value for IDD Field `diffuse_horizontal_illuminance` Unit: lux value >= 0.0 Missing value: 999999.0 if `value` is None it will not be checked against the specification and is assumed to be a missing value Raises: ValueError: if `value` is not a valid value
[ "Corresponds", "to", "IDD", "Field", "diffuse_horizontal_illuminance", "will", "be", "missing", "if", ">", "=", "999900" ]
373d4d3c8386c8d35789f086ac5f6018c2711745
https://github.com/rbuffat/pyepw/blob/373d4d3c8386c8d35789f086ac5f6018c2711745/pyepw/epw.py#L6410-L6436
train
rbuffat/pyepw
pyepw/epw.py
WeatherData.zenith_luminance
def zenith_luminance(self, value=9999.0): """ Corresponds to IDD Field `zenith_luminance` will be missing if >= 9999 Args: value (float): value for IDD Field `zenith_luminance` Unit: Cd/m2 value >= 0.0 Missing value: 9999.0 if `value` is None it will not be checked against the specification and is assumed to be a missing value Raises: ValueError: if `value` is not a valid value """ if value is not None: try: value = float(value) except ValueError: raise ValueError('value {} need to be of type float ' 'for field `zenith_luminance`'.format(value)) if value < 0.0: raise ValueError('value need to be greater or equal 0.0 ' 'for field `zenith_luminance`') self._zenith_luminance = value
python
def zenith_luminance(self, value=9999.0): """ Corresponds to IDD Field `zenith_luminance` will be missing if >= 9999 Args: value (float): value for IDD Field `zenith_luminance` Unit: Cd/m2 value >= 0.0 Missing value: 9999.0 if `value` is None it will not be checked against the specification and is assumed to be a missing value Raises: ValueError: if `value` is not a valid value """ if value is not None: try: value = float(value) except ValueError: raise ValueError('value {} need to be of type float ' 'for field `zenith_luminance`'.format(value)) if value < 0.0: raise ValueError('value need to be greater or equal 0.0 ' 'for field `zenith_luminance`') self._zenith_luminance = value
[ "def", "zenith_luminance", "(", "self", ",", "value", "=", "9999.0", ")", ":", "if", "value", "is", "not", "None", ":", "try", ":", "value", "=", "float", "(", "value", ")", "except", "ValueError", ":", "raise", "ValueError", "(", "'value {} need to be of type float '", "'for field `zenith_luminance`'", ".", "format", "(", "value", ")", ")", "if", "value", "<", "0.0", ":", "raise", "ValueError", "(", "'value need to be greater or equal 0.0 '", "'for field `zenith_luminance`'", ")", "self", ".", "_zenith_luminance", "=", "value" ]
Corresponds to IDD Field `zenith_luminance` will be missing if >= 9999 Args: value (float): value for IDD Field `zenith_luminance` Unit: Cd/m2 value >= 0.0 Missing value: 9999.0 if `value` is None it will not be checked against the specification and is assumed to be a missing value Raises: ValueError: if `value` is not a valid value
[ "Corresponds", "to", "IDD", "Field", "zenith_luminance", "will", "be", "missing", "if", ">", "=", "9999" ]
373d4d3c8386c8d35789f086ac5f6018c2711745
https://github.com/rbuffat/pyepw/blob/373d4d3c8386c8d35789f086ac5f6018c2711745/pyepw/epw.py#L6449-L6474
train
rbuffat/pyepw
pyepw/epw.py
WeatherData.wind_direction
def wind_direction(self, value=999.0): """Corresponds to IDD Field `wind_direction` Args: value (float): value for IDD Field `wind_direction` Unit: degrees value >= 0.0 value <= 360.0 Missing value: 999.0 if `value` is None it will not be checked against the specification and is assumed to be a missing value Raises: ValueError: if `value` is not a valid value """ if value is not None: try: value = float(value) except ValueError: raise ValueError('value {} need to be of type float ' 'for field `wind_direction`'.format(value)) if value < 0.0: raise ValueError('value need to be greater or equal 0.0 ' 'for field `wind_direction`') if value > 360.0: raise ValueError('value need to be smaller 360.0 ' 'for field `wind_direction`') self._wind_direction = value
python
def wind_direction(self, value=999.0): """Corresponds to IDD Field `wind_direction` Args: value (float): value for IDD Field `wind_direction` Unit: degrees value >= 0.0 value <= 360.0 Missing value: 999.0 if `value` is None it will not be checked against the specification and is assumed to be a missing value Raises: ValueError: if `value` is not a valid value """ if value is not None: try: value = float(value) except ValueError: raise ValueError('value {} need to be of type float ' 'for field `wind_direction`'.format(value)) if value < 0.0: raise ValueError('value need to be greater or equal 0.0 ' 'for field `wind_direction`') if value > 360.0: raise ValueError('value need to be smaller 360.0 ' 'for field `wind_direction`') self._wind_direction = value
[ "def", "wind_direction", "(", "self", ",", "value", "=", "999.0", ")", ":", "if", "value", "is", "not", "None", ":", "try", ":", "value", "=", "float", "(", "value", ")", "except", "ValueError", ":", "raise", "ValueError", "(", "'value {} need to be of type float '", "'for field `wind_direction`'", ".", "format", "(", "value", ")", ")", "if", "value", "<", "0.0", ":", "raise", "ValueError", "(", "'value need to be greater or equal 0.0 '", "'for field `wind_direction`'", ")", "if", "value", ">", "360.0", ":", "raise", "ValueError", "(", "'value need to be smaller 360.0 '", "'for field `wind_direction`'", ")", "self", ".", "_wind_direction", "=", "value" ]
Corresponds to IDD Field `wind_direction` Args: value (float): value for IDD Field `wind_direction` Unit: degrees value >= 0.0 value <= 360.0 Missing value: 999.0 if `value` is None it will not be checked against the specification and is assumed to be a missing value Raises: ValueError: if `value` is not a valid value
[ "Corresponds", "to", "IDD", "Field", "wind_direction" ]
373d4d3c8386c8d35789f086ac5f6018c2711745
https://github.com/rbuffat/pyepw/blob/373d4d3c8386c8d35789f086ac5f6018c2711745/pyepw/epw.py#L6487-L6516
train
rbuffat/pyepw
pyepw/epw.py
WeatherData.wind_speed
def wind_speed(self, value=999.0): """Corresponds to IDD Field `wind_speed` Args: value (float): value for IDD Field `wind_speed` Unit: m/s value >= 0.0 value <= 40.0 Missing value: 999.0 if `value` is None it will not be checked against the specification and is assumed to be a missing value Raises: ValueError: if `value` is not a valid value """ if value is not None: try: value = float(value) except ValueError: raise ValueError('value {} need to be of type float ' 'for field `wind_speed`'.format(value)) if value < 0.0: raise ValueError('value need to be greater or equal 0.0 ' 'for field `wind_speed`') if value > 40.0: raise ValueError('value need to be smaller 40.0 ' 'for field `wind_speed`') self._wind_speed = value
python
def wind_speed(self, value=999.0): """Corresponds to IDD Field `wind_speed` Args: value (float): value for IDD Field `wind_speed` Unit: m/s value >= 0.0 value <= 40.0 Missing value: 999.0 if `value` is None it will not be checked against the specification and is assumed to be a missing value Raises: ValueError: if `value` is not a valid value """ if value is not None: try: value = float(value) except ValueError: raise ValueError('value {} need to be of type float ' 'for field `wind_speed`'.format(value)) if value < 0.0: raise ValueError('value need to be greater or equal 0.0 ' 'for field `wind_speed`') if value > 40.0: raise ValueError('value need to be smaller 40.0 ' 'for field `wind_speed`') self._wind_speed = value
[ "def", "wind_speed", "(", "self", ",", "value", "=", "999.0", ")", ":", "if", "value", "is", "not", "None", ":", "try", ":", "value", "=", "float", "(", "value", ")", "except", "ValueError", ":", "raise", "ValueError", "(", "'value {} need to be of type float '", "'for field `wind_speed`'", ".", "format", "(", "value", ")", ")", "if", "value", "<", "0.0", ":", "raise", "ValueError", "(", "'value need to be greater or equal 0.0 '", "'for field `wind_speed`'", ")", "if", "value", ">", "40.0", ":", "raise", "ValueError", "(", "'value need to be smaller 40.0 '", "'for field `wind_speed`'", ")", "self", ".", "_wind_speed", "=", "value" ]
Corresponds to IDD Field `wind_speed` Args: value (float): value for IDD Field `wind_speed` Unit: m/s value >= 0.0 value <= 40.0 Missing value: 999.0 if `value` is None it will not be checked against the specification and is assumed to be a missing value Raises: ValueError: if `value` is not a valid value
[ "Corresponds", "to", "IDD", "Field", "wind_speed" ]
373d4d3c8386c8d35789f086ac5f6018c2711745
https://github.com/rbuffat/pyepw/blob/373d4d3c8386c8d35789f086ac5f6018c2711745/pyepw/epw.py#L6529-L6558
train
rbuffat/pyepw
pyepw/epw.py
WeatherData.total_sky_cover
def total_sky_cover(self, value=99.0): """Corresponds to IDD Field `total_sky_cover` This is the value for total sky cover (tenths of coverage). (i.e. 1 is 1/10 covered. 10 is total coverage). (Amount of sky dome in tenths covered by clouds or obscuring phenomena at the hour indicated at the time indicated.) Args: value (float): value for IDD Field `total_sky_cover` value >= 0.0 value <= 10.0 Missing value: 99.0 if `value` is None it will not be checked against the specification and is assumed to be a missing value Raises: ValueError: if `value` is not a valid value """ if value is not None: try: value = float(value) except ValueError: raise ValueError('value {} need to be of type float ' 'for field `total_sky_cover`'.format(value)) if value < 0.0: raise ValueError('value need to be greater or equal 0.0 ' 'for field `total_sky_cover`') if value > 10.0: raise ValueError('value need to be smaller 10.0 ' 'for field `total_sky_cover`') self._total_sky_cover = value
python
def total_sky_cover(self, value=99.0): """Corresponds to IDD Field `total_sky_cover` This is the value for total sky cover (tenths of coverage). (i.e. 1 is 1/10 covered. 10 is total coverage). (Amount of sky dome in tenths covered by clouds or obscuring phenomena at the hour indicated at the time indicated.) Args: value (float): value for IDD Field `total_sky_cover` value >= 0.0 value <= 10.0 Missing value: 99.0 if `value` is None it will not be checked against the specification and is assumed to be a missing value Raises: ValueError: if `value` is not a valid value """ if value is not None: try: value = float(value) except ValueError: raise ValueError('value {} need to be of type float ' 'for field `total_sky_cover`'.format(value)) if value < 0.0: raise ValueError('value need to be greater or equal 0.0 ' 'for field `total_sky_cover`') if value > 10.0: raise ValueError('value need to be smaller 10.0 ' 'for field `total_sky_cover`') self._total_sky_cover = value
[ "def", "total_sky_cover", "(", "self", ",", "value", "=", "99.0", ")", ":", "if", "value", "is", "not", "None", ":", "try", ":", "value", "=", "float", "(", "value", ")", "except", "ValueError", ":", "raise", "ValueError", "(", "'value {} need to be of type float '", "'for field `total_sky_cover`'", ".", "format", "(", "value", ")", ")", "if", "value", "<", "0.0", ":", "raise", "ValueError", "(", "'value need to be greater or equal 0.0 '", "'for field `total_sky_cover`'", ")", "if", "value", ">", "10.0", ":", "raise", "ValueError", "(", "'value need to be smaller 10.0 '", "'for field `total_sky_cover`'", ")", "self", ".", "_total_sky_cover", "=", "value" ]
Corresponds to IDD Field `total_sky_cover` This is the value for total sky cover (tenths of coverage). (i.e. 1 is 1/10 covered. 10 is total coverage). (Amount of sky dome in tenths covered by clouds or obscuring phenomena at the hour indicated at the time indicated.) Args: value (float): value for IDD Field `total_sky_cover` value >= 0.0 value <= 10.0 Missing value: 99.0 if `value` is None it will not be checked against the specification and is assumed to be a missing value Raises: ValueError: if `value` is not a valid value
[ "Corresponds", "to", "IDD", "Field", "total_sky_cover", "This", "is", "the", "value", "for", "total", "sky", "cover", "(", "tenths", "of", "coverage", ")", ".", "(", "i", ".", "e", ".", "1", "is", "1", "/", "10", "covered", ".", "10", "is", "total", "coverage", ")", ".", "(", "Amount", "of", "sky", "dome", "in", "tenths", "covered", "by", "clouds", "or", "obscuring", "phenomena", "at", "the", "hour", "indicated", "at", "the", "time", "indicated", ".", ")" ]
373d4d3c8386c8d35789f086ac5f6018c2711745
https://github.com/rbuffat/pyepw/blob/373d4d3c8386c8d35789f086ac5f6018c2711745/pyepw/epw.py#L6571-L6602
train
rbuffat/pyepw
pyepw/epw.py
WeatherData.opaque_sky_cover
def opaque_sky_cover(self, value=99.0): """Corresponds to IDD Field `opaque_sky_cover` This is the value for opaque sky cover (tenths of coverage). (i.e. 1 is 1/10 covered. 10 is total coverage). (Amount of sky dome in tenths covered by clouds or obscuring phenomena that prevent observing the sky or higher cloud layers at the time indicated.) This is not used unless the field for Horizontal Infrared Radiation Intensity is missing and then it is used to calculate Horizontal Infrared Radiation Intensity. Args: value (float): value for IDD Field `opaque_sky_cover` value >= 0.0 value <= 10.0 Missing value: 99.0 if `value` is None it will not be checked against the specification and is assumed to be a missing value Raises: ValueError: if `value` is not a valid value """ if value is not None: try: value = float(value) except ValueError: raise ValueError('value {} need to be of type float ' 'for field `opaque_sky_cover`'.format(value)) if value < 0.0: raise ValueError('value need to be greater or equal 0.0 ' 'for field `opaque_sky_cover`') if value > 10.0: raise ValueError('value need to be smaller 10.0 ' 'for field `opaque_sky_cover`') self._opaque_sky_cover = value
python
def opaque_sky_cover(self, value=99.0): """Corresponds to IDD Field `opaque_sky_cover` This is the value for opaque sky cover (tenths of coverage). (i.e. 1 is 1/10 covered. 10 is total coverage). (Amount of sky dome in tenths covered by clouds or obscuring phenomena that prevent observing the sky or higher cloud layers at the time indicated.) This is not used unless the field for Horizontal Infrared Radiation Intensity is missing and then it is used to calculate Horizontal Infrared Radiation Intensity. Args: value (float): value for IDD Field `opaque_sky_cover` value >= 0.0 value <= 10.0 Missing value: 99.0 if `value` is None it will not be checked against the specification and is assumed to be a missing value Raises: ValueError: if `value` is not a valid value """ if value is not None: try: value = float(value) except ValueError: raise ValueError('value {} need to be of type float ' 'for field `opaque_sky_cover`'.format(value)) if value < 0.0: raise ValueError('value need to be greater or equal 0.0 ' 'for field `opaque_sky_cover`') if value > 10.0: raise ValueError('value need to be smaller 10.0 ' 'for field `opaque_sky_cover`') self._opaque_sky_cover = value
[ "def", "opaque_sky_cover", "(", "self", ",", "value", "=", "99.0", ")", ":", "if", "value", "is", "not", "None", ":", "try", ":", "value", "=", "float", "(", "value", ")", "except", "ValueError", ":", "raise", "ValueError", "(", "'value {} need to be of type float '", "'for field `opaque_sky_cover`'", ".", "format", "(", "value", ")", ")", "if", "value", "<", "0.0", ":", "raise", "ValueError", "(", "'value need to be greater or equal 0.0 '", "'for field `opaque_sky_cover`'", ")", "if", "value", ">", "10.0", ":", "raise", "ValueError", "(", "'value need to be smaller 10.0 '", "'for field `opaque_sky_cover`'", ")", "self", ".", "_opaque_sky_cover", "=", "value" ]
Corresponds to IDD Field `opaque_sky_cover` This is the value for opaque sky cover (tenths of coverage). (i.e. 1 is 1/10 covered. 10 is total coverage). (Amount of sky dome in tenths covered by clouds or obscuring phenomena that prevent observing the sky or higher cloud layers at the time indicated.) This is not used unless the field for Horizontal Infrared Radiation Intensity is missing and then it is used to calculate Horizontal Infrared Radiation Intensity. Args: value (float): value for IDD Field `opaque_sky_cover` value >= 0.0 value <= 10.0 Missing value: 99.0 if `value` is None it will not be checked against the specification and is assumed to be a missing value Raises: ValueError: if `value` is not a valid value
[ "Corresponds", "to", "IDD", "Field", "opaque_sky_cover", "This", "is", "the", "value", "for", "opaque", "sky", "cover", "(", "tenths", "of", "coverage", ")", ".", "(", "i", ".", "e", ".", "1", "is", "1", "/", "10", "covered", ".", "10", "is", "total", "coverage", ")", ".", "(", "Amount", "of", "sky", "dome", "in", "tenths", "covered", "by", "clouds", "or", "obscuring", "phenomena", "that", "prevent", "observing", "the", "sky", "or", "higher", "cloud", "layers", "at", "the", "time", "indicated", ".", ")", "This", "is", "not", "used", "unless", "the", "field", "for", "Horizontal", "Infrared", "Radiation", "Intensity", "is", "missing", "and", "then", "it", "is", "used", "to", "calculate", "Horizontal", "Infrared", "Radiation", "Intensity", "." ]
373d4d3c8386c8d35789f086ac5f6018c2711745
https://github.com/rbuffat/pyepw/blob/373d4d3c8386c8d35789f086ac5f6018c2711745/pyepw/epw.py#L6615-L6649
train
rbuffat/pyepw
pyepw/epw.py
WeatherData.visibility
def visibility(self, value=9999.0): """Corresponds to IDD Field `visibility` This is the value for visibility in km. (Horizontal visibility at the time indicated.) Args: value (float): value for IDD Field `visibility` Unit: km Missing value: 9999.0 if `value` is None it will not be checked against the specification and is assumed to be a missing value Raises: ValueError: if `value` is not a valid value """ if value is not None: try: value = float(value) except ValueError: raise ValueError('value {} need to be of type float ' 'for field `visibility`'.format(value)) self._visibility = value
python
def visibility(self, value=9999.0): """Corresponds to IDD Field `visibility` This is the value for visibility in km. (Horizontal visibility at the time indicated.) Args: value (float): value for IDD Field `visibility` Unit: km Missing value: 9999.0 if `value` is None it will not be checked against the specification and is assumed to be a missing value Raises: ValueError: if `value` is not a valid value """ if value is not None: try: value = float(value) except ValueError: raise ValueError('value {} need to be of type float ' 'for field `visibility`'.format(value)) self._visibility = value
[ "def", "visibility", "(", "self", ",", "value", "=", "9999.0", ")", ":", "if", "value", "is", "not", "None", ":", "try", ":", "value", "=", "float", "(", "value", ")", "except", "ValueError", ":", "raise", "ValueError", "(", "'value {} need to be of type float '", "'for field `visibility`'", ".", "format", "(", "value", ")", ")", "self", ".", "_visibility", "=", "value" ]
Corresponds to IDD Field `visibility` This is the value for visibility in km. (Horizontal visibility at the time indicated.) Args: value (float): value for IDD Field `visibility` Unit: km Missing value: 9999.0 if `value` is None it will not be checked against the specification and is assumed to be a missing value Raises: ValueError: if `value` is not a valid value
[ "Corresponds", "to", "IDD", "Field", "visibility", "This", "is", "the", "value", "for", "visibility", "in", "km", ".", "(", "Horizontal", "visibility", "at", "the", "time", "indicated", ".", ")" ]
373d4d3c8386c8d35789f086ac5f6018c2711745
https://github.com/rbuffat/pyepw/blob/373d4d3c8386c8d35789f086ac5f6018c2711745/pyepw/epw.py#L6662-L6684
train
rbuffat/pyepw
pyepw/epw.py
WeatherData.ceiling_height
def ceiling_height(self, value=99999.0): """Corresponds to IDD Field `ceiling_height` This is the value for ceiling height in m. (77777 is unlimited ceiling height. 88888 is cirroform ceiling.) It is not currently used in EnergyPlus calculations. Args: value (float): value for IDD Field `ceiling_height` Unit: m Missing value: 99999.0 if `value` is None it will not be checked against the specification and is assumed to be a missing value Raises: ValueError: if `value` is not a valid value """ if value is not None: try: value = float(value) except ValueError: raise ValueError('value {} need to be of type float ' 'for field `ceiling_height`'.format(value)) self._ceiling_height = value
python
def ceiling_height(self, value=99999.0): """Corresponds to IDD Field `ceiling_height` This is the value for ceiling height in m. (77777 is unlimited ceiling height. 88888 is cirroform ceiling.) It is not currently used in EnergyPlus calculations. Args: value (float): value for IDD Field `ceiling_height` Unit: m Missing value: 99999.0 if `value` is None it will not be checked against the specification and is assumed to be a missing value Raises: ValueError: if `value` is not a valid value """ if value is not None: try: value = float(value) except ValueError: raise ValueError('value {} need to be of type float ' 'for field `ceiling_height`'.format(value)) self._ceiling_height = value
[ "def", "ceiling_height", "(", "self", ",", "value", "=", "99999.0", ")", ":", "if", "value", "is", "not", "None", ":", "try", ":", "value", "=", "float", "(", "value", ")", "except", "ValueError", ":", "raise", "ValueError", "(", "'value {} need to be of type float '", "'for field `ceiling_height`'", ".", "format", "(", "value", ")", ")", "self", ".", "_ceiling_height", "=", "value" ]
Corresponds to IDD Field `ceiling_height` This is the value for ceiling height in m. (77777 is unlimited ceiling height. 88888 is cirroform ceiling.) It is not currently used in EnergyPlus calculations. Args: value (float): value for IDD Field `ceiling_height` Unit: m Missing value: 99999.0 if `value` is None it will not be checked against the specification and is assumed to be a missing value Raises: ValueError: if `value` is not a valid value
[ "Corresponds", "to", "IDD", "Field", "ceiling_height", "This", "is", "the", "value", "for", "ceiling", "height", "in", "m", ".", "(", "77777", "is", "unlimited", "ceiling", "height", ".", "88888", "is", "cirroform", "ceiling", ".", ")", "It", "is", "not", "currently", "used", "in", "EnergyPlus", "calculations", "." ]
373d4d3c8386c8d35789f086ac5f6018c2711745
https://github.com/rbuffat/pyepw/blob/373d4d3c8386c8d35789f086ac5f6018c2711745/pyepw/epw.py#L6697-L6721
train
rbuffat/pyepw
pyepw/epw.py
WeatherData.present_weather_observation
def present_weather_observation(self, value=None): """Corresponds to IDD Field `present_weather_observation` If the value of the field is 0, then the observed weather codes are taken from the following field. If the value of the field is 9, then "missing" weather is assumed. Since the primary use of these fields (Present Weather Observation and Present Weather Codes) is for rain/wet surfaces, a missing observation field or a missing weather code implies "no rain". Args: value (int): value for IDD Field `present_weather_observation` if `value` is None it will not be checked against the specification and is assumed to be a missing value Raises: ValueError: if `value` is not a valid value """ if value is not None: try: value = int(value) except ValueError: raise ValueError( 'value {} need to be of type int ' 'for field `present_weather_observation`'.format(value)) self._present_weather_observation = value
python
def present_weather_observation(self, value=None): """Corresponds to IDD Field `present_weather_observation` If the value of the field is 0, then the observed weather codes are taken from the following field. If the value of the field is 9, then "missing" weather is assumed. Since the primary use of these fields (Present Weather Observation and Present Weather Codes) is for rain/wet surfaces, a missing observation field or a missing weather code implies "no rain". Args: value (int): value for IDD Field `present_weather_observation` if `value` is None it will not be checked against the specification and is assumed to be a missing value Raises: ValueError: if `value` is not a valid value """ if value is not None: try: value = int(value) except ValueError: raise ValueError( 'value {} need to be of type int ' 'for field `present_weather_observation`'.format(value)) self._present_weather_observation = value
[ "def", "present_weather_observation", "(", "self", ",", "value", "=", "None", ")", ":", "if", "value", "is", "not", "None", ":", "try", ":", "value", "=", "int", "(", "value", ")", "except", "ValueError", ":", "raise", "ValueError", "(", "'value {} need to be of type int '", "'for field `present_weather_observation`'", ".", "format", "(", "value", ")", ")", "self", ".", "_present_weather_observation", "=", "value" ]
Corresponds to IDD Field `present_weather_observation` If the value of the field is 0, then the observed weather codes are taken from the following field. If the value of the field is 9, then "missing" weather is assumed. Since the primary use of these fields (Present Weather Observation and Present Weather Codes) is for rain/wet surfaces, a missing observation field or a missing weather code implies "no rain". Args: value (int): value for IDD Field `present_weather_observation` if `value` is None it will not be checked against the specification and is assumed to be a missing value Raises: ValueError: if `value` is not a valid value
[ "Corresponds", "to", "IDD", "Field", "present_weather_observation", "If", "the", "value", "of", "the", "field", "is", "0", "then", "the", "observed", "weather", "codes", "are", "taken", "from", "the", "following", "field", ".", "If", "the", "value", "of", "the", "field", "is", "9", "then", "missing", "weather", "is", "assumed", ".", "Since", "the", "primary", "use", "of", "these", "fields", "(", "Present", "Weather", "Observation", "and", "Present", "Weather", "Codes", ")", "is", "for", "rain", "/", "wet", "surfaces", "a", "missing", "observation", "field", "or", "a", "missing", "weather", "code", "implies", "no", "rain", "." ]
373d4d3c8386c8d35789f086ac5f6018c2711745
https://github.com/rbuffat/pyepw/blob/373d4d3c8386c8d35789f086ac5f6018c2711745/pyepw/epw.py#L6734-L6759
train
rbuffat/pyepw
pyepw/epw.py
WeatherData.present_weather_codes
def present_weather_codes(self, value=None): """Corresponds to IDD Field `present_weather_codes` Args: value (int): value for IDD Field `present_weather_codes` if `value` is None it will not be checked against the specification and is assumed to be a missing value Raises: ValueError: if `value` is not a valid value """ if value is not None: try: value = int(value) except ValueError: raise ValueError( 'value {} need to be of type int ' 'for field `present_weather_codes`'.format(value)) self._present_weather_codes = value
python
def present_weather_codes(self, value=None): """Corresponds to IDD Field `present_weather_codes` Args: value (int): value for IDD Field `present_weather_codes` if `value` is None it will not be checked against the specification and is assumed to be a missing value Raises: ValueError: if `value` is not a valid value """ if value is not None: try: value = int(value) except ValueError: raise ValueError( 'value {} need to be of type int ' 'for field `present_weather_codes`'.format(value)) self._present_weather_codes = value
[ "def", "present_weather_codes", "(", "self", ",", "value", "=", "None", ")", ":", "if", "value", "is", "not", "None", ":", "try", ":", "value", "=", "int", "(", "value", ")", "except", "ValueError", ":", "raise", "ValueError", "(", "'value {} need to be of type int '", "'for field `present_weather_codes`'", ".", "format", "(", "value", ")", ")", "self", ".", "_present_weather_codes", "=", "value" ]
Corresponds to IDD Field `present_weather_codes` Args: value (int): value for IDD Field `present_weather_codes` if `value` is None it will not be checked against the specification and is assumed to be a missing value Raises: ValueError: if `value` is not a valid value
[ "Corresponds", "to", "IDD", "Field", "present_weather_codes" ]
373d4d3c8386c8d35789f086ac5f6018c2711745
https://github.com/rbuffat/pyepw/blob/373d4d3c8386c8d35789f086ac5f6018c2711745/pyepw/epw.py#L6772-L6792
train
rbuffat/pyepw
pyepw/epw.py
WeatherData.precipitable_water
def precipitable_water(self, value=999.0): """Corresponds to IDD Field `precipitable_water` Args: value (float): value for IDD Field `precipitable_water` Unit: mm Missing value: 999.0 if `value` is None it will not be checked against the specification and is assumed to be a missing value Raises: ValueError: if `value` is not a valid value """ if value is not None: try: value = float(value) except ValueError: raise ValueError( 'value {} need to be of type float ' 'for field `precipitable_water`'.format(value)) self._precipitable_water = value
python
def precipitable_water(self, value=999.0): """Corresponds to IDD Field `precipitable_water` Args: value (float): value for IDD Field `precipitable_water` Unit: mm Missing value: 999.0 if `value` is None it will not be checked against the specification and is assumed to be a missing value Raises: ValueError: if `value` is not a valid value """ if value is not None: try: value = float(value) except ValueError: raise ValueError( 'value {} need to be of type float ' 'for field `precipitable_water`'.format(value)) self._precipitable_water = value
[ "def", "precipitable_water", "(", "self", ",", "value", "=", "999.0", ")", ":", "if", "value", "is", "not", "None", ":", "try", ":", "value", "=", "float", "(", "value", ")", "except", "ValueError", ":", "raise", "ValueError", "(", "'value {} need to be of type float '", "'for field `precipitable_water`'", ".", "format", "(", "value", ")", ")", "self", ".", "_precipitable_water", "=", "value" ]
Corresponds to IDD Field `precipitable_water` Args: value (float): value for IDD Field `precipitable_water` Unit: mm Missing value: 999.0 if `value` is None it will not be checked against the specification and is assumed to be a missing value Raises: ValueError: if `value` is not a valid value
[ "Corresponds", "to", "IDD", "Field", "precipitable_water" ]
373d4d3c8386c8d35789f086ac5f6018c2711745
https://github.com/rbuffat/pyepw/blob/373d4d3c8386c8d35789f086ac5f6018c2711745/pyepw/epw.py#L6805-L6827
train
rbuffat/pyepw
pyepw/epw.py
WeatherData.aerosol_optical_depth
def aerosol_optical_depth(self, value=0.999): """Corresponds to IDD Field `aerosol_optical_depth` Args: value (float): value for IDD Field `aerosol_optical_depth` Unit: thousandths Missing value: 0.999 if `value` is None it will not be checked against the specification and is assumed to be a missing value Raises: ValueError: if `value` is not a valid value """ if value is not None: try: value = float(value) except ValueError: raise ValueError( 'value {} need to be of type float ' 'for field `aerosol_optical_depth`'.format(value)) self._aerosol_optical_depth = value
python
def aerosol_optical_depth(self, value=0.999): """Corresponds to IDD Field `aerosol_optical_depth` Args: value (float): value for IDD Field `aerosol_optical_depth` Unit: thousandths Missing value: 0.999 if `value` is None it will not be checked against the specification and is assumed to be a missing value Raises: ValueError: if `value` is not a valid value """ if value is not None: try: value = float(value) except ValueError: raise ValueError( 'value {} need to be of type float ' 'for field `aerosol_optical_depth`'.format(value)) self._aerosol_optical_depth = value
[ "def", "aerosol_optical_depth", "(", "self", ",", "value", "=", "0.999", ")", ":", "if", "value", "is", "not", "None", ":", "try", ":", "value", "=", "float", "(", "value", ")", "except", "ValueError", ":", "raise", "ValueError", "(", "'value {} need to be of type float '", "'for field `aerosol_optical_depth`'", ".", "format", "(", "value", ")", ")", "self", ".", "_aerosol_optical_depth", "=", "value" ]
Corresponds to IDD Field `aerosol_optical_depth` Args: value (float): value for IDD Field `aerosol_optical_depth` Unit: thousandths Missing value: 0.999 if `value` is None it will not be checked against the specification and is assumed to be a missing value Raises: ValueError: if `value` is not a valid value
[ "Corresponds", "to", "IDD", "Field", "aerosol_optical_depth" ]
373d4d3c8386c8d35789f086ac5f6018c2711745
https://github.com/rbuffat/pyepw/blob/373d4d3c8386c8d35789f086ac5f6018c2711745/pyepw/epw.py#L6840-L6862
train
rbuffat/pyepw
pyepw/epw.py
WeatherData.snow_depth
def snow_depth(self, value=999.0): """Corresponds to IDD Field `snow_depth` Args: value (float): value for IDD Field `snow_depth` Unit: cm Missing value: 999.0 if `value` is None it will not be checked against the specification and is assumed to be a missing value Raises: ValueError: if `value` is not a valid value """ if value is not None: try: value = float(value) except ValueError: raise ValueError('value {} need to be of type float ' 'for field `snow_depth`'.format(value)) self._snow_depth = value
python
def snow_depth(self, value=999.0): """Corresponds to IDD Field `snow_depth` Args: value (float): value for IDD Field `snow_depth` Unit: cm Missing value: 999.0 if `value` is None it will not be checked against the specification and is assumed to be a missing value Raises: ValueError: if `value` is not a valid value """ if value is not None: try: value = float(value) except ValueError: raise ValueError('value {} need to be of type float ' 'for field `snow_depth`'.format(value)) self._snow_depth = value
[ "def", "snow_depth", "(", "self", ",", "value", "=", "999.0", ")", ":", "if", "value", "is", "not", "None", ":", "try", ":", "value", "=", "float", "(", "value", ")", "except", "ValueError", ":", "raise", "ValueError", "(", "'value {} need to be of type float '", "'for field `snow_depth`'", ".", "format", "(", "value", ")", ")", "self", ".", "_snow_depth", "=", "value" ]
Corresponds to IDD Field `snow_depth` Args: value (float): value for IDD Field `snow_depth` Unit: cm Missing value: 999.0 if `value` is None it will not be checked against the specification and is assumed to be a missing value Raises: ValueError: if `value` is not a valid value
[ "Corresponds", "to", "IDD", "Field", "snow_depth" ]
373d4d3c8386c8d35789f086ac5f6018c2711745
https://github.com/rbuffat/pyepw/blob/373d4d3c8386c8d35789f086ac5f6018c2711745/pyepw/epw.py#L6875-L6896
train
rbuffat/pyepw
pyepw/epw.py
WeatherData.days_since_last_snowfall
def days_since_last_snowfall(self, value=99): """Corresponds to IDD Field `days_since_last_snowfall` Args: value (int): value for IDD Field `days_since_last_snowfall` Missing value: 99 if `value` is None it will not be checked against the specification and is assumed to be a missing value Raises: ValueError: if `value` is not a valid value """ if value is not None: try: value = int(value) except ValueError: raise ValueError( 'value {} need to be of type int ' 'for field `days_since_last_snowfall`'.format(value)) self._days_since_last_snowfall = value
python
def days_since_last_snowfall(self, value=99): """Corresponds to IDD Field `days_since_last_snowfall` Args: value (int): value for IDD Field `days_since_last_snowfall` Missing value: 99 if `value` is None it will not be checked against the specification and is assumed to be a missing value Raises: ValueError: if `value` is not a valid value """ if value is not None: try: value = int(value) except ValueError: raise ValueError( 'value {} need to be of type int ' 'for field `days_since_last_snowfall`'.format(value)) self._days_since_last_snowfall = value
[ "def", "days_since_last_snowfall", "(", "self", ",", "value", "=", "99", ")", ":", "if", "value", "is", "not", "None", ":", "try", ":", "value", "=", "int", "(", "value", ")", "except", "ValueError", ":", "raise", "ValueError", "(", "'value {} need to be of type int '", "'for field `days_since_last_snowfall`'", ".", "format", "(", "value", ")", ")", "self", ".", "_days_since_last_snowfall", "=", "value" ]
Corresponds to IDD Field `days_since_last_snowfall` Args: value (int): value for IDD Field `days_since_last_snowfall` Missing value: 99 if `value` is None it will not be checked against the specification and is assumed to be a missing value Raises: ValueError: if `value` is not a valid value
[ "Corresponds", "to", "IDD", "Field", "days_since_last_snowfall" ]
373d4d3c8386c8d35789f086ac5f6018c2711745
https://github.com/rbuffat/pyepw/blob/373d4d3c8386c8d35789f086ac5f6018c2711745/pyepw/epw.py#L6909-L6930
train
rbuffat/pyepw
pyepw/epw.py
WeatherData.albedo
def albedo(self, value=999.0): """Corresponds to IDD Field `albedo` Args: value (float): value for IDD Field `albedo` Missing value: 999.0 if `value` is None it will not be checked against the specification and is assumed to be a missing value Raises: ValueError: if `value` is not a valid value """ if value is not None: try: value = float(value) except ValueError: raise ValueError('value {} need to be of type float ' 'for field `albedo`'.format(value)) self._albedo = value
python
def albedo(self, value=999.0): """Corresponds to IDD Field `albedo` Args: value (float): value for IDD Field `albedo` Missing value: 999.0 if `value` is None it will not be checked against the specification and is assumed to be a missing value Raises: ValueError: if `value` is not a valid value """ if value is not None: try: value = float(value) except ValueError: raise ValueError('value {} need to be of type float ' 'for field `albedo`'.format(value)) self._albedo = value
[ "def", "albedo", "(", "self", ",", "value", "=", "999.0", ")", ":", "if", "value", "is", "not", "None", ":", "try", ":", "value", "=", "float", "(", "value", ")", "except", "ValueError", ":", "raise", "ValueError", "(", "'value {} need to be of type float '", "'for field `albedo`'", ".", "format", "(", "value", ")", ")", "self", ".", "_albedo", "=", "value" ]
Corresponds to IDD Field `albedo` Args: value (float): value for IDD Field `albedo` Missing value: 999.0 if `value` is None it will not be checked against the specification and is assumed to be a missing value Raises: ValueError: if `value` is not a valid value
[ "Corresponds", "to", "IDD", "Field", "albedo" ]
373d4d3c8386c8d35789f086ac5f6018c2711745
https://github.com/rbuffat/pyepw/blob/373d4d3c8386c8d35789f086ac5f6018c2711745/pyepw/epw.py#L6943-L6963
train
rbuffat/pyepw
pyepw/epw.py
WeatherData.liquid_precipitation_depth
def liquid_precipitation_depth(self, value=999.0): """Corresponds to IDD Field `liquid_precipitation_depth` Args: value (float): value for IDD Field `liquid_precipitation_depth` Unit: mm Missing value: 999.0 if `value` is None it will not be checked against the specification and is assumed to be a missing value Raises: ValueError: if `value` is not a valid value """ if value is not None: try: value = float(value) except ValueError: raise ValueError( 'value {} need to be of type float ' 'for field `liquid_precipitation_depth`'.format(value)) self._liquid_precipitation_depth = value
python
def liquid_precipitation_depth(self, value=999.0): """Corresponds to IDD Field `liquid_precipitation_depth` Args: value (float): value for IDD Field `liquid_precipitation_depth` Unit: mm Missing value: 999.0 if `value` is None it will not be checked against the specification and is assumed to be a missing value Raises: ValueError: if `value` is not a valid value """ if value is not None: try: value = float(value) except ValueError: raise ValueError( 'value {} need to be of type float ' 'for field `liquid_precipitation_depth`'.format(value)) self._liquid_precipitation_depth = value
[ "def", "liquid_precipitation_depth", "(", "self", ",", "value", "=", "999.0", ")", ":", "if", "value", "is", "not", "None", ":", "try", ":", "value", "=", "float", "(", "value", ")", "except", "ValueError", ":", "raise", "ValueError", "(", "'value {} need to be of type float '", "'for field `liquid_precipitation_depth`'", ".", "format", "(", "value", ")", ")", "self", ".", "_liquid_precipitation_depth", "=", "value" ]
Corresponds to IDD Field `liquid_precipitation_depth` Args: value (float): value for IDD Field `liquid_precipitation_depth` Unit: mm Missing value: 999.0 if `value` is None it will not be checked against the specification and is assumed to be a missing value Raises: ValueError: if `value` is not a valid value
[ "Corresponds", "to", "IDD", "Field", "liquid_precipitation_depth" ]
373d4d3c8386c8d35789f086ac5f6018c2711745
https://github.com/rbuffat/pyepw/blob/373d4d3c8386c8d35789f086ac5f6018c2711745/pyepw/epw.py#L6976-L6998
train
rbuffat/pyepw
pyepw/epw.py
WeatherData.liquid_precipitation_quantity
def liquid_precipitation_quantity(self, value=99.0): """Corresponds to IDD Field `liquid_precipitation_quantity` Args: value (float): value for IDD Field `liquid_precipitation_quantity` Unit: hr Missing value: 99.0 if `value` is None it will not be checked against the specification and is assumed to be a missing value Raises: ValueError: if `value` is not a valid value """ if value is not None: try: value = float(value) except ValueError: raise ValueError( 'value {} need to be of type float ' 'for field `liquid_precipitation_quantity`'.format(value)) self._liquid_precipitation_quantity = value
python
def liquid_precipitation_quantity(self, value=99.0): """Corresponds to IDD Field `liquid_precipitation_quantity` Args: value (float): value for IDD Field `liquid_precipitation_quantity` Unit: hr Missing value: 99.0 if `value` is None it will not be checked against the specification and is assumed to be a missing value Raises: ValueError: if `value` is not a valid value """ if value is not None: try: value = float(value) except ValueError: raise ValueError( 'value {} need to be of type float ' 'for field `liquid_precipitation_quantity`'.format(value)) self._liquid_precipitation_quantity = value
[ "def", "liquid_precipitation_quantity", "(", "self", ",", "value", "=", "99.0", ")", ":", "if", "value", "is", "not", "None", ":", "try", ":", "value", "=", "float", "(", "value", ")", "except", "ValueError", ":", "raise", "ValueError", "(", "'value {} need to be of type float '", "'for field `liquid_precipitation_quantity`'", ".", "format", "(", "value", ")", ")", "self", ".", "_liquid_precipitation_quantity", "=", "value" ]
Corresponds to IDD Field `liquid_precipitation_quantity` Args: value (float): value for IDD Field `liquid_precipitation_quantity` Unit: hr Missing value: 99.0 if `value` is None it will not be checked against the specification and is assumed to be a missing value Raises: ValueError: if `value` is not a valid value
[ "Corresponds", "to", "IDD", "Field", "liquid_precipitation_quantity" ]
373d4d3c8386c8d35789f086ac5f6018c2711745
https://github.com/rbuffat/pyepw/blob/373d4d3c8386c8d35789f086ac5f6018c2711745/pyepw/epw.py#L7011-L7033
train
rbuffat/pyepw
pyepw/epw.py
WeatherData.export
def export(self, top=True): """Exports object to its string representation. Args: top (bool): if True appends `internal_name` before values. All non list objects should be exported with value top=True, all list objects, that are embedded in as fields inlist objects should be exported with `top`=False Returns: str: The objects string representation """ out = [] if top: out.append(self._internal_name) out.append(self._to_str(self.year)) out.append(self._to_str(self.month)) out.append(self._to_str(self.day)) out.append(self._to_str(self.hour)) out.append(self._to_str(self.minute)) out.append(self._to_str(self.data_source_and_uncertainty_flags)) out.append(self._to_str(self.dry_bulb_temperature)) out.append(self._to_str(self.dew_point_temperature)) out.append(self._to_str(self.relative_humidity)) out.append(self._to_str(self.atmospheric_station_pressure)) out.append(self._to_str(self.extraterrestrial_horizontal_radiation)) out.append(self._to_str(self.extraterrestrial_direct_normal_radiation)) out.append(self._to_str(self.horizontal_infrared_radiation_intensity)) out.append(self._to_str(self.global_horizontal_radiation)) out.append(self._to_str(self.direct_normal_radiation)) out.append(self._to_str(self.diffuse_horizontal_radiation)) out.append(self._to_str(self.global_horizontal_illuminance)) out.append(self._to_str(self.direct_normal_illuminance)) out.append(self._to_str(self.diffuse_horizontal_illuminance)) out.append(self._to_str(self.zenith_luminance)) out.append(self._to_str(self.wind_direction)) out.append(self._to_str(self.wind_speed)) out.append(self._to_str(self.total_sky_cover)) out.append(self._to_str(self.opaque_sky_cover)) out.append(self._to_str(self.visibility)) out.append(self._to_str(self.ceiling_height)) out.append(self._to_str(self.present_weather_observation)) out.append(self._to_str(self.present_weather_codes)) out.append(self._to_str(self.precipitable_water)) out.append(self._to_str(self.aerosol_optical_depth)) out.append(self._to_str(self.snow_depth)) out.append(self._to_str(self.days_since_last_snowfall)) out.append(self._to_str(self.albedo)) out.append(self._to_str(self.liquid_precipitation_depth)) out.append(self._to_str(self.liquid_precipitation_quantity)) return ",".join(out)
python
def export(self, top=True): """Exports object to its string representation. Args: top (bool): if True appends `internal_name` before values. All non list objects should be exported with value top=True, all list objects, that are embedded in as fields inlist objects should be exported with `top`=False Returns: str: The objects string representation """ out = [] if top: out.append(self._internal_name) out.append(self._to_str(self.year)) out.append(self._to_str(self.month)) out.append(self._to_str(self.day)) out.append(self._to_str(self.hour)) out.append(self._to_str(self.minute)) out.append(self._to_str(self.data_source_and_uncertainty_flags)) out.append(self._to_str(self.dry_bulb_temperature)) out.append(self._to_str(self.dew_point_temperature)) out.append(self._to_str(self.relative_humidity)) out.append(self._to_str(self.atmospheric_station_pressure)) out.append(self._to_str(self.extraterrestrial_horizontal_radiation)) out.append(self._to_str(self.extraterrestrial_direct_normal_radiation)) out.append(self._to_str(self.horizontal_infrared_radiation_intensity)) out.append(self._to_str(self.global_horizontal_radiation)) out.append(self._to_str(self.direct_normal_radiation)) out.append(self._to_str(self.diffuse_horizontal_radiation)) out.append(self._to_str(self.global_horizontal_illuminance)) out.append(self._to_str(self.direct_normal_illuminance)) out.append(self._to_str(self.diffuse_horizontal_illuminance)) out.append(self._to_str(self.zenith_luminance)) out.append(self._to_str(self.wind_direction)) out.append(self._to_str(self.wind_speed)) out.append(self._to_str(self.total_sky_cover)) out.append(self._to_str(self.opaque_sky_cover)) out.append(self._to_str(self.visibility)) out.append(self._to_str(self.ceiling_height)) out.append(self._to_str(self.present_weather_observation)) out.append(self._to_str(self.present_weather_codes)) out.append(self._to_str(self.precipitable_water)) out.append(self._to_str(self.aerosol_optical_depth)) out.append(self._to_str(self.snow_depth)) out.append(self._to_str(self.days_since_last_snowfall)) out.append(self._to_str(self.albedo)) out.append(self._to_str(self.liquid_precipitation_depth)) out.append(self._to_str(self.liquid_precipitation_quantity)) return ",".join(out)
[ "def", "export", "(", "self", ",", "top", "=", "True", ")", ":", "out", "=", "[", "]", "if", "top", ":", "out", ".", "append", "(", "self", ".", "_internal_name", ")", "out", ".", "append", "(", "self", ".", "_to_str", "(", "self", ".", "year", ")", ")", "out", ".", "append", "(", "self", ".", "_to_str", "(", "self", ".", "month", ")", ")", "out", ".", "append", "(", "self", ".", "_to_str", "(", "self", ".", "day", ")", ")", "out", ".", "append", "(", "self", ".", "_to_str", "(", "self", ".", "hour", ")", ")", "out", ".", "append", "(", "self", ".", "_to_str", "(", "self", ".", "minute", ")", ")", "out", ".", "append", "(", "self", ".", "_to_str", "(", "self", ".", "data_source_and_uncertainty_flags", ")", ")", "out", ".", "append", "(", "self", ".", "_to_str", "(", "self", ".", "dry_bulb_temperature", ")", ")", "out", ".", "append", "(", "self", ".", "_to_str", "(", "self", ".", "dew_point_temperature", ")", ")", "out", ".", "append", "(", "self", ".", "_to_str", "(", "self", ".", "relative_humidity", ")", ")", "out", ".", "append", "(", "self", ".", "_to_str", "(", "self", ".", "atmospheric_station_pressure", ")", ")", "out", ".", "append", "(", "self", ".", "_to_str", "(", "self", ".", "extraterrestrial_horizontal_radiation", ")", ")", "out", ".", "append", "(", "self", ".", "_to_str", "(", "self", ".", "extraterrestrial_direct_normal_radiation", ")", ")", "out", ".", "append", "(", "self", ".", "_to_str", "(", "self", ".", "horizontal_infrared_radiation_intensity", ")", ")", "out", ".", "append", "(", "self", ".", "_to_str", "(", "self", ".", "global_horizontal_radiation", ")", ")", "out", ".", "append", "(", "self", ".", "_to_str", "(", "self", ".", "direct_normal_radiation", ")", ")", "out", ".", "append", "(", "self", ".", "_to_str", "(", "self", ".", "diffuse_horizontal_radiation", ")", ")", "out", ".", "append", "(", "self", ".", "_to_str", "(", "self", ".", "global_horizontal_illuminance", ")", ")", "out", ".", "append", "(", "self", ".", "_to_str", "(", "self", ".", "direct_normal_illuminance", ")", ")", "out", ".", "append", "(", "self", ".", "_to_str", "(", "self", ".", "diffuse_horizontal_illuminance", ")", ")", "out", ".", "append", "(", "self", ".", "_to_str", "(", "self", ".", "zenith_luminance", ")", ")", "out", ".", "append", "(", "self", ".", "_to_str", "(", "self", ".", "wind_direction", ")", ")", "out", ".", "append", "(", "self", ".", "_to_str", "(", "self", ".", "wind_speed", ")", ")", "out", ".", "append", "(", "self", ".", "_to_str", "(", "self", ".", "total_sky_cover", ")", ")", "out", ".", "append", "(", "self", ".", "_to_str", "(", "self", ".", "opaque_sky_cover", ")", ")", "out", ".", "append", "(", "self", ".", "_to_str", "(", "self", ".", "visibility", ")", ")", "out", ".", "append", "(", "self", ".", "_to_str", "(", "self", ".", "ceiling_height", ")", ")", "out", ".", "append", "(", "self", ".", "_to_str", "(", "self", ".", "present_weather_observation", ")", ")", "out", ".", "append", "(", "self", ".", "_to_str", "(", "self", ".", "present_weather_codes", ")", ")", "out", ".", "append", "(", "self", ".", "_to_str", "(", "self", ".", "precipitable_water", ")", ")", "out", ".", "append", "(", "self", ".", "_to_str", "(", "self", ".", "aerosol_optical_depth", ")", ")", "out", ".", "append", "(", "self", ".", "_to_str", "(", "self", ".", "snow_depth", ")", ")", "out", ".", "append", "(", "self", ".", "_to_str", "(", "self", ".", "days_since_last_snowfall", ")", ")", "out", ".", "append", "(", "self", ".", "_to_str", "(", "self", ".", "albedo", ")", ")", "out", ".", "append", "(", "self", ".", "_to_str", "(", "self", ".", "liquid_precipitation_depth", ")", ")", "out", ".", "append", "(", "self", ".", "_to_str", "(", "self", ".", "liquid_precipitation_quantity", ")", ")", "return", "\",\"", ".", "join", "(", "out", ")" ]
Exports object to its string representation. Args: top (bool): if True appends `internal_name` before values. All non list objects should be exported with value top=True, all list objects, that are embedded in as fields inlist objects should be exported with `top`=False Returns: str: The objects string representation
[ "Exports", "object", "to", "its", "string", "representation", "." ]
373d4d3c8386c8d35789f086ac5f6018c2711745
https://github.com/rbuffat/pyepw/blob/373d4d3c8386c8d35789f086ac5f6018c2711745/pyepw/epw.py#L7048-L7099
train
rbuffat/pyepw
pyepw/epw.py
EPW.add_weatherdata
def add_weatherdata(self, data): """Appends weather data. Args: data (WeatherData): weather data object """ if not isinstance(data, WeatherData): raise ValueError('Weather data need to be of type WeatherData') self._data["WEATHER DATA"].append(data)
python
def add_weatherdata(self, data): """Appends weather data. Args: data (WeatherData): weather data object """ if not isinstance(data, WeatherData): raise ValueError('Weather data need to be of type WeatherData') self._data["WEATHER DATA"].append(data)
[ "def", "add_weatherdata", "(", "self", ",", "data", ")", ":", "if", "not", "isinstance", "(", "data", ",", "WeatherData", ")", ":", "raise", "ValueError", "(", "'Weather data need to be of type WeatherData'", ")", "self", ".", "_data", "[", "\"WEATHER DATA\"", "]", ".", "append", "(", "data", ")" ]
Appends weather data. Args: data (WeatherData): weather data object
[ "Appends", "weather", "data", "." ]
373d4d3c8386c8d35789f086ac5f6018c2711745
https://github.com/rbuffat/pyepw/blob/373d4d3c8386c8d35789f086ac5f6018c2711745/pyepw/epw.py#L7315-L7324
train
rbuffat/pyepw
pyepw/epw.py
EPW.save
def save(self, path, check=True): """Save WeatherData in EPW format to path. Args: path (str): path where EPW file should be saved """ with open(path, 'w') as f: if check: if ("LOCATION" not in self._data or self._data["LOCATION"] is None): raise ValueError('location is not valid.') if ("DESIGN CONDITIONS" not in self._data or self._data["DESIGN CONDITIONS"] is None): raise ValueError('design_conditions is not valid.') if ("TYPICAL/EXTREME PERIODS" not in self._data or self._data["TYPICAL/EXTREME PERIODS"] is None): raise ValueError( 'typical_or_extreme_periods is not valid.') if ("GROUND TEMPERATURES" not in self._data or self._data["GROUND TEMPERATURES"] is None): raise ValueError('ground_temperatures is not valid.') if ("HOLIDAYS/DAYLIGHT SAVINGS" not in self._data or self._data["HOLIDAYS/DAYLIGHT SAVINGS"] is None): raise ValueError( 'holidays_or_daylight_savings is not valid.') if ("COMMENTS 1" not in self._data or self._data["COMMENTS 1"] is None): raise ValueError('comments_1 is not valid.') if ("COMMENTS 2" not in self._data or self._data["COMMENTS 2"] is None): raise ValueError('comments_2 is not valid.') if ("DATA PERIODS" not in self._data or self._data["DATA PERIODS"] is None): raise ValueError('data_periods is not valid.') if ("LOCATION" in self._data and self._data["LOCATION"] is not None): f.write(self._data["LOCATION"].export() + "\n") if ("DESIGN CONDITIONS" in self._data and self._data["DESIGN CONDITIONS"] is not None): f.write(self._data["DESIGN CONDITIONS"].export() + "\n") if ("TYPICAL/EXTREME PERIODS" in self._data and self._data["TYPICAL/EXTREME PERIODS"] is not None): f.write(self._data["TYPICAL/EXTREME PERIODS"].export() + "\n") if ("GROUND TEMPERATURES" in self._data and self._data["GROUND TEMPERATURES"] is not None): f.write(self._data["GROUND TEMPERATURES"].export() + "\n") if ("HOLIDAYS/DAYLIGHT SAVINGS" in self._data and self._data["HOLIDAYS/DAYLIGHT SAVINGS"] is not None): f.write( self._data["HOLIDAYS/DAYLIGHT SAVINGS"].export() + "\n") if ("COMMENTS 1" in self._data and self._data["COMMENTS 1"] is not None): f.write(self._data["COMMENTS 1"].export() + "\n") if ("COMMENTS 2" in self._data and self._data["COMMENTS 2"] is not None): f.write(self._data["COMMENTS 2"].export() + "\n") if ("DATA PERIODS" in self._data and self._data["DATA PERIODS"] is not None): f.write(self._data["DATA PERIODS"].export() + "\n") for item in self._data["WEATHER DATA"]: f.write(item.export(False) + "\n")
python
def save(self, path, check=True): """Save WeatherData in EPW format to path. Args: path (str): path where EPW file should be saved """ with open(path, 'w') as f: if check: if ("LOCATION" not in self._data or self._data["LOCATION"] is None): raise ValueError('location is not valid.') if ("DESIGN CONDITIONS" not in self._data or self._data["DESIGN CONDITIONS"] is None): raise ValueError('design_conditions is not valid.') if ("TYPICAL/EXTREME PERIODS" not in self._data or self._data["TYPICAL/EXTREME PERIODS"] is None): raise ValueError( 'typical_or_extreme_periods is not valid.') if ("GROUND TEMPERATURES" not in self._data or self._data["GROUND TEMPERATURES"] is None): raise ValueError('ground_temperatures is not valid.') if ("HOLIDAYS/DAYLIGHT SAVINGS" not in self._data or self._data["HOLIDAYS/DAYLIGHT SAVINGS"] is None): raise ValueError( 'holidays_or_daylight_savings is not valid.') if ("COMMENTS 1" not in self._data or self._data["COMMENTS 1"] is None): raise ValueError('comments_1 is not valid.') if ("COMMENTS 2" not in self._data or self._data["COMMENTS 2"] is None): raise ValueError('comments_2 is not valid.') if ("DATA PERIODS" not in self._data or self._data["DATA PERIODS"] is None): raise ValueError('data_periods is not valid.') if ("LOCATION" in self._data and self._data["LOCATION"] is not None): f.write(self._data["LOCATION"].export() + "\n") if ("DESIGN CONDITIONS" in self._data and self._data["DESIGN CONDITIONS"] is not None): f.write(self._data["DESIGN CONDITIONS"].export() + "\n") if ("TYPICAL/EXTREME PERIODS" in self._data and self._data["TYPICAL/EXTREME PERIODS"] is not None): f.write(self._data["TYPICAL/EXTREME PERIODS"].export() + "\n") if ("GROUND TEMPERATURES" in self._data and self._data["GROUND TEMPERATURES"] is not None): f.write(self._data["GROUND TEMPERATURES"].export() + "\n") if ("HOLIDAYS/DAYLIGHT SAVINGS" in self._data and self._data["HOLIDAYS/DAYLIGHT SAVINGS"] is not None): f.write( self._data["HOLIDAYS/DAYLIGHT SAVINGS"].export() + "\n") if ("COMMENTS 1" in self._data and self._data["COMMENTS 1"] is not None): f.write(self._data["COMMENTS 1"].export() + "\n") if ("COMMENTS 2" in self._data and self._data["COMMENTS 2"] is not None): f.write(self._data["COMMENTS 2"].export() + "\n") if ("DATA PERIODS" in self._data and self._data["DATA PERIODS"] is not None): f.write(self._data["DATA PERIODS"].export() + "\n") for item in self._data["WEATHER DATA"]: f.write(item.export(False) + "\n")
[ "def", "save", "(", "self", ",", "path", ",", "check", "=", "True", ")", ":", "with", "open", "(", "path", ",", "'w'", ")", "as", "f", ":", "if", "check", ":", "if", "(", "\"LOCATION\"", "not", "in", "self", ".", "_data", "or", "self", ".", "_data", "[", "\"LOCATION\"", "]", "is", "None", ")", ":", "raise", "ValueError", "(", "'location is not valid.'", ")", "if", "(", "\"DESIGN CONDITIONS\"", "not", "in", "self", ".", "_data", "or", "self", ".", "_data", "[", "\"DESIGN CONDITIONS\"", "]", "is", "None", ")", ":", "raise", "ValueError", "(", "'design_conditions is not valid.'", ")", "if", "(", "\"TYPICAL/EXTREME PERIODS\"", "not", "in", "self", ".", "_data", "or", "self", ".", "_data", "[", "\"TYPICAL/EXTREME PERIODS\"", "]", "is", "None", ")", ":", "raise", "ValueError", "(", "'typical_or_extreme_periods is not valid.'", ")", "if", "(", "\"GROUND TEMPERATURES\"", "not", "in", "self", ".", "_data", "or", "self", ".", "_data", "[", "\"GROUND TEMPERATURES\"", "]", "is", "None", ")", ":", "raise", "ValueError", "(", "'ground_temperatures is not valid.'", ")", "if", "(", "\"HOLIDAYS/DAYLIGHT SAVINGS\"", "not", "in", "self", ".", "_data", "or", "self", ".", "_data", "[", "\"HOLIDAYS/DAYLIGHT SAVINGS\"", "]", "is", "None", ")", ":", "raise", "ValueError", "(", "'holidays_or_daylight_savings is not valid.'", ")", "if", "(", "\"COMMENTS 1\"", "not", "in", "self", ".", "_data", "or", "self", ".", "_data", "[", "\"COMMENTS 1\"", "]", "is", "None", ")", ":", "raise", "ValueError", "(", "'comments_1 is not valid.'", ")", "if", "(", "\"COMMENTS 2\"", "not", "in", "self", ".", "_data", "or", "self", ".", "_data", "[", "\"COMMENTS 2\"", "]", "is", "None", ")", ":", "raise", "ValueError", "(", "'comments_2 is not valid.'", ")", "if", "(", "\"DATA PERIODS\"", "not", "in", "self", ".", "_data", "or", "self", ".", "_data", "[", "\"DATA PERIODS\"", "]", "is", "None", ")", ":", "raise", "ValueError", "(", "'data_periods is not valid.'", ")", "if", "(", "\"LOCATION\"", "in", "self", ".", "_data", "and", "self", ".", "_data", "[", "\"LOCATION\"", "]", "is", "not", "None", ")", ":", "f", ".", "write", "(", "self", ".", "_data", "[", "\"LOCATION\"", "]", ".", "export", "(", ")", "+", "\"\\n\"", ")", "if", "(", "\"DESIGN CONDITIONS\"", "in", "self", ".", "_data", "and", "self", ".", "_data", "[", "\"DESIGN CONDITIONS\"", "]", "is", "not", "None", ")", ":", "f", ".", "write", "(", "self", ".", "_data", "[", "\"DESIGN CONDITIONS\"", "]", ".", "export", "(", ")", "+", "\"\\n\"", ")", "if", "(", "\"TYPICAL/EXTREME PERIODS\"", "in", "self", ".", "_data", "and", "self", ".", "_data", "[", "\"TYPICAL/EXTREME PERIODS\"", "]", "is", "not", "None", ")", ":", "f", ".", "write", "(", "self", ".", "_data", "[", "\"TYPICAL/EXTREME PERIODS\"", "]", ".", "export", "(", ")", "+", "\"\\n\"", ")", "if", "(", "\"GROUND TEMPERATURES\"", "in", "self", ".", "_data", "and", "self", ".", "_data", "[", "\"GROUND TEMPERATURES\"", "]", "is", "not", "None", ")", ":", "f", ".", "write", "(", "self", ".", "_data", "[", "\"GROUND TEMPERATURES\"", "]", ".", "export", "(", ")", "+", "\"\\n\"", ")", "if", "(", "\"HOLIDAYS/DAYLIGHT SAVINGS\"", "in", "self", ".", "_data", "and", "self", ".", "_data", "[", "\"HOLIDAYS/DAYLIGHT SAVINGS\"", "]", "is", "not", "None", ")", ":", "f", ".", "write", "(", "self", ".", "_data", "[", "\"HOLIDAYS/DAYLIGHT SAVINGS\"", "]", ".", "export", "(", ")", "+", "\"\\n\"", ")", "if", "(", "\"COMMENTS 1\"", "in", "self", ".", "_data", "and", "self", ".", "_data", "[", "\"COMMENTS 1\"", "]", "is", "not", "None", ")", ":", "f", ".", "write", "(", "self", ".", "_data", "[", "\"COMMENTS 1\"", "]", ".", "export", "(", ")", "+", "\"\\n\"", ")", "if", "(", "\"COMMENTS 2\"", "in", "self", ".", "_data", "and", "self", ".", "_data", "[", "\"COMMENTS 2\"", "]", "is", "not", "None", ")", ":", "f", ".", "write", "(", "self", ".", "_data", "[", "\"COMMENTS 2\"", "]", ".", "export", "(", ")", "+", "\"\\n\"", ")", "if", "(", "\"DATA PERIODS\"", "in", "self", ".", "_data", "and", "self", ".", "_data", "[", "\"DATA PERIODS\"", "]", "is", "not", "None", ")", ":", "f", ".", "write", "(", "self", ".", "_data", "[", "\"DATA PERIODS\"", "]", ".", "export", "(", ")", "+", "\"\\n\"", ")", "for", "item", "in", "self", ".", "_data", "[", "\"WEATHER DATA\"", "]", ":", "f", ".", "write", "(", "item", ".", "export", "(", "False", ")", "+", "\"\\n\"", ")" ]
Save WeatherData in EPW format to path. Args: path (str): path where EPW file should be saved
[ "Save", "WeatherData", "in", "EPW", "format", "to", "path", "." ]
373d4d3c8386c8d35789f086ac5f6018c2711745
https://github.com/rbuffat/pyepw/blob/373d4d3c8386c8d35789f086ac5f6018c2711745/pyepw/epw.py#L7326-L7388
train
rbuffat/pyepw
pyepw/epw.py
EPW._create_datadict
def _create_datadict(cls, internal_name): """Creates an object depending on `internal_name` Args: internal_name (str): IDD name Raises: ValueError: if `internal_name` cannot be matched to a data dictionary object """ if internal_name == "LOCATION": return Location() if internal_name == "DESIGN CONDITIONS": return DesignConditions() if internal_name == "TYPICAL/EXTREME PERIODS": return TypicalOrExtremePeriods() if internal_name == "GROUND TEMPERATURES": return GroundTemperatures() if internal_name == "HOLIDAYS/DAYLIGHT SAVINGS": return HolidaysOrDaylightSavings() if internal_name == "COMMENTS 1": return Comments1() if internal_name == "COMMENTS 2": return Comments2() if internal_name == "DATA PERIODS": return DataPeriods() raise ValueError( "No DataDictionary known for {}".format(internal_name))
python
def _create_datadict(cls, internal_name): """Creates an object depending on `internal_name` Args: internal_name (str): IDD name Raises: ValueError: if `internal_name` cannot be matched to a data dictionary object """ if internal_name == "LOCATION": return Location() if internal_name == "DESIGN CONDITIONS": return DesignConditions() if internal_name == "TYPICAL/EXTREME PERIODS": return TypicalOrExtremePeriods() if internal_name == "GROUND TEMPERATURES": return GroundTemperatures() if internal_name == "HOLIDAYS/DAYLIGHT SAVINGS": return HolidaysOrDaylightSavings() if internal_name == "COMMENTS 1": return Comments1() if internal_name == "COMMENTS 2": return Comments2() if internal_name == "DATA PERIODS": return DataPeriods() raise ValueError( "No DataDictionary known for {}".format(internal_name))
[ "def", "_create_datadict", "(", "cls", ",", "internal_name", ")", ":", "if", "internal_name", "==", "\"LOCATION\"", ":", "return", "Location", "(", ")", "if", "internal_name", "==", "\"DESIGN CONDITIONS\"", ":", "return", "DesignConditions", "(", ")", "if", "internal_name", "==", "\"TYPICAL/EXTREME PERIODS\"", ":", "return", "TypicalOrExtremePeriods", "(", ")", "if", "internal_name", "==", "\"GROUND TEMPERATURES\"", ":", "return", "GroundTemperatures", "(", ")", "if", "internal_name", "==", "\"HOLIDAYS/DAYLIGHT SAVINGS\"", ":", "return", "HolidaysOrDaylightSavings", "(", ")", "if", "internal_name", "==", "\"COMMENTS 1\"", ":", "return", "Comments1", "(", ")", "if", "internal_name", "==", "\"COMMENTS 2\"", ":", "return", "Comments2", "(", ")", "if", "internal_name", "==", "\"DATA PERIODS\"", ":", "return", "DataPeriods", "(", ")", "raise", "ValueError", "(", "\"No DataDictionary known for {}\"", ".", "format", "(", "internal_name", ")", ")" ]
Creates an object depending on `internal_name` Args: internal_name (str): IDD name Raises: ValueError: if `internal_name` cannot be matched to a data dictionary object
[ "Creates", "an", "object", "depending", "on", "internal_name" ]
373d4d3c8386c8d35789f086ac5f6018c2711745
https://github.com/rbuffat/pyepw/blob/373d4d3c8386c8d35789f086ac5f6018c2711745/pyepw/epw.py#L7391-L7418
train
rbuffat/pyepw
pyepw/epw.py
EPW.read
def read(self, path): """Read EPW weather data from path. Args: path (str): path to read weather data from """ with open(path, "r") as f: for line in f: line = line.strip() match_obj_name = re.search(r"^([A-Z][A-Z/ \d]+),", line) if match_obj_name is not None: internal_name = match_obj_name.group(1) if internal_name in self._data: self._data[internal_name] = self._create_datadict( internal_name) data_line = line[len(internal_name) + 1:] vals = data_line.strip().split(',') self._data[internal_name].read(vals) else: wd = WeatherData() wd.read(line.strip().split(',')) self.add_weatherdata(wd)
python
def read(self, path): """Read EPW weather data from path. Args: path (str): path to read weather data from """ with open(path, "r") as f: for line in f: line = line.strip() match_obj_name = re.search(r"^([A-Z][A-Z/ \d]+),", line) if match_obj_name is not None: internal_name = match_obj_name.group(1) if internal_name in self._data: self._data[internal_name] = self._create_datadict( internal_name) data_line = line[len(internal_name) + 1:] vals = data_line.strip().split(',') self._data[internal_name].read(vals) else: wd = WeatherData() wd.read(line.strip().split(',')) self.add_weatherdata(wd)
[ "def", "read", "(", "self", ",", "path", ")", ":", "with", "open", "(", "path", ",", "\"r\"", ")", "as", "f", ":", "for", "line", "in", "f", ":", "line", "=", "line", ".", "strip", "(", ")", "match_obj_name", "=", "re", ".", "search", "(", "r\"^([A-Z][A-Z/ \\d]+),\"", ",", "line", ")", "if", "match_obj_name", "is", "not", "None", ":", "internal_name", "=", "match_obj_name", ".", "group", "(", "1", ")", "if", "internal_name", "in", "self", ".", "_data", ":", "self", ".", "_data", "[", "internal_name", "]", "=", "self", ".", "_create_datadict", "(", "internal_name", ")", "data_line", "=", "line", "[", "len", "(", "internal_name", ")", "+", "1", ":", "]", "vals", "=", "data_line", ".", "strip", "(", ")", ".", "split", "(", "','", ")", "self", ".", "_data", "[", "internal_name", "]", ".", "read", "(", "vals", ")", "else", ":", "wd", "=", "WeatherData", "(", ")", "wd", ".", "read", "(", "line", ".", "strip", "(", ")", ".", "split", "(", "','", ")", ")", "self", ".", "add_weatherdata", "(", "wd", ")" ]
Read EPW weather data from path. Args: path (str): path to read weather data from
[ "Read", "EPW", "weather", "data", "from", "path", "." ]
373d4d3c8386c8d35789f086ac5f6018c2711745
https://github.com/rbuffat/pyepw/blob/373d4d3c8386c8d35789f086ac5f6018c2711745/pyepw/epw.py#L7420-L7442
train
sods/ods
pods/notebook.py
display_url
def display_url(target): """Displaying URL in an IPython notebook to allow the user to click and check on information. With thanks to Fernando Perez for putting together the implementation! :param target: the url to display. :type target: string.""" prefix = u"http://" if not target.startswith("http") else u"" target = prefix + target display(HTML(u'<a href="{t}" target=_blank>{t}</a>'.format(t=target)))
python
def display_url(target): """Displaying URL in an IPython notebook to allow the user to click and check on information. With thanks to Fernando Perez for putting together the implementation! :param target: the url to display. :type target: string.""" prefix = u"http://" if not target.startswith("http") else u"" target = prefix + target display(HTML(u'<a href="{t}" target=_blank>{t}</a>'.format(t=target)))
[ "def", "display_url", "(", "target", ")", ":", "prefix", "=", "u\"http://\"", "if", "not", "target", ".", "startswith", "(", "\"http\"", ")", "else", "u\"\"", "target", "=", "prefix", "+", "target", "display", "(", "HTML", "(", "u'<a href=\"{t}\" target=_blank>{t}</a>'", ".", "format", "(", "t", "=", "target", ")", ")", ")" ]
Displaying URL in an IPython notebook to allow the user to click and check on information. With thanks to Fernando Perez for putting together the implementation! :param target: the url to display. :type target: string.
[ "Displaying", "URL", "in", "an", "IPython", "notebook", "to", "allow", "the", "user", "to", "click", "and", "check", "on", "information", ".", "With", "thanks", "to", "Fernando", "Perez", "for", "putting", "together", "the", "implementation!", ":", "param", "target", ":", "the", "url", "to", "display", ".", ":", "type", "target", ":", "string", "." ]
3995c659f25a0a640f6009ed7fcc2559ce659b1d
https://github.com/sods/ods/blob/3995c659f25a0a640f6009ed7fcc2559ce659b1d/pods/notebook.py#L11-L18
train
sods/ods
pods/notebook.py
iframe_url
def iframe_url(target, width=500, height=400, scrolling=True, border=0, frameborder=0): """Produce an iframe for displaying an item in HTML window. :param target: the target url. :type target: string :param width: the width of the iframe (default 500). :type width: int :param height: the height of the iframe (default 400). :type height: int :param scrolling: whether or not to allow scrolling (default True). :type scrolling: bool :param border: width of the border. :type border: int :param frameborder: width of the frameborder. :type frameborder: int""" prefix = u"http://" if not target.startswith("http") else u"" target = prefix + target if scrolling: scroll_val = 'yes' else: scroll_val = 'no' return u'<iframe frameborder="{frameborder}" scrolling="{scrolling}" style="border:{border}px" src="{url}", width={width} height={height}></iframe>'.format(frameborder=frameborder, scrolling=scroll_val, border=border, url=target, width=width, height=height)
python
def iframe_url(target, width=500, height=400, scrolling=True, border=0, frameborder=0): """Produce an iframe for displaying an item in HTML window. :param target: the target url. :type target: string :param width: the width of the iframe (default 500). :type width: int :param height: the height of the iframe (default 400). :type height: int :param scrolling: whether or not to allow scrolling (default True). :type scrolling: bool :param border: width of the border. :type border: int :param frameborder: width of the frameborder. :type frameborder: int""" prefix = u"http://" if not target.startswith("http") else u"" target = prefix + target if scrolling: scroll_val = 'yes' else: scroll_val = 'no' return u'<iframe frameborder="{frameborder}" scrolling="{scrolling}" style="border:{border}px" src="{url}", width={width} height={height}></iframe>'.format(frameborder=frameborder, scrolling=scroll_val, border=border, url=target, width=width, height=height)
[ "def", "iframe_url", "(", "target", ",", "width", "=", "500", ",", "height", "=", "400", ",", "scrolling", "=", "True", ",", "border", "=", "0", ",", "frameborder", "=", "0", ")", ":", "prefix", "=", "u\"http://\"", "if", "not", "target", ".", "startswith", "(", "\"http\"", ")", "else", "u\"\"", "target", "=", "prefix", "+", "target", "if", "scrolling", ":", "scroll_val", "=", "'yes'", "else", ":", "scroll_val", "=", "'no'", "return", "u'<iframe frameborder=\"{frameborder}\" scrolling=\"{scrolling}\" style=\"border:{border}px\" src=\"{url}\", width={width} height={height}></iframe>'", ".", "format", "(", "frameborder", "=", "frameborder", ",", "scrolling", "=", "scroll_val", ",", "border", "=", "border", ",", "url", "=", "target", ",", "width", "=", "width", ",", "height", "=", "height", ")" ]
Produce an iframe for displaying an item in HTML window. :param target: the target url. :type target: string :param width: the width of the iframe (default 500). :type width: int :param height: the height of the iframe (default 400). :type height: int :param scrolling: whether or not to allow scrolling (default True). :type scrolling: bool :param border: width of the border. :type border: int :param frameborder: width of the frameborder. :type frameborder: int
[ "Produce", "an", "iframe", "for", "displaying", "an", "item", "in", "HTML", "window", ".", ":", "param", "target", ":", "the", "target", "url", ".", ":", "type", "target", ":", "string", ":", "param", "width", ":", "the", "width", "of", "the", "iframe", "(", "default", "500", ")", ".", ":", "type", "width", ":", "int", ":", "param", "height", ":", "the", "height", "of", "the", "iframe", "(", "default", "400", ")", ".", ":", "type", "height", ":", "int", ":", "param", "scrolling", ":", "whether", "or", "not", "to", "allow", "scrolling", "(", "default", "True", ")", ".", ":", "type", "scrolling", ":", "bool", ":", "param", "border", ":", "width", "of", "the", "border", ".", ":", "type", "border", ":", "int", ":", "param", "frameborder", ":", "width", "of", "the", "frameborder", ".", ":", "type", "frameborder", ":", "int" ]
3995c659f25a0a640f6009ed7fcc2559ce659b1d
https://github.com/sods/ods/blob/3995c659f25a0a640f6009ed7fcc2559ce659b1d/pods/notebook.py#L20-L41
train
sods/ods
pods/notebook.py
display_iframe_url
def display_iframe_url(target, **kwargs): """Display the contents of a URL in an IPython notebook. :param target: the target url. :type target: string .. seealso:: `iframe_url()` for additional arguments.""" txt = iframe_url(target, **kwargs) display(HTML(txt))
python
def display_iframe_url(target, **kwargs): """Display the contents of a URL in an IPython notebook. :param target: the target url. :type target: string .. seealso:: `iframe_url()` for additional arguments.""" txt = iframe_url(target, **kwargs) display(HTML(txt))
[ "def", "display_iframe_url", "(", "target", ",", "*", "*", "kwargs", ")", ":", "txt", "=", "iframe_url", "(", "target", ",", "*", "*", "kwargs", ")", "display", "(", "HTML", "(", "txt", ")", ")" ]
Display the contents of a URL in an IPython notebook. :param target: the target url. :type target: string .. seealso:: `iframe_url()` for additional arguments.
[ "Display", "the", "contents", "of", "a", "URL", "in", "an", "IPython", "notebook", ".", ":", "param", "target", ":", "the", "target", "url", ".", ":", "type", "target", ":", "string" ]
3995c659f25a0a640f6009ed7fcc2559ce659b1d
https://github.com/sods/ods/blob/3995c659f25a0a640f6009ed7fcc2559ce659b1d/pods/notebook.py#L43-L52
train
sods/ods
pods/notebook.py
display_google_book
def display_google_book(id, page=None, width=700, height=500, **kwargs): """Display an embedded version of a Google book. :param id: the id of the google book to display. :type id: string :param page: the start page for the book. :type id: string or int.""" if isinstance(page, int): url = 'http://books.google.co.uk/books?id={id}&pg=PA{page}&output=embed'.format(id=id, page=page) else: url = 'http://books.google.co.uk/books?id={id}&pg={page}&output=embed'.format(id=id, page=page) display_iframe_url(url, width=width, height=height, **kwargs)
python
def display_google_book(id, page=None, width=700, height=500, **kwargs): """Display an embedded version of a Google book. :param id: the id of the google book to display. :type id: string :param page: the start page for the book. :type id: string or int.""" if isinstance(page, int): url = 'http://books.google.co.uk/books?id={id}&pg=PA{page}&output=embed'.format(id=id, page=page) else: url = 'http://books.google.co.uk/books?id={id}&pg={page}&output=embed'.format(id=id, page=page) display_iframe_url(url, width=width, height=height, **kwargs)
[ "def", "display_google_book", "(", "id", ",", "page", "=", "None", ",", "width", "=", "700", ",", "height", "=", "500", ",", "*", "*", "kwargs", ")", ":", "if", "isinstance", "(", "page", ",", "int", ")", ":", "url", "=", "'http://books.google.co.uk/books?id={id}&pg=PA{page}&output=embed'", ".", "format", "(", "id", "=", "id", ",", "page", "=", "page", ")", "else", ":", "url", "=", "'http://books.google.co.uk/books?id={id}&pg={page}&output=embed'", ".", "format", "(", "id", "=", "id", ",", "page", "=", "page", ")", "display_iframe_url", "(", "url", ",", "width", "=", "width", ",", "height", "=", "height", ",", "*", "*", "kwargs", ")" ]
Display an embedded version of a Google book. :param id: the id of the google book to display. :type id: string :param page: the start page for the book. :type id: string or int.
[ "Display", "an", "embedded", "version", "of", "a", "Google", "book", ".", ":", "param", "id", ":", "the", "id", "of", "the", "google", "book", "to", "display", ".", ":", "type", "id", ":", "string", ":", "param", "page", ":", "the", "start", "page", "for", "the", "book", ".", ":", "type", "id", ":", "string", "or", "int", "." ]
3995c659f25a0a640f6009ed7fcc2559ce659b1d
https://github.com/sods/ods/blob/3995c659f25a0a640f6009ed7fcc2559ce659b1d/pods/notebook.py#L55-L65
train
sods/ods
pods/notebook.py
code_toggle
def code_toggle(start_show=False, message=None): """Toggling on and off code in a notebook. :param start_show: Whether to display the code or not on first load (default is False). :type start_show: bool :param message: the message used to toggle display of the code. :type message: string The tip that this idea is based on is from Damian Kao (http://blog.nextgenetics.net/?e=102).""" html ='<script>\n' if message is None: message = u'The raw code for this jupyter notebook can be hidden for easier reading.' if start_show: html += u'code_show=true;\n' else: html += u'code_show=false;\n' html+='''function code_toggle() { if (code_show){ $('div.input').show(); } else { $('div.input').hide(); } code_show = !code_show } $( document ).ready(code_toggle); </script> ''' html += message + ' To toggle on/off the raw code, click <a href="javascript:code_toggle()">here</a>.' display(HTML(html))
python
def code_toggle(start_show=False, message=None): """Toggling on and off code in a notebook. :param start_show: Whether to display the code or not on first load (default is False). :type start_show: bool :param message: the message used to toggle display of the code. :type message: string The tip that this idea is based on is from Damian Kao (http://blog.nextgenetics.net/?e=102).""" html ='<script>\n' if message is None: message = u'The raw code for this jupyter notebook can be hidden for easier reading.' if start_show: html += u'code_show=true;\n' else: html += u'code_show=false;\n' html+='''function code_toggle() { if (code_show){ $('div.input').show(); } else { $('div.input').hide(); } code_show = !code_show } $( document ).ready(code_toggle); </script> ''' html += message + ' To toggle on/off the raw code, click <a href="javascript:code_toggle()">here</a>.' display(HTML(html))
[ "def", "code_toggle", "(", "start_show", "=", "False", ",", "message", "=", "None", ")", ":", "html", "=", "'<script>\\n'", "if", "message", "is", "None", ":", "message", "=", "u'The raw code for this jupyter notebook can be hidden for easier reading.'", "if", "start_show", ":", "html", "+=", "u'code_show=true;\\n'", "else", ":", "html", "+=", "u'code_show=false;\\n'", "html", "+=", "'''function code_toggle() {\n if (code_show){\n $('div.input').show();\n } else {\n $('div.input').hide();\n }\n code_show = !code_show\n} \n$( document ).ready(code_toggle);\n</script>\n'''", "html", "+=", "message", "+", "' To toggle on/off the raw code, click <a href=\"javascript:code_toggle()\">here</a>.'", "display", "(", "HTML", "(", "html", ")", ")" ]
Toggling on and off code in a notebook. :param start_show: Whether to display the code or not on first load (default is False). :type start_show: bool :param message: the message used to toggle display of the code. :type message: string The tip that this idea is based on is from Damian Kao (http://blog.nextgenetics.net/?e=102).
[ "Toggling", "on", "and", "off", "code", "in", "a", "notebook", ".", ":", "param", "start_show", ":", "Whether", "to", "display", "the", "code", "or", "not", "on", "first", "load", "(", "default", "is", "False", ")", ".", ":", "type", "start_show", ":", "bool", ":", "param", "message", ":", "the", "message", "used", "to", "toggle", "display", "of", "the", "code", ".", ":", "type", "message", ":", "string" ]
3995c659f25a0a640f6009ed7fcc2559ce659b1d
https://github.com/sods/ods/blob/3995c659f25a0a640f6009ed7fcc2559ce659b1d/pods/notebook.py#L68-L98
train
sods/ods
pods/notebook.py
display_prediction
def display_prediction(basis, num_basis=4, wlim=(-1.,1.), fig=None, ax=None, xlim=None, ylim=None, num_points=1000, offset=0.0, **kwargs): """Interactive widget for displaying a prediction function based on summing separate basis functions. :param basis: a function handle that calls the basis functions. :type basis: function handle. :param xlim: limits of the x axis to use. :param ylim: limits of the y axis to use. :param wlim: limits for the basis function weights.""" import numpy as np import pylab as plt if fig is not None: if ax is None: ax = fig.gca() if xlim is None: if ax is not None: xlim = ax.get_xlim() else: xlim = (-2., 2.) if ylim is None: if ax is not None: ylim = ax.get_ylim() else: ylim = (-1., 1.) # initialise X and set up W arguments. x = np.zeros((num_points, 1)) x[:, 0] = np.linspace(xlim[0], xlim[1], num_points) param_args = {} for i in range(num_basis): lim = list(wlim) if i ==0: lim[0] += offset lim[1] += offset param_args['w_' + str(i)] = tuple(lim) # helper function for making basis prediction. def predict_basis(w, basis, x, num_basis, **kwargs): Phi = basis(x, num_basis, **kwargs) f = np.dot(Phi, w) return f, Phi if type(basis) is dict: use_basis = basis[list(basis.keys())[0]] else: use_basis = basis f, Phi = predict_basis(np.zeros((num_basis, 1)), use_basis, x, num_basis, **kwargs) if fig is None: fig, ax=plt.subplots(figsize=(12,4)) ax.set_ylim(ylim) ax.set_xlim(xlim) predline = ax.plot(x, f, linewidth=2)[0] basislines = [] for i in range(num_basis): basislines.append(ax.plot(x, Phi[:, i], 'r')[0]) ax.set_ylim(ylim) ax.set_xlim(xlim) def generate_function(basis, num_basis, predline, basislines, basis_args, display_basis, offset, **kwargs): w = np.zeros((num_basis, 1)) for i in range(num_basis): w[i] = kwargs['w_'+ str(i)] f, Phi = predict_basis(w, basis, x, num_basis, **basis_args) predline.set_xdata(x[:, 0]) predline.set_ydata(f) for i in range(num_basis): basislines[i].set_xdata(x[:, 0]) basislines[i].set_ydata(Phi[:, i]) if display_basis: for i in range(num_basis): basislines[i].set_alpha(1) # make visible else: for i in range(num_basis): basislines[i].set_alpha(0) display(fig) if type(basis) is not dict: basis = fixed(basis) plt.close(fig) interact(generate_function, basis=basis, num_basis=fixed(num_basis), predline=fixed(predline), basislines=fixed(basislines), basis_args=fixed(kwargs), offset = fixed(offset), display_basis = False, **param_args)
python
def display_prediction(basis, num_basis=4, wlim=(-1.,1.), fig=None, ax=None, xlim=None, ylim=None, num_points=1000, offset=0.0, **kwargs): """Interactive widget for displaying a prediction function based on summing separate basis functions. :param basis: a function handle that calls the basis functions. :type basis: function handle. :param xlim: limits of the x axis to use. :param ylim: limits of the y axis to use. :param wlim: limits for the basis function weights.""" import numpy as np import pylab as plt if fig is not None: if ax is None: ax = fig.gca() if xlim is None: if ax is not None: xlim = ax.get_xlim() else: xlim = (-2., 2.) if ylim is None: if ax is not None: ylim = ax.get_ylim() else: ylim = (-1., 1.) # initialise X and set up W arguments. x = np.zeros((num_points, 1)) x[:, 0] = np.linspace(xlim[0], xlim[1], num_points) param_args = {} for i in range(num_basis): lim = list(wlim) if i ==0: lim[0] += offset lim[1] += offset param_args['w_' + str(i)] = tuple(lim) # helper function for making basis prediction. def predict_basis(w, basis, x, num_basis, **kwargs): Phi = basis(x, num_basis, **kwargs) f = np.dot(Phi, w) return f, Phi if type(basis) is dict: use_basis = basis[list(basis.keys())[0]] else: use_basis = basis f, Phi = predict_basis(np.zeros((num_basis, 1)), use_basis, x, num_basis, **kwargs) if fig is None: fig, ax=plt.subplots(figsize=(12,4)) ax.set_ylim(ylim) ax.set_xlim(xlim) predline = ax.plot(x, f, linewidth=2)[0] basislines = [] for i in range(num_basis): basislines.append(ax.plot(x, Phi[:, i], 'r')[0]) ax.set_ylim(ylim) ax.set_xlim(xlim) def generate_function(basis, num_basis, predline, basislines, basis_args, display_basis, offset, **kwargs): w = np.zeros((num_basis, 1)) for i in range(num_basis): w[i] = kwargs['w_'+ str(i)] f, Phi = predict_basis(w, basis, x, num_basis, **basis_args) predline.set_xdata(x[:, 0]) predline.set_ydata(f) for i in range(num_basis): basislines[i].set_xdata(x[:, 0]) basislines[i].set_ydata(Phi[:, i]) if display_basis: for i in range(num_basis): basislines[i].set_alpha(1) # make visible else: for i in range(num_basis): basislines[i].set_alpha(0) display(fig) if type(basis) is not dict: basis = fixed(basis) plt.close(fig) interact(generate_function, basis=basis, num_basis=fixed(num_basis), predline=fixed(predline), basislines=fixed(basislines), basis_args=fixed(kwargs), offset = fixed(offset), display_basis = False, **param_args)
[ "def", "display_prediction", "(", "basis", ",", "num_basis", "=", "4", ",", "wlim", "=", "(", "-", "1.", ",", "1.", ")", ",", "fig", "=", "None", ",", "ax", "=", "None", ",", "xlim", "=", "None", ",", "ylim", "=", "None", ",", "num_points", "=", "1000", ",", "offset", "=", "0.0", ",", "*", "*", "kwargs", ")", ":", "import", "numpy", "as", "np", "import", "pylab", "as", "plt", "if", "fig", "is", "not", "None", ":", "if", "ax", "is", "None", ":", "ax", "=", "fig", ".", "gca", "(", ")", "if", "xlim", "is", "None", ":", "if", "ax", "is", "not", "None", ":", "xlim", "=", "ax", ".", "get_xlim", "(", ")", "else", ":", "xlim", "=", "(", "-", "2.", ",", "2.", ")", "if", "ylim", "is", "None", ":", "if", "ax", "is", "not", "None", ":", "ylim", "=", "ax", ".", "get_ylim", "(", ")", "else", ":", "ylim", "=", "(", "-", "1.", ",", "1.", ")", "# initialise X and set up W arguments.", "x", "=", "np", ".", "zeros", "(", "(", "num_points", ",", "1", ")", ")", "x", "[", ":", ",", "0", "]", "=", "np", ".", "linspace", "(", "xlim", "[", "0", "]", ",", "xlim", "[", "1", "]", ",", "num_points", ")", "param_args", "=", "{", "}", "for", "i", "in", "range", "(", "num_basis", ")", ":", "lim", "=", "list", "(", "wlim", ")", "if", "i", "==", "0", ":", "lim", "[", "0", "]", "+=", "offset", "lim", "[", "1", "]", "+=", "offset", "param_args", "[", "'w_'", "+", "str", "(", "i", ")", "]", "=", "tuple", "(", "lim", ")", "# helper function for making basis prediction.", "def", "predict_basis", "(", "w", ",", "basis", ",", "x", ",", "num_basis", ",", "*", "*", "kwargs", ")", ":", "Phi", "=", "basis", "(", "x", ",", "num_basis", ",", "*", "*", "kwargs", ")", "f", "=", "np", ".", "dot", "(", "Phi", ",", "w", ")", "return", "f", ",", "Phi", "if", "type", "(", "basis", ")", "is", "dict", ":", "use_basis", "=", "basis", "[", "list", "(", "basis", ".", "keys", "(", ")", ")", "[", "0", "]", "]", "else", ":", "use_basis", "=", "basis", "f", ",", "Phi", "=", "predict_basis", "(", "np", ".", "zeros", "(", "(", "num_basis", ",", "1", ")", ")", ",", "use_basis", ",", "x", ",", "num_basis", ",", "*", "*", "kwargs", ")", "if", "fig", "is", "None", ":", "fig", ",", "ax", "=", "plt", ".", "subplots", "(", "figsize", "=", "(", "12", ",", "4", ")", ")", "ax", ".", "set_ylim", "(", "ylim", ")", "ax", ".", "set_xlim", "(", "xlim", ")", "predline", "=", "ax", ".", "plot", "(", "x", ",", "f", ",", "linewidth", "=", "2", ")", "[", "0", "]", "basislines", "=", "[", "]", "for", "i", "in", "range", "(", "num_basis", ")", ":", "basislines", ".", "append", "(", "ax", ".", "plot", "(", "x", ",", "Phi", "[", ":", ",", "i", "]", ",", "'r'", ")", "[", "0", "]", ")", "ax", ".", "set_ylim", "(", "ylim", ")", "ax", ".", "set_xlim", "(", "xlim", ")", "def", "generate_function", "(", "basis", ",", "num_basis", ",", "predline", ",", "basislines", ",", "basis_args", ",", "display_basis", ",", "offset", ",", "*", "*", "kwargs", ")", ":", "w", "=", "np", ".", "zeros", "(", "(", "num_basis", ",", "1", ")", ")", "for", "i", "in", "range", "(", "num_basis", ")", ":", "w", "[", "i", "]", "=", "kwargs", "[", "'w_'", "+", "str", "(", "i", ")", "]", "f", ",", "Phi", "=", "predict_basis", "(", "w", ",", "basis", ",", "x", ",", "num_basis", ",", "*", "*", "basis_args", ")", "predline", ".", "set_xdata", "(", "x", "[", ":", ",", "0", "]", ")", "predline", ".", "set_ydata", "(", "f", ")", "for", "i", "in", "range", "(", "num_basis", ")", ":", "basislines", "[", "i", "]", ".", "set_xdata", "(", "x", "[", ":", ",", "0", "]", ")", "basislines", "[", "i", "]", ".", "set_ydata", "(", "Phi", "[", ":", ",", "i", "]", ")", "if", "display_basis", ":", "for", "i", "in", "range", "(", "num_basis", ")", ":", "basislines", "[", "i", "]", ".", "set_alpha", "(", "1", ")", "# make visible", "else", ":", "for", "i", "in", "range", "(", "num_basis", ")", ":", "basislines", "[", "i", "]", ".", "set_alpha", "(", "0", ")", "display", "(", "fig", ")", "if", "type", "(", "basis", ")", "is", "not", "dict", ":", "basis", "=", "fixed", "(", "basis", ")", "plt", ".", "close", "(", "fig", ")", "interact", "(", "generate_function", ",", "basis", "=", "basis", ",", "num_basis", "=", "fixed", "(", "num_basis", ")", ",", "predline", "=", "fixed", "(", "predline", ")", ",", "basislines", "=", "fixed", "(", "basislines", ")", ",", "basis_args", "=", "fixed", "(", "kwargs", ")", ",", "offset", "=", "fixed", "(", "offset", ")", ",", "display_basis", "=", "False", ",", "*", "*", "param_args", ")" ]
Interactive widget for displaying a prediction function based on summing separate basis functions. :param basis: a function handle that calls the basis functions. :type basis: function handle. :param xlim: limits of the x axis to use. :param ylim: limits of the y axis to use. :param wlim: limits for the basis function weights.
[ "Interactive", "widget", "for", "displaying", "a", "prediction", "function", "based", "on", "summing", "separate", "basis", "functions", ".", ":", "param", "basis", ":", "a", "function", "handle", "that", "calls", "the", "basis", "functions", ".", ":", "type", "basis", ":", "function", "handle", ".", ":", "param", "xlim", ":", "limits", "of", "the", "x", "axis", "to", "use", ".", ":", "param", "ylim", ":", "limits", "of", "the", "y", "axis", "to", "use", ".", ":", "param", "wlim", ":", "limits", "for", "the", "basis", "function", "weights", "." ]
3995c659f25a0a640f6009ed7fcc2559ce659b1d
https://github.com/sods/ods/blob/3995c659f25a0a640f6009ed7fcc2559ce659b1d/pods/notebook.py#L102-L195
train
sods/ods
pods/notebook.py
display_plots
def display_plots(filebase, directory=None, width=700, height=500, **kwargs): """Display a series of plots controlled by sliders. The function relies on Python string format functionality to index through a series of plots.""" def show_figure(filebase, directory, **kwargs): """Helper function to load in the relevant plot for display.""" filename = filebase.format(**kwargs) if directory is not None: filename = directory + '/' + filename display(HTML("<img src='{filename}'>".format(filename=filename))) interact(show_figure, filebase=fixed(filebase), directory=fixed(directory), **kwargs)
python
def display_plots(filebase, directory=None, width=700, height=500, **kwargs): """Display a series of plots controlled by sliders. The function relies on Python string format functionality to index through a series of plots.""" def show_figure(filebase, directory, **kwargs): """Helper function to load in the relevant plot for display.""" filename = filebase.format(**kwargs) if directory is not None: filename = directory + '/' + filename display(HTML("<img src='{filename}'>".format(filename=filename))) interact(show_figure, filebase=fixed(filebase), directory=fixed(directory), **kwargs)
[ "def", "display_plots", "(", "filebase", ",", "directory", "=", "None", ",", "width", "=", "700", ",", "height", "=", "500", ",", "*", "*", "kwargs", ")", ":", "def", "show_figure", "(", "filebase", ",", "directory", ",", "*", "*", "kwargs", ")", ":", "\"\"\"Helper function to load in the relevant plot for display.\"\"\"", "filename", "=", "filebase", ".", "format", "(", "*", "*", "kwargs", ")", "if", "directory", "is", "not", "None", ":", "filename", "=", "directory", "+", "'/'", "+", "filename", "display", "(", "HTML", "(", "\"<img src='{filename}'>\"", ".", "format", "(", "filename", "=", "filename", ")", ")", ")", "interact", "(", "show_figure", ",", "filebase", "=", "fixed", "(", "filebase", ")", ",", "directory", "=", "fixed", "(", "directory", ")", ",", "*", "*", "kwargs", ")" ]
Display a series of plots controlled by sliders. The function relies on Python string format functionality to index through a series of plots.
[ "Display", "a", "series", "of", "plots", "controlled", "by", "sliders", ".", "The", "function", "relies", "on", "Python", "string", "format", "functionality", "to", "index", "through", "a", "series", "of", "plots", "." ]
3995c659f25a0a640f6009ed7fcc2559ce659b1d
https://github.com/sods/ods/blob/3995c659f25a0a640f6009ed7fcc2559ce659b1d/pods/notebook.py#L198-L207
train
sods/ods
pods/assesser.py
answer
def answer(part, module='mlai2014.json'): """Returns the answers to the lab classes.""" marks = json.load(open(os.path.join(data_directory, module), 'rb')) return marks['Lab ' + str(part+1)]
python
def answer(part, module='mlai2014.json'): """Returns the answers to the lab classes.""" marks = json.load(open(os.path.join(data_directory, module), 'rb')) return marks['Lab ' + str(part+1)]
[ "def", "answer", "(", "part", ",", "module", "=", "'mlai2014.json'", ")", ":", "marks", "=", "json", ".", "load", "(", "open", "(", "os", ".", "path", ".", "join", "(", "data_directory", ",", "module", ")", ",", "'rb'", ")", ")", "return", "marks", "[", "'Lab '", "+", "str", "(", "part", "+", "1", ")", "]" ]
Returns the answers to the lab classes.
[ "Returns", "the", "answers", "to", "the", "lab", "classes", "." ]
3995c659f25a0a640f6009ed7fcc2559ce659b1d
https://github.com/sods/ods/blob/3995c659f25a0a640f6009ed7fcc2559ce659b1d/pods/assesser.py#L289-L292
train
sods/ods
pods/assesser.py
assessment.latex
def latex(self): """Gives a latex representation of the assessment.""" output = self.latex_preamble output += self._repr_latex_() output += self.latex_post return output
python
def latex(self): """Gives a latex representation of the assessment.""" output = self.latex_preamble output += self._repr_latex_() output += self.latex_post return output
[ "def", "latex", "(", "self", ")", ":", "output", "=", "self", ".", "latex_preamble", "output", "+=", "self", ".", "_repr_latex_", "(", ")", "output", "+=", "self", ".", "latex_post", "return", "output" ]
Gives a latex representation of the assessment.
[ "Gives", "a", "latex", "representation", "of", "the", "assessment", "." ]
3995c659f25a0a640f6009ed7fcc2559ce659b1d
https://github.com/sods/ods/blob/3995c659f25a0a640f6009ed7fcc2559ce659b1d/pods/assesser.py#L145-L150
train
sods/ods
pods/assesser.py
assessment.html
def html(self): """Gives an html representation of the assessment.""" output = self.html_preamble output += self._repr_html_() output += self.html_post return output
python
def html(self): """Gives an html representation of the assessment.""" output = self.html_preamble output += self._repr_html_() output += self.html_post return output
[ "def", "html", "(", "self", ")", ":", "output", "=", "self", ".", "html_preamble", "output", "+=", "self", ".", "_repr_html_", "(", ")", "output", "+=", "self", ".", "html_post", "return", "output" ]
Gives an html representation of the assessment.
[ "Gives", "an", "html", "representation", "of", "the", "assessment", "." ]
3995c659f25a0a640f6009ed7fcc2559ce659b1d
https://github.com/sods/ods/blob/3995c659f25a0a640f6009ed7fcc2559ce659b1d/pods/assesser.py#L152-L157
train
sods/ods
pods/assesser.py
assessment.marksheet
def marksheet(self): """Returns an pandas empty dataframe object containing rows and columns for marking. This can then be passed to a google doc that is distributed to markers for editing with the mark for each section.""" columns=['Number', 'Question', 'Correct (a fraction)', 'Max Mark', 'Comments'] mark_sheet = pd.DataFrame() for qu_number, question in enumerate(self.answers): part_no = 0 for number, part in enumerate(question): if number>0: if part[2] > 0: part_no += 1 index = str(qu_number+1) +'_'+str(part_no) frame = pd.DataFrame(columns=columns, index=[index]) frame.loc[index]['Number'] = index frame.loc[index]['Question'] = part[0] frame.loc[index]['Max Mark'] = part[2] mark_sheet = mark_sheet.append(frame) return mark_sheet.sort(columns='Number')
python
def marksheet(self): """Returns an pandas empty dataframe object containing rows and columns for marking. This can then be passed to a google doc that is distributed to markers for editing with the mark for each section.""" columns=['Number', 'Question', 'Correct (a fraction)', 'Max Mark', 'Comments'] mark_sheet = pd.DataFrame() for qu_number, question in enumerate(self.answers): part_no = 0 for number, part in enumerate(question): if number>0: if part[2] > 0: part_no += 1 index = str(qu_number+1) +'_'+str(part_no) frame = pd.DataFrame(columns=columns, index=[index]) frame.loc[index]['Number'] = index frame.loc[index]['Question'] = part[0] frame.loc[index]['Max Mark'] = part[2] mark_sheet = mark_sheet.append(frame) return mark_sheet.sort(columns='Number')
[ "def", "marksheet", "(", "self", ")", ":", "columns", "=", "[", "'Number'", ",", "'Question'", ",", "'Correct (a fraction)'", ",", "'Max Mark'", ",", "'Comments'", "]", "mark_sheet", "=", "pd", ".", "DataFrame", "(", ")", "for", "qu_number", ",", "question", "in", "enumerate", "(", "self", ".", "answers", ")", ":", "part_no", "=", "0", "for", "number", ",", "part", "in", "enumerate", "(", "question", ")", ":", "if", "number", ">", "0", ":", "if", "part", "[", "2", "]", ">", "0", ":", "part_no", "+=", "1", "index", "=", "str", "(", "qu_number", "+", "1", ")", "+", "'_'", "+", "str", "(", "part_no", ")", "frame", "=", "pd", ".", "DataFrame", "(", "columns", "=", "columns", ",", "index", "=", "[", "index", "]", ")", "frame", ".", "loc", "[", "index", "]", "[", "'Number'", "]", "=", "index", "frame", ".", "loc", "[", "index", "]", "[", "'Question'", "]", "=", "part", "[", "0", "]", "frame", ".", "loc", "[", "index", "]", "[", "'Max Mark'", "]", "=", "part", "[", "2", "]", "mark_sheet", "=", "mark_sheet", ".", "append", "(", "frame", ")", "return", "mark_sheet", ".", "sort", "(", "columns", "=", "'Number'", ")" ]
Returns an pandas empty dataframe object containing rows and columns for marking. This can then be passed to a google doc that is distributed to markers for editing with the mark for each section.
[ "Returns", "an", "pandas", "empty", "dataframe", "object", "containing", "rows", "and", "columns", "for", "marking", ".", "This", "can", "then", "be", "passed", "to", "a", "google", "doc", "that", "is", "distributed", "to", "markers", "for", "editing", "with", "the", "mark", "for", "each", "section", "." ]
3995c659f25a0a640f6009ed7fcc2559ce659b1d
https://github.com/sods/ods/blob/3995c659f25a0a640f6009ed7fcc2559ce659b1d/pods/assesser.py#L211-L228
train
sods/ods
pods/assesser.py
assessment.total_marks
def total_marks(self): """Compute the total mark for the assessment.""" total = 0 for answer in self.answers: for number, part in enumerate(answer): if number>0: if part[2]>0: total+=part[2] return total
python
def total_marks(self): """Compute the total mark for the assessment.""" total = 0 for answer in self.answers: for number, part in enumerate(answer): if number>0: if part[2]>0: total+=part[2] return total
[ "def", "total_marks", "(", "self", ")", ":", "total", "=", "0", "for", "answer", "in", "self", ".", "answers", ":", "for", "number", ",", "part", "in", "enumerate", "(", "answer", ")", ":", "if", "number", ">", "0", ":", "if", "part", "[", "2", "]", ">", "0", ":", "total", "+=", "part", "[", "2", "]", "return", "total" ]
Compute the total mark for the assessment.
[ "Compute", "the", "total", "mark", "for", "the", "assessment", "." ]
3995c659f25a0a640f6009ed7fcc2559ce659b1d
https://github.com/sods/ods/blob/3995c659f25a0a640f6009ed7fcc2559ce659b1d/pods/assesser.py#L230-L238
train
sods/ods
pods/lab.py
download
def download(name, course, github='SheffieldML/notebook/master/lab_classes/'): """Download a lab class from the relevant course :param course: the course short name to download the class from. :type course: string :param reference: reference to the course for downloading the class. :type reference: string :param github: github repo for downloading the course from. :type string: github repo for downloading the lab.""" github_stub = 'https://raw.githubusercontent.com/' if not name.endswith('.ipynb'): name += '.ipynb' from pods.util import download_url download_url(os.path.join(github_stub, github, course, name), store_directory=course)
python
def download(name, course, github='SheffieldML/notebook/master/lab_classes/'): """Download a lab class from the relevant course :param course: the course short name to download the class from. :type course: string :param reference: reference to the course for downloading the class. :type reference: string :param github: github repo for downloading the course from. :type string: github repo for downloading the lab.""" github_stub = 'https://raw.githubusercontent.com/' if not name.endswith('.ipynb'): name += '.ipynb' from pods.util import download_url download_url(os.path.join(github_stub, github, course, name), store_directory=course)
[ "def", "download", "(", "name", ",", "course", ",", "github", "=", "'SheffieldML/notebook/master/lab_classes/'", ")", ":", "github_stub", "=", "'https://raw.githubusercontent.com/'", "if", "not", "name", ".", "endswith", "(", "'.ipynb'", ")", ":", "name", "+=", "'.ipynb'", "from", "pods", ".", "util", "import", "download_url", "download_url", "(", "os", ".", "path", ".", "join", "(", "github_stub", ",", "github", ",", "course", ",", "name", ")", ",", "store_directory", "=", "course", ")" ]
Download a lab class from the relevant course :param course: the course short name to download the class from. :type course: string :param reference: reference to the course for downloading the class. :type reference: string :param github: github repo for downloading the course from. :type string: github repo for downloading the lab.
[ "Download", "a", "lab", "class", "from", "the", "relevant", "course", ":", "param", "course", ":", "the", "course", "short", "name", "to", "download", "the", "class", "from", ".", ":", "type", "course", ":", "string", ":", "param", "reference", ":", "reference", "to", "the", "course", "for", "downloading", "the", "class", ".", ":", "type", "reference", ":", "string", ":", "param", "github", ":", "github", "repo", "for", "downloading", "the", "course", "from", ".", ":", "type", "string", ":", "github", "repo", "for", "downloading", "the", "lab", "." ]
3995c659f25a0a640f6009ed7fcc2559ce659b1d
https://github.com/sods/ods/blob/3995c659f25a0a640f6009ed7fcc2559ce659b1d/pods/lab.py#L316-L329
train
rbuffat/pyepw
generator/templates/class.py
read
def read(self, vals): """ Read values Args: vals (list): list of strings representing values """ i = 0 {%- for field in fields %} {%- if field.is_list %} count = int(vals[i]) i += 1 for _ in range(count): obj = {{field.object_name}}() obj.read(vals[i:i + obj.field_count]) self.add_{{field.field_name}}(obj) i += obj.field_count {%- else %} if len(vals[i]) == 0: self.{{field.field_name}} = None else: self.{{field.field_name}} = vals[i] i += 1 {%- endif %} {%- endfor %}
python
def read(self, vals): """ Read values Args: vals (list): list of strings representing values """ i = 0 {%- for field in fields %} {%- if field.is_list %} count = int(vals[i]) i += 1 for _ in range(count): obj = {{field.object_name}}() obj.read(vals[i:i + obj.field_count]) self.add_{{field.field_name}}(obj) i += obj.field_count {%- else %} if len(vals[i]) == 0: self.{{field.field_name}} = None else: self.{{field.field_name}} = vals[i] i += 1 {%- endif %} {%- endfor %}
[ "def", "read", "(", "self", ",", "vals", ")", ":", "i", "=", "0", "{", "%", "-", "for", "field", "in", "fields", "%", "}", "{", "%", "-", "if", "field", ".", "is_list", "%", "}", "count", "=", "int", "(", "vals", "[", "i", "]", ")", "i", "+=", "1", "for", "_", "in", "range", "(", "count", ")", ":", "obj", "=", "{", "{", "field", ".", "object_name", "}", "}", "(", ")", "obj", ".", "read", "(", "vals", "[", "i", ":", "i", "+", "obj", ".", "field_count", "]", ")", "self", ".", "add_", "{", "{", "field", ".", "field_name", "}", "}", "(", "obj", ")", "i", "+=", "obj", ".", "field_count", "{", "%", "-", "else", "%", "}", "if", "len", "(", "vals", "[", "i", "]", ")", "==", "0", ":", "self", ".", "{", "{", "field", ".", "field_name", "}", "}", "=", "None", "else", ":", "self", ".", "{", "{", "field", ".", "field_name", "}", "}", "=", "vals", "[", "i", "]", "i", "+=", "1", "{", "%", "-", "endif", "%", "}", "{", "%", "-", "endfor", "%", "}" ]
Read values Args: vals (list): list of strings representing values
[ "Read", "values", "Args", ":", "vals", "(", "list", ")", ":", "list", "of", "strings", "representing", "values" ]
373d4d3c8386c8d35789f086ac5f6018c2711745
https://github.com/rbuffat/pyepw/blob/373d4d3c8386c8d35789f086ac5f6018c2711745/generator/templates/class.py#L18-L41
train
sods/ods
pods/datasets.py
permute
def permute(num): "Permutation for randomizing data order." if permute_data: return np.random.permutation(num) else: logging.warning("Warning not permuting data") return np.arange(num)
python
def permute(num): "Permutation for randomizing data order." if permute_data: return np.random.permutation(num) else: logging.warning("Warning not permuting data") return np.arange(num)
[ "def", "permute", "(", "num", ")", ":", "if", "permute_data", ":", "return", "np", ".", "random", ".", "permutation", "(", "num", ")", "else", ":", "logging", ".", "warning", "(", "\"Warning not permuting data\"", ")", "return", "np", ".", "arange", "(", "num", ")" ]
Permutation for randomizing data order.
[ "Permutation", "for", "randomizing", "data", "order", "." ]
3995c659f25a0a640f6009ed7fcc2559ce659b1d
https://github.com/sods/ods/blob/3995c659f25a0a640f6009ed7fcc2559ce659b1d/pods/datasets.py#L75-L81
train
sods/ods
pods/datasets.py
discrete
def discrete(cats, name='discrete'): """Return a class category that shows the encoding""" import json ks = list(cats) for key in ks: if isinstance(key, bytes): cats[key.decode('utf-8')] = cats.pop(key) return 'discrete(' + json.dumps([cats, name]) + ')'
python
def discrete(cats, name='discrete'): """Return a class category that shows the encoding""" import json ks = list(cats) for key in ks: if isinstance(key, bytes): cats[key.decode('utf-8')] = cats.pop(key) return 'discrete(' + json.dumps([cats, name]) + ')'
[ "def", "discrete", "(", "cats", ",", "name", "=", "'discrete'", ")", ":", "import", "json", "ks", "=", "list", "(", "cats", ")", "for", "key", "in", "ks", ":", "if", "isinstance", "(", "key", ",", "bytes", ")", ":", "cats", "[", "key", ".", "decode", "(", "'utf-8'", ")", "]", "=", "cats", ".", "pop", "(", "key", ")", "return", "'discrete('", "+", "json", ".", "dumps", "(", "[", "cats", ",", "name", "]", ")", "+", "')'" ]
Return a class category that shows the encoding
[ "Return", "a", "class", "category", "that", "shows", "the", "encoding" ]
3995c659f25a0a640f6009ed7fcc2559ce659b1d
https://github.com/sods/ods/blob/3995c659f25a0a640f6009ed7fcc2559ce659b1d/pods/datasets.py#L92-L99
train
sods/ods
pods/datasets.py
prompt_stdin
def prompt_stdin(prompt): """Ask user for agreeing to data set licenses.""" # raw_input returns the empty string for "enter" yes = set(['yes', 'y']) no = set(['no','n']) try: print(prompt) if sys.version_info>=(3,0): choice = input().lower() else: choice = raw_input().lower() # would like to test for which exceptions here except: print('Stdin is not implemented.') print('You need to set') print('overide_manual_authorize=True') print('to proceed with the download. Please set that variable and continue.') raise if choice in yes: return True elif choice in no: return False else: print("Your response was a " + choice) print("Please respond with 'yes', 'y' or 'no', 'n'")
python
def prompt_stdin(prompt): """Ask user for agreeing to data set licenses.""" # raw_input returns the empty string for "enter" yes = set(['yes', 'y']) no = set(['no','n']) try: print(prompt) if sys.version_info>=(3,0): choice = input().lower() else: choice = raw_input().lower() # would like to test for which exceptions here except: print('Stdin is not implemented.') print('You need to set') print('overide_manual_authorize=True') print('to proceed with the download. Please set that variable and continue.') raise if choice in yes: return True elif choice in no: return False else: print("Your response was a " + choice) print("Please respond with 'yes', 'y' or 'no', 'n'")
[ "def", "prompt_stdin", "(", "prompt", ")", ":", "# raw_input returns the empty string for \"enter\"", "yes", "=", "set", "(", "[", "'yes'", ",", "'y'", "]", ")", "no", "=", "set", "(", "[", "'no'", ",", "'n'", "]", ")", "try", ":", "print", "(", "prompt", ")", "if", "sys", ".", "version_info", ">=", "(", "3", ",", "0", ")", ":", "choice", "=", "input", "(", ")", ".", "lower", "(", ")", "else", ":", "choice", "=", "raw_input", "(", ")", ".", "lower", "(", ")", "# would like to test for which exceptions here", "except", ":", "print", "(", "'Stdin is not implemented.'", ")", "print", "(", "'You need to set'", ")", "print", "(", "'overide_manual_authorize=True'", ")", "print", "(", "'to proceed with the download. Please set that variable and continue.'", ")", "raise", "if", "choice", "in", "yes", ":", "return", "True", "elif", "choice", "in", "no", ":", "return", "False", "else", ":", "print", "(", "\"Your response was a \"", "+", "choice", ")", "print", "(", "\"Please respond with 'yes', 'y' or 'no', 'n'\"", ")" ]
Ask user for agreeing to data set licenses.
[ "Ask", "user", "for", "agreeing", "to", "data", "set", "licenses", "." ]
3995c659f25a0a640f6009ed7fcc2559ce659b1d
https://github.com/sods/ods/blob/3995c659f25a0a640f6009ed7fcc2559ce659b1d/pods/datasets.py#L117-L144
train
sods/ods
pods/datasets.py
clear_cache
def clear_cache(dataset_name=None): """Remove a data set from the cache""" dr = data_resources[dataset_name] if 'dirs' in dr: for dirs, files in zip(dr['dirs'], dr['files']): for dir, file in zip(dirs, files): path = os.path.join(data_path, dataset_name, dir, file) if os.path.exists(path): logging.info("clear_cache: removing " + path) os.unlink(path) for dir in dirs: path = os.path.join(data_path, dataset_name, dir) if os.path.exists(path): logging.info("clear_cache: remove directory " + path) os.rmdir(path) else: for file_list in dr['files']: for file in file_list: path = os.path.join(data_path, dataset_name, file) if os.path.exists(path): logging.info("clear_cache: remove " + path) os.unlink(path)
python
def clear_cache(dataset_name=None): """Remove a data set from the cache""" dr = data_resources[dataset_name] if 'dirs' in dr: for dirs, files in zip(dr['dirs'], dr['files']): for dir, file in zip(dirs, files): path = os.path.join(data_path, dataset_name, dir, file) if os.path.exists(path): logging.info("clear_cache: removing " + path) os.unlink(path) for dir in dirs: path = os.path.join(data_path, dataset_name, dir) if os.path.exists(path): logging.info("clear_cache: remove directory " + path) os.rmdir(path) else: for file_list in dr['files']: for file in file_list: path = os.path.join(data_path, dataset_name, file) if os.path.exists(path): logging.info("clear_cache: remove " + path) os.unlink(path)
[ "def", "clear_cache", "(", "dataset_name", "=", "None", ")", ":", "dr", "=", "data_resources", "[", "dataset_name", "]", "if", "'dirs'", "in", "dr", ":", "for", "dirs", ",", "files", "in", "zip", "(", "dr", "[", "'dirs'", "]", ",", "dr", "[", "'files'", "]", ")", ":", "for", "dir", ",", "file", "in", "zip", "(", "dirs", ",", "files", ")", ":", "path", "=", "os", ".", "path", ".", "join", "(", "data_path", ",", "dataset_name", ",", "dir", ",", "file", ")", "if", "os", ".", "path", ".", "exists", "(", "path", ")", ":", "logging", ".", "info", "(", "\"clear_cache: removing \"", "+", "path", ")", "os", ".", "unlink", "(", "path", ")", "for", "dir", "in", "dirs", ":", "path", "=", "os", ".", "path", ".", "join", "(", "data_path", ",", "dataset_name", ",", "dir", ")", "if", "os", ".", "path", ".", "exists", "(", "path", ")", ":", "logging", ".", "info", "(", "\"clear_cache: remove directory \"", "+", "path", ")", "os", ".", "rmdir", "(", "path", ")", "else", ":", "for", "file_list", "in", "dr", "[", "'files'", "]", ":", "for", "file", "in", "file_list", ":", "path", "=", "os", ".", "path", ".", "join", "(", "data_path", ",", "dataset_name", ",", "file", ")", "if", "os", ".", "path", ".", "exists", "(", "path", ")", ":", "logging", ".", "info", "(", "\"clear_cache: remove \"", "+", "path", ")", "os", ".", "unlink", "(", "path", ")" ]
Remove a data set from the cache
[ "Remove", "a", "data", "set", "from", "the", "cache" ]
3995c659f25a0a640f6009ed7fcc2559ce659b1d
https://github.com/sods/ods/blob/3995c659f25a0a640f6009ed7fcc2559ce659b1d/pods/datasets.py#L147-L169
train
sods/ods
pods/datasets.py
data_available
def data_available(dataset_name=None): """Check if the data set is available on the local machine already.""" dr = data_resources[dataset_name] if 'dirs' in dr: for dirs, files in zip(dr['dirs'], dr['files']): for dir, file in zip(dirs, files): if not os.path.exists(os.path.join(data_path, dataset_name, dir, file)): return False else: for file_list in dr['files']: for file in file_list: if not os.path.exists(os.path.join(data_path, dataset_name, file)): return False return True
python
def data_available(dataset_name=None): """Check if the data set is available on the local machine already.""" dr = data_resources[dataset_name] if 'dirs' in dr: for dirs, files in zip(dr['dirs'], dr['files']): for dir, file in zip(dirs, files): if not os.path.exists(os.path.join(data_path, dataset_name, dir, file)): return False else: for file_list in dr['files']: for file in file_list: if not os.path.exists(os.path.join(data_path, dataset_name, file)): return False return True
[ "def", "data_available", "(", "dataset_name", "=", "None", ")", ":", "dr", "=", "data_resources", "[", "dataset_name", "]", "if", "'dirs'", "in", "dr", ":", "for", "dirs", ",", "files", "in", "zip", "(", "dr", "[", "'dirs'", "]", ",", "dr", "[", "'files'", "]", ")", ":", "for", "dir", ",", "file", "in", "zip", "(", "dirs", ",", "files", ")", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "os", ".", "path", ".", "join", "(", "data_path", ",", "dataset_name", ",", "dir", ",", "file", ")", ")", ":", "return", "False", "else", ":", "for", "file_list", "in", "dr", "[", "'files'", "]", ":", "for", "file", "in", "file_list", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "os", ".", "path", ".", "join", "(", "data_path", ",", "dataset_name", ",", "file", ")", ")", ":", "return", "False", "return", "True" ]
Check if the data set is available on the local machine already.
[ "Check", "if", "the", "data", "set", "is", "available", "on", "the", "local", "machine", "already", "." ]
3995c659f25a0a640f6009ed7fcc2559ce659b1d
https://github.com/sods/ods/blob/3995c659f25a0a640f6009ed7fcc2559ce659b1d/pods/datasets.py#L172-L185
train
sods/ods
pods/datasets.py
download_data
def download_data(dataset_name=None, prompt=prompt_stdin): """Check with the user that the are happy with terms and conditions for the data set, then download it.""" dr = data_resources[dataset_name] if not authorize_download(dataset_name, prompt=prompt): raise Exception("Permission to download data set denied.") if 'suffices' in dr: for url, files, suffices in zip(dr['urls'], dr['files'], dr['suffices']): for file, suffix in zip(files, suffices): download_url(url=os.path.join(url,file), dir_name = data_path, store_directory=dataset_name, suffix=suffix) elif 'dirs' in dr: for url, dirs, files in zip(dr['urls'], dr['dirs'], dr['files']): for file, dir in zip(files, dirs): print(file, dir) download_url( url=os.path.join(url,dir,file), dir_name = data_path, store_directory=os.path.join(dataset_name,dir) ) else: for url, files in zip(dr['urls'], dr['files']): for file in files: download_url( url=os.path.join(url,file), dir_name = data_path, store_directory=dataset_name ) return True
python
def download_data(dataset_name=None, prompt=prompt_stdin): """Check with the user that the are happy with terms and conditions for the data set, then download it.""" dr = data_resources[dataset_name] if not authorize_download(dataset_name, prompt=prompt): raise Exception("Permission to download data set denied.") if 'suffices' in dr: for url, files, suffices in zip(dr['urls'], dr['files'], dr['suffices']): for file, suffix in zip(files, suffices): download_url(url=os.path.join(url,file), dir_name = data_path, store_directory=dataset_name, suffix=suffix) elif 'dirs' in dr: for url, dirs, files in zip(dr['urls'], dr['dirs'], dr['files']): for file, dir in zip(files, dirs): print(file, dir) download_url( url=os.path.join(url,dir,file), dir_name = data_path, store_directory=os.path.join(dataset_name,dir) ) else: for url, files in zip(dr['urls'], dr['files']): for file in files: download_url( url=os.path.join(url,file), dir_name = data_path, store_directory=dataset_name ) return True
[ "def", "download_data", "(", "dataset_name", "=", "None", ",", "prompt", "=", "prompt_stdin", ")", ":", "dr", "=", "data_resources", "[", "dataset_name", "]", "if", "not", "authorize_download", "(", "dataset_name", ",", "prompt", "=", "prompt", ")", ":", "raise", "Exception", "(", "\"Permission to download data set denied.\"", ")", "if", "'suffices'", "in", "dr", ":", "for", "url", ",", "files", ",", "suffices", "in", "zip", "(", "dr", "[", "'urls'", "]", ",", "dr", "[", "'files'", "]", ",", "dr", "[", "'suffices'", "]", ")", ":", "for", "file", ",", "suffix", "in", "zip", "(", "files", ",", "suffices", ")", ":", "download_url", "(", "url", "=", "os", ".", "path", ".", "join", "(", "url", ",", "file", ")", ",", "dir_name", "=", "data_path", ",", "store_directory", "=", "dataset_name", ",", "suffix", "=", "suffix", ")", "elif", "'dirs'", "in", "dr", ":", "for", "url", ",", "dirs", ",", "files", "in", "zip", "(", "dr", "[", "'urls'", "]", ",", "dr", "[", "'dirs'", "]", ",", "dr", "[", "'files'", "]", ")", ":", "for", "file", ",", "dir", "in", "zip", "(", "files", ",", "dirs", ")", ":", "print", "(", "file", ",", "dir", ")", "download_url", "(", "url", "=", "os", ".", "path", ".", "join", "(", "url", ",", "dir", ",", "file", ")", ",", "dir_name", "=", "data_path", ",", "store_directory", "=", "os", ".", "path", ".", "join", "(", "dataset_name", ",", "dir", ")", ")", "else", ":", "for", "url", ",", "files", "in", "zip", "(", "dr", "[", "'urls'", "]", ",", "dr", "[", "'files'", "]", ")", ":", "for", "file", "in", "files", ":", "download_url", "(", "url", "=", "os", ".", "path", ".", "join", "(", "url", ",", "file", ")", ",", "dir_name", "=", "data_path", ",", "store_directory", "=", "dataset_name", ")", "return", "True" ]
Check with the user that the are happy with terms and conditions for the data set, then download it.
[ "Check", "with", "the", "user", "that", "the", "are", "happy", "with", "terms", "and", "conditions", "for", "the", "data", "set", "then", "download", "it", "." ]
3995c659f25a0a640f6009ed7fcc2559ce659b1d
https://github.com/sods/ods/blob/3995c659f25a0a640f6009ed7fcc2559ce659b1d/pods/datasets.py#L220-L251
train
sods/ods
pods/datasets.py
df2arff
def df2arff(df, dataset_name, pods_data): """Write an arff file from a data set loaded in from pods""" def java_simple_date(date_format): date_format = date_format.replace('%Y', 'yyyy').replace('%m', 'MM').replace('%d', 'dd').replace('%H', 'HH') return date_format.replace('%h', 'hh').replace('%M', 'mm').replace('%S', 'ss').replace('%f', 'SSSSSS') def tidy_field(atr): return str(atr).replace(' / ', '/').replace(' ', '_') types = {'STRING': [str], 'INTEGER': [int, np.int64, np.uint8], 'REAL': [np.float64]} d = {} d['attributes'] = [] for atr in df.columns: if isinstance(atr, str): if len(atr)>8 and atr[:9] == 'discrete(': import json elements = json.loads(atr[9:-1]) d['attributes'].append((tidy_field(elements[1]), list(elements[0].keys()))) mask = {} c = pd.Series(index=df.index) for key, val in elements[0].items(): mask = df[atr]==val c[mask] = key df[atr] = c continue if len(atr)>7 and atr[:8] == 'integer(': name = atr[8:-1] d['attributes'].append((tidy_field(name), 'INTEGER')) df[atr] = df[atr].astype(int) continue if len(atr)>7 and atr[:8]=='datenum(': from matplotlib.dates import num2date elements = atr[8:-1].split(',') d['attributes'].append((elements[0] + '_datenum_' + java_simple_date(elements[1]), 'STRING')) df[atr] = num2date(df[atr].values) # df[atr] = df[atr].dt.strftime(elements[1]) continue if len(atr)>9 and atr[:10]=='timestamp(': def timestamp2date(values): import datetime """Convert timestamp into a date object""" new = [] for value in values: new.append(np.datetime64(datetime.datetime.fromtimestamp(value))) return np.asarray(new) elements = atr[10:-1].split(',') d['attributes'].append((elements[0] + '_datenum_' + java_simple_date(elements[1]), 'STRING')) df[atr] = timestamp2date(df[atr].values) # df[atr] = df[atr].dt.strftime(elements[1]) continue if len(atr)>10 and atr[:11]=='datetime64(': elements = atr[11:-1].split(',') d['attributes'].append((elements[0] + '_datenum_' + java_simple_date(elements[1]), 'STRING')) df[atr] = df[atr].dt.strftime(elements[1]) continue if len(atr)>11 and atr[:12]=='decimalyear(': def decyear2date(values): """Convert decimal year into a date object""" new = [] for i, decyear in enumerate(values): year = int(np.floor(decyear)) dec = decyear-year end = np.datetime64(str(year+1)+'-01-01') start = np.datetime64(str(year)+'-01-01') diff=end-start days = dec*(diff/np.timedelta64(1, 'D')) # round to nearest day add = np.timedelta64(int(np.round(days)), 'D') new.append(start+add) return np.asarray(new) elements = atr[12:-1].split(',') d['attributes'].append((elements[0] + '_datenum_' + java_simple_date(elements[1]), 'STRING')) df[atr] = decyear2date(df[atr].values) # df[atr] = df[atr].dt.strftime(elements[1]) continue field = tidy_field(atr) el = df[atr][0] type_assigned=False for t in types: if isinstance(el, tuple(types[t])): d['attributes'].append((field, t)) type_assigned=True break if not type_assigned: import json d['attributes'].append((field+'_json', 'STRING')) df[atr] = df[atr].apply(json.dumps) d['data'] = [] for ind, row in df.iterrows(): d['data'].append(list(row)) import textwrap as tw width = 78 d['description'] = dataset_name + "\n\n" if 'info' in pods_data and pods_data['info']: d['description'] += "\n".join(tw.wrap(pods_data['info'], width)) + "\n\n" if 'details' in pods_data and pods_data['details']: d['description'] += "\n".join(tw.wrap(pods_data['details'], width)) if 'citation' in pods_data and pods_data['citation']: d['description'] += "\n\n" + "Citation" "\n\n" + "\n".join(tw.wrap(pods_data['citation'], width)) d['relation'] = dataset_name import arff string = arff.dumps(d) import re string = re.sub(r'\@ATTRIBUTE "?(.*)_datenum_(.*)"? STRING', r'@ATTRIBUTE "\1" DATE [\2]', string) f = open(dataset_name + '.arff', 'w') f.write(string) f.close()
python
def df2arff(df, dataset_name, pods_data): """Write an arff file from a data set loaded in from pods""" def java_simple_date(date_format): date_format = date_format.replace('%Y', 'yyyy').replace('%m', 'MM').replace('%d', 'dd').replace('%H', 'HH') return date_format.replace('%h', 'hh').replace('%M', 'mm').replace('%S', 'ss').replace('%f', 'SSSSSS') def tidy_field(atr): return str(atr).replace(' / ', '/').replace(' ', '_') types = {'STRING': [str], 'INTEGER': [int, np.int64, np.uint8], 'REAL': [np.float64]} d = {} d['attributes'] = [] for atr in df.columns: if isinstance(atr, str): if len(atr)>8 and atr[:9] == 'discrete(': import json elements = json.loads(atr[9:-1]) d['attributes'].append((tidy_field(elements[1]), list(elements[0].keys()))) mask = {} c = pd.Series(index=df.index) for key, val in elements[0].items(): mask = df[atr]==val c[mask] = key df[atr] = c continue if len(atr)>7 and atr[:8] == 'integer(': name = atr[8:-1] d['attributes'].append((tidy_field(name), 'INTEGER')) df[atr] = df[atr].astype(int) continue if len(atr)>7 and atr[:8]=='datenum(': from matplotlib.dates import num2date elements = atr[8:-1].split(',') d['attributes'].append((elements[0] + '_datenum_' + java_simple_date(elements[1]), 'STRING')) df[atr] = num2date(df[atr].values) # df[atr] = df[atr].dt.strftime(elements[1]) continue if len(atr)>9 and atr[:10]=='timestamp(': def timestamp2date(values): import datetime """Convert timestamp into a date object""" new = [] for value in values: new.append(np.datetime64(datetime.datetime.fromtimestamp(value))) return np.asarray(new) elements = atr[10:-1].split(',') d['attributes'].append((elements[0] + '_datenum_' + java_simple_date(elements[1]), 'STRING')) df[atr] = timestamp2date(df[atr].values) # df[atr] = df[atr].dt.strftime(elements[1]) continue if len(atr)>10 and atr[:11]=='datetime64(': elements = atr[11:-1].split(',') d['attributes'].append((elements[0] + '_datenum_' + java_simple_date(elements[1]), 'STRING')) df[atr] = df[atr].dt.strftime(elements[1]) continue if len(atr)>11 and atr[:12]=='decimalyear(': def decyear2date(values): """Convert decimal year into a date object""" new = [] for i, decyear in enumerate(values): year = int(np.floor(decyear)) dec = decyear-year end = np.datetime64(str(year+1)+'-01-01') start = np.datetime64(str(year)+'-01-01') diff=end-start days = dec*(diff/np.timedelta64(1, 'D')) # round to nearest day add = np.timedelta64(int(np.round(days)), 'D') new.append(start+add) return np.asarray(new) elements = atr[12:-1].split(',') d['attributes'].append((elements[0] + '_datenum_' + java_simple_date(elements[1]), 'STRING')) df[atr] = decyear2date(df[atr].values) # df[atr] = df[atr].dt.strftime(elements[1]) continue field = tidy_field(atr) el = df[atr][0] type_assigned=False for t in types: if isinstance(el, tuple(types[t])): d['attributes'].append((field, t)) type_assigned=True break if not type_assigned: import json d['attributes'].append((field+'_json', 'STRING')) df[atr] = df[atr].apply(json.dumps) d['data'] = [] for ind, row in df.iterrows(): d['data'].append(list(row)) import textwrap as tw width = 78 d['description'] = dataset_name + "\n\n" if 'info' in pods_data and pods_data['info']: d['description'] += "\n".join(tw.wrap(pods_data['info'], width)) + "\n\n" if 'details' in pods_data and pods_data['details']: d['description'] += "\n".join(tw.wrap(pods_data['details'], width)) if 'citation' in pods_data and pods_data['citation']: d['description'] += "\n\n" + "Citation" "\n\n" + "\n".join(tw.wrap(pods_data['citation'], width)) d['relation'] = dataset_name import arff string = arff.dumps(d) import re string = re.sub(r'\@ATTRIBUTE "?(.*)_datenum_(.*)"? STRING', r'@ATTRIBUTE "\1" DATE [\2]', string) f = open(dataset_name + '.arff', 'w') f.write(string) f.close()
[ "def", "df2arff", "(", "df", ",", "dataset_name", ",", "pods_data", ")", ":", "def", "java_simple_date", "(", "date_format", ")", ":", "date_format", "=", "date_format", ".", "replace", "(", "'%Y'", ",", "'yyyy'", ")", ".", "replace", "(", "'%m'", ",", "'MM'", ")", ".", "replace", "(", "'%d'", ",", "'dd'", ")", ".", "replace", "(", "'%H'", ",", "'HH'", ")", "return", "date_format", ".", "replace", "(", "'%h'", ",", "'hh'", ")", ".", "replace", "(", "'%M'", ",", "'mm'", ")", ".", "replace", "(", "'%S'", ",", "'ss'", ")", ".", "replace", "(", "'%f'", ",", "'SSSSSS'", ")", "def", "tidy_field", "(", "atr", ")", ":", "return", "str", "(", "atr", ")", ".", "replace", "(", "' / '", ",", "'/'", ")", ".", "replace", "(", "' '", ",", "'_'", ")", "types", "=", "{", "'STRING'", ":", "[", "str", "]", ",", "'INTEGER'", ":", "[", "int", ",", "np", ".", "int64", ",", "np", ".", "uint8", "]", ",", "'REAL'", ":", "[", "np", ".", "float64", "]", "}", "d", "=", "{", "}", "d", "[", "'attributes'", "]", "=", "[", "]", "for", "atr", "in", "df", ".", "columns", ":", "if", "isinstance", "(", "atr", ",", "str", ")", ":", "if", "len", "(", "atr", ")", ">", "8", "and", "atr", "[", ":", "9", "]", "==", "'discrete('", ":", "import", "json", "elements", "=", "json", ".", "loads", "(", "atr", "[", "9", ":", "-", "1", "]", ")", "d", "[", "'attributes'", "]", ".", "append", "(", "(", "tidy_field", "(", "elements", "[", "1", "]", ")", ",", "list", "(", "elements", "[", "0", "]", ".", "keys", "(", ")", ")", ")", ")", "mask", "=", "{", "}", "c", "=", "pd", ".", "Series", "(", "index", "=", "df", ".", "index", ")", "for", "key", ",", "val", "in", "elements", "[", "0", "]", ".", "items", "(", ")", ":", "mask", "=", "df", "[", "atr", "]", "==", "val", "c", "[", "mask", "]", "=", "key", "df", "[", "atr", "]", "=", "c", "continue", "if", "len", "(", "atr", ")", ">", "7", "and", "atr", "[", ":", "8", "]", "==", "'integer('", ":", "name", "=", "atr", "[", "8", ":", "-", "1", "]", "d", "[", "'attributes'", "]", ".", "append", "(", "(", "tidy_field", "(", "name", ")", ",", "'INTEGER'", ")", ")", "df", "[", "atr", "]", "=", "df", "[", "atr", "]", ".", "astype", "(", "int", ")", "continue", "if", "len", "(", "atr", ")", ">", "7", "and", "atr", "[", ":", "8", "]", "==", "'datenum('", ":", "from", "matplotlib", ".", "dates", "import", "num2date", "elements", "=", "atr", "[", "8", ":", "-", "1", "]", ".", "split", "(", "','", ")", "d", "[", "'attributes'", "]", ".", "append", "(", "(", "elements", "[", "0", "]", "+", "'_datenum_'", "+", "java_simple_date", "(", "elements", "[", "1", "]", ")", ",", "'STRING'", ")", ")", "df", "[", "atr", "]", "=", "num2date", "(", "df", "[", "atr", "]", ".", "values", ")", "#", "df", "[", "atr", "]", "=", "df", "[", "atr", "]", ".", "dt", ".", "strftime", "(", "elements", "[", "1", "]", ")", "continue", "if", "len", "(", "atr", ")", ">", "9", "and", "atr", "[", ":", "10", "]", "==", "'timestamp('", ":", "def", "timestamp2date", "(", "values", ")", ":", "import", "datetime", "\"\"\"Convert timestamp into a date object\"\"\"", "new", "=", "[", "]", "for", "value", "in", "values", ":", "new", ".", "append", "(", "np", ".", "datetime64", "(", "datetime", ".", "datetime", ".", "fromtimestamp", "(", "value", ")", ")", ")", "return", "np", ".", "asarray", "(", "new", ")", "elements", "=", "atr", "[", "10", ":", "-", "1", "]", ".", "split", "(", "','", ")", "d", "[", "'attributes'", "]", ".", "append", "(", "(", "elements", "[", "0", "]", "+", "'_datenum_'", "+", "java_simple_date", "(", "elements", "[", "1", "]", ")", ",", "'STRING'", ")", ")", "df", "[", "atr", "]", "=", "timestamp2date", "(", "df", "[", "atr", "]", ".", "values", ")", "#", "df", "[", "atr", "]", "=", "df", "[", "atr", "]", ".", "dt", ".", "strftime", "(", "elements", "[", "1", "]", ")", "continue", "if", "len", "(", "atr", ")", ">", "10", "and", "atr", "[", ":", "11", "]", "==", "'datetime64('", ":", "elements", "=", "atr", "[", "11", ":", "-", "1", "]", ".", "split", "(", "','", ")", "d", "[", "'attributes'", "]", ".", "append", "(", "(", "elements", "[", "0", "]", "+", "'_datenum_'", "+", "java_simple_date", "(", "elements", "[", "1", "]", ")", ",", "'STRING'", ")", ")", "df", "[", "atr", "]", "=", "df", "[", "atr", "]", ".", "dt", ".", "strftime", "(", "elements", "[", "1", "]", ")", "continue", "if", "len", "(", "atr", ")", ">", "11", "and", "atr", "[", ":", "12", "]", "==", "'decimalyear('", ":", "def", "decyear2date", "(", "values", ")", ":", "\"\"\"Convert decimal year into a date object\"\"\"", "new", "=", "[", "]", "for", "i", ",", "decyear", "in", "enumerate", "(", "values", ")", ":", "year", "=", "int", "(", "np", ".", "floor", "(", "decyear", ")", ")", "dec", "=", "decyear", "-", "year", "end", "=", "np", ".", "datetime64", "(", "str", "(", "year", "+", "1", ")", "+", "'-01-01'", ")", "start", "=", "np", ".", "datetime64", "(", "str", "(", "year", ")", "+", "'-01-01'", ")", "diff", "=", "end", "-", "start", "days", "=", "dec", "*", "(", "diff", "/", "np", ".", "timedelta64", "(", "1", ",", "'D'", ")", ")", "# round to nearest day", "add", "=", "np", ".", "timedelta64", "(", "int", "(", "np", ".", "round", "(", "days", ")", ")", ",", "'D'", ")", "new", ".", "append", "(", "start", "+", "add", ")", "return", "np", ".", "asarray", "(", "new", ")", "elements", "=", "atr", "[", "12", ":", "-", "1", "]", ".", "split", "(", "','", ")", "d", "[", "'attributes'", "]", ".", "append", "(", "(", "elements", "[", "0", "]", "+", "'_datenum_'", "+", "java_simple_date", "(", "elements", "[", "1", "]", ")", ",", "'STRING'", ")", ")", "df", "[", "atr", "]", "=", "decyear2date", "(", "df", "[", "atr", "]", ".", "values", ")", "#", "df", "[", "atr", "]", "=", "df", "[", "atr", "]", ".", "dt", ".", "strftime", "(", "elements", "[", "1", "]", ")", "continue", "field", "=", "tidy_field", "(", "atr", ")", "el", "=", "df", "[", "atr", "]", "[", "0", "]", "type_assigned", "=", "False", "for", "t", "in", "types", ":", "if", "isinstance", "(", "el", ",", "tuple", "(", "types", "[", "t", "]", ")", ")", ":", "d", "[", "'attributes'", "]", ".", "append", "(", "(", "field", ",", "t", ")", ")", "type_assigned", "=", "True", "break", "if", "not", "type_assigned", ":", "import", "json", "d", "[", "'attributes'", "]", ".", "append", "(", "(", "field", "+", "'_json'", ",", "'STRING'", ")", ")", "df", "[", "atr", "]", "=", "df", "[", "atr", "]", ".", "apply", "(", "json", ".", "dumps", ")", "d", "[", "'data'", "]", "=", "[", "]", "for", "ind", ",", "row", "in", "df", ".", "iterrows", "(", ")", ":", "d", "[", "'data'", "]", ".", "append", "(", "list", "(", "row", ")", ")", "import", "textwrap", "as", "tw", "width", "=", "78", "d", "[", "'description'", "]", "=", "dataset_name", "+", "\"\\n\\n\"", "if", "'info'", "in", "pods_data", "and", "pods_data", "[", "'info'", "]", ":", "d", "[", "'description'", "]", "+=", "\"\\n\"", ".", "join", "(", "tw", ".", "wrap", "(", "pods_data", "[", "'info'", "]", ",", "width", ")", ")", "+", "\"\\n\\n\"", "if", "'details'", "in", "pods_data", "and", "pods_data", "[", "'details'", "]", ":", "d", "[", "'description'", "]", "+=", "\"\\n\"", ".", "join", "(", "tw", ".", "wrap", "(", "pods_data", "[", "'details'", "]", ",", "width", ")", ")", "if", "'citation'", "in", "pods_data", "and", "pods_data", "[", "'citation'", "]", ":", "d", "[", "'description'", "]", "+=", "\"\\n\\n\"", "+", "\"Citation\"", "\"\\n\\n\"", "+", "\"\\n\"", ".", "join", "(", "tw", ".", "wrap", "(", "pods_data", "[", "'citation'", "]", ",", "width", ")", ")", "d", "[", "'relation'", "]", "=", "dataset_name", "import", "arff", "string", "=", "arff", ".", "dumps", "(", "d", ")", "import", "re", "string", "=", "re", ".", "sub", "(", "r'\\@ATTRIBUTE \"?(.*)_datenum_(.*)\"? STRING'", ",", "r'@ATTRIBUTE \"\\1\" DATE [\\2]'", ",", "string", ")", "f", "=", "open", "(", "dataset_name", "+", "'.arff'", ",", "'w'", ")", "f", ".", "write", "(", "string", ")", "f", ".", "close", "(", ")" ]
Write an arff file from a data set loaded in from pods
[ "Write", "an", "arff", "file", "from", "a", "data", "set", "loaded", "in", "from", "pods" ]
3995c659f25a0a640f6009ed7fcc2559ce659b1d
https://github.com/sods/ods/blob/3995c659f25a0a640f6009ed7fcc2559ce659b1d/pods/datasets.py#L259-L371
train
sods/ods
pods/datasets.py
to_arff
def to_arff(dataset, **kwargs): """Take a pods data set and write it as an ARFF file""" pods_data = dataset(**kwargs) vals = list(kwargs.values()) for i, v in enumerate(vals): if isinstance(v, list): vals[i] = '|'.join(v) else: vals[i] = str(v) args = '_'.join(vals) n = dataset.__name__ if len(args)>0: n += '_' + args n = n.replace(' ', '-') ks = pods_data.keys() d = None if 'Y' in ks and 'X' in ks: d = pd.DataFrame(pods_data['X']) if 'Xtest' in ks: d = d.append(pd.DataFrame(pods_data['Xtest']), ignore_index=True) if 'covariates' in ks: d.columns = pods_data['covariates'] dy = pd.DataFrame(pods_data['Y']) if 'Ytest' in ks: dy = dy.append(pd.DataFrame(pods_data['Ytest']), ignore_index=True) if 'response' in ks: dy.columns = pods_data['response'] for c in dy.columns: if c not in d.columns: d[c] = dy[c] else: d['y'+str(c)] = dy[c] elif 'Y' in ks: d = pd.DataFrame(pods_data['Y']) if 'Ytest' in ks: d = d.append(pd.DataFrame(pods_data['Ytest']), ignore_index=True) elif 'data' in ks: d = pd.DataFrame(pods_data['data']) if d is not None: df2arff(d, n, pods_data)
python
def to_arff(dataset, **kwargs): """Take a pods data set and write it as an ARFF file""" pods_data = dataset(**kwargs) vals = list(kwargs.values()) for i, v in enumerate(vals): if isinstance(v, list): vals[i] = '|'.join(v) else: vals[i] = str(v) args = '_'.join(vals) n = dataset.__name__ if len(args)>0: n += '_' + args n = n.replace(' ', '-') ks = pods_data.keys() d = None if 'Y' in ks and 'X' in ks: d = pd.DataFrame(pods_data['X']) if 'Xtest' in ks: d = d.append(pd.DataFrame(pods_data['Xtest']), ignore_index=True) if 'covariates' in ks: d.columns = pods_data['covariates'] dy = pd.DataFrame(pods_data['Y']) if 'Ytest' in ks: dy = dy.append(pd.DataFrame(pods_data['Ytest']), ignore_index=True) if 'response' in ks: dy.columns = pods_data['response'] for c in dy.columns: if c not in d.columns: d[c] = dy[c] else: d['y'+str(c)] = dy[c] elif 'Y' in ks: d = pd.DataFrame(pods_data['Y']) if 'Ytest' in ks: d = d.append(pd.DataFrame(pods_data['Ytest']), ignore_index=True) elif 'data' in ks: d = pd.DataFrame(pods_data['data']) if d is not None: df2arff(d, n, pods_data)
[ "def", "to_arff", "(", "dataset", ",", "*", "*", "kwargs", ")", ":", "pods_data", "=", "dataset", "(", "*", "*", "kwargs", ")", "vals", "=", "list", "(", "kwargs", ".", "values", "(", ")", ")", "for", "i", ",", "v", "in", "enumerate", "(", "vals", ")", ":", "if", "isinstance", "(", "v", ",", "list", ")", ":", "vals", "[", "i", "]", "=", "'|'", ".", "join", "(", "v", ")", "else", ":", "vals", "[", "i", "]", "=", "str", "(", "v", ")", "args", "=", "'_'", ".", "join", "(", "vals", ")", "n", "=", "dataset", ".", "__name__", "if", "len", "(", "args", ")", ">", "0", ":", "n", "+=", "'_'", "+", "args", "n", "=", "n", ".", "replace", "(", "' '", ",", "'-'", ")", "ks", "=", "pods_data", ".", "keys", "(", ")", "d", "=", "None", "if", "'Y'", "in", "ks", "and", "'X'", "in", "ks", ":", "d", "=", "pd", ".", "DataFrame", "(", "pods_data", "[", "'X'", "]", ")", "if", "'Xtest'", "in", "ks", ":", "d", "=", "d", ".", "append", "(", "pd", ".", "DataFrame", "(", "pods_data", "[", "'Xtest'", "]", ")", ",", "ignore_index", "=", "True", ")", "if", "'covariates'", "in", "ks", ":", "d", ".", "columns", "=", "pods_data", "[", "'covariates'", "]", "dy", "=", "pd", ".", "DataFrame", "(", "pods_data", "[", "'Y'", "]", ")", "if", "'Ytest'", "in", "ks", ":", "dy", "=", "dy", ".", "append", "(", "pd", ".", "DataFrame", "(", "pods_data", "[", "'Ytest'", "]", ")", ",", "ignore_index", "=", "True", ")", "if", "'response'", "in", "ks", ":", "dy", ".", "columns", "=", "pods_data", "[", "'response'", "]", "for", "c", "in", "dy", ".", "columns", ":", "if", "c", "not", "in", "d", ".", "columns", ":", "d", "[", "c", "]", "=", "dy", "[", "c", "]", "else", ":", "d", "[", "'y'", "+", "str", "(", "c", ")", "]", "=", "dy", "[", "c", "]", "elif", "'Y'", "in", "ks", ":", "d", "=", "pd", ".", "DataFrame", "(", "pods_data", "[", "'Y'", "]", ")", "if", "'Ytest'", "in", "ks", ":", "d", "=", "d", ".", "append", "(", "pd", ".", "DataFrame", "(", "pods_data", "[", "'Ytest'", "]", ")", ",", "ignore_index", "=", "True", ")", "elif", "'data'", "in", "ks", ":", "d", "=", "pd", ".", "DataFrame", "(", "pods_data", "[", "'data'", "]", ")", "if", "d", "is", "not", "None", ":", "df2arff", "(", "d", ",", "n", ",", "pods_data", ")" ]
Take a pods data set and write it as an ARFF file
[ "Take", "a", "pods", "data", "set", "and", "write", "it", "as", "an", "ARFF", "file" ]
3995c659f25a0a640f6009ed7fcc2559ce659b1d
https://github.com/sods/ods/blob/3995c659f25a0a640f6009ed7fcc2559ce659b1d/pods/datasets.py#L373-L413
train
sods/ods
pods/datasets.py
epomeo_gpx
def epomeo_gpx(data_set='epomeo_gpx', sample_every=4): """Data set of three GPS traces of the same movement on Mt Epomeo in Ischia. Requires gpxpy to run.""" import gpxpy import gpxpy.gpx if not data_available(data_set): download_data(data_set) files = ['endomondo_1', 'endomondo_2', 'garmin_watch_via_endomondo','viewranger_phone', 'viewranger_tablet'] X = [] for file in files: gpx_file = open(os.path.join(data_path, 'epomeo_gpx', file + '.gpx'), 'r') gpx = gpxpy.parse(gpx_file) segment = gpx.tracks[0].segments[0] points = [point for track in gpx.tracks for segment in track.segments for point in segment.points] data = [[(point.time-datetime.datetime(2013,8,21)).total_seconds(), point.latitude, point.longitude, point.elevation] for point in points] X.append(np.asarray(data)[::sample_every, :]) gpx_file.close() if pandas_available: X = pd.DataFrame(X[0], columns=['seconds', 'latitude', 'longitude', 'elevation']) X.set_index(keys='seconds', inplace=True) return data_details_return({'X' : X, 'info' : 'Data is an array containing time in seconds, latitude, longitude and elevation in that order.'}, data_set)
python
def epomeo_gpx(data_set='epomeo_gpx', sample_every=4): """Data set of three GPS traces of the same movement on Mt Epomeo in Ischia. Requires gpxpy to run.""" import gpxpy import gpxpy.gpx if not data_available(data_set): download_data(data_set) files = ['endomondo_1', 'endomondo_2', 'garmin_watch_via_endomondo','viewranger_phone', 'viewranger_tablet'] X = [] for file in files: gpx_file = open(os.path.join(data_path, 'epomeo_gpx', file + '.gpx'), 'r') gpx = gpxpy.parse(gpx_file) segment = gpx.tracks[0].segments[0] points = [point for track in gpx.tracks for segment in track.segments for point in segment.points] data = [[(point.time-datetime.datetime(2013,8,21)).total_seconds(), point.latitude, point.longitude, point.elevation] for point in points] X.append(np.asarray(data)[::sample_every, :]) gpx_file.close() if pandas_available: X = pd.DataFrame(X[0], columns=['seconds', 'latitude', 'longitude', 'elevation']) X.set_index(keys='seconds', inplace=True) return data_details_return({'X' : X, 'info' : 'Data is an array containing time in seconds, latitude, longitude and elevation in that order.'}, data_set)
[ "def", "epomeo_gpx", "(", "data_set", "=", "'epomeo_gpx'", ",", "sample_every", "=", "4", ")", ":", "import", "gpxpy", "import", "gpxpy", ".", "gpx", "if", "not", "data_available", "(", "data_set", ")", ":", "download_data", "(", "data_set", ")", "files", "=", "[", "'endomondo_1'", ",", "'endomondo_2'", ",", "'garmin_watch_via_endomondo'", ",", "'viewranger_phone'", ",", "'viewranger_tablet'", "]", "X", "=", "[", "]", "for", "file", "in", "files", ":", "gpx_file", "=", "open", "(", "os", ".", "path", ".", "join", "(", "data_path", ",", "'epomeo_gpx'", ",", "file", "+", "'.gpx'", ")", ",", "'r'", ")", "gpx", "=", "gpxpy", ".", "parse", "(", "gpx_file", ")", "segment", "=", "gpx", ".", "tracks", "[", "0", "]", ".", "segments", "[", "0", "]", "points", "=", "[", "point", "for", "track", "in", "gpx", ".", "tracks", "for", "segment", "in", "track", ".", "segments", "for", "point", "in", "segment", ".", "points", "]", "data", "=", "[", "[", "(", "point", ".", "time", "-", "datetime", ".", "datetime", "(", "2013", ",", "8", ",", "21", ")", ")", ".", "total_seconds", "(", ")", ",", "point", ".", "latitude", ",", "point", ".", "longitude", ",", "point", ".", "elevation", "]", "for", "point", "in", "points", "]", "X", ".", "append", "(", "np", ".", "asarray", "(", "data", ")", "[", ":", ":", "sample_every", ",", ":", "]", ")", "gpx_file", ".", "close", "(", ")", "if", "pandas_available", ":", "X", "=", "pd", ".", "DataFrame", "(", "X", "[", "0", "]", ",", "columns", "=", "[", "'seconds'", ",", "'latitude'", ",", "'longitude'", ",", "'elevation'", "]", ")", "X", ".", "set_index", "(", "keys", "=", "'seconds'", ",", "inplace", "=", "True", ")", "return", "data_details_return", "(", "{", "'X'", ":", "X", ",", "'info'", ":", "'Data is an array containing time in seconds, latitude, longitude and elevation in that order.'", "}", ",", "data_set", ")" ]
Data set of three GPS traces of the same movement on Mt Epomeo in Ischia. Requires gpxpy to run.
[ "Data", "set", "of", "three", "GPS", "traces", "of", "the", "same", "movement", "on", "Mt", "Epomeo", "in", "Ischia", ".", "Requires", "gpxpy", "to", "run", "." ]
3995c659f25a0a640f6009ed7fcc2559ce659b1d
https://github.com/sods/ods/blob/3995c659f25a0a640f6009ed7fcc2559ce659b1d/pods/datasets.py#L519-L540
train
sods/ods
pods/datasets.py
pmlr
def pmlr(volumes='all', data_set='pmlr'): """Abstracts from the Proceedings of Machine Learning Research""" if not data_available(data_set): download_data(data_set) proceedings_file = open(os.path.join(data_path, data_set, 'proceedings.yaml'), 'r') import yaml proceedings = yaml.load(proceedings_file) # Create a new resources entry for downloading contents of proceedings. data_name_full = 'pmlr_volumes' data_resources[data_name_full] = data_resources[data_set].copy() data_resources[data_name_full]['files'] = [] data_resources[data_name_full]['dirs'] = [] data_resources[data_name_full]['urls'] = [] for entry in proceedings: if volumes=='all' or entry['volume'] in volumes: file = entry['yaml'].split('/')[-1] dir = 'v' + str(entry['volume']) data_resources[data_name_full]['files'].append([file]) data_resources[data_name_full]['dirs'].append([dir]) data_resources[data_name_full]['urls'].append(data_resources[data_set]['urls'][0]) Y = [] # Download the volume data if not data_available(data_name_full): download_data(data_name_full) for entry in reversed(proceedings): volume = entry['volume'] if volumes == 'all' or volume in volumes: file = entry['yaml'].split('/')[-1] volume_file = open(os.path.join( data_path, data_name_full, 'v'+str(volume), file ), 'r') Y+=yaml.load(volume_file) if pandas_available: Y = pd.DataFrame(Y) Y['published'] = pd.to_datetime(Y['published']) #Y.columns.values[4] = json_object('authors') #Y.columns.values[7] = json_object('editors') Y['issued'] = Y['issued'].apply(lambda x: np.datetime64(datetime.datetime(*x['date-parts']))) Y['author'] = Y['author'].apply(lambda x: [str(author['given']) + ' ' + str(author['family']) for author in x]) Y['editor'] = Y['editor'].apply(lambda x: [str(editor['given']) + ' ' + str(editor['family']) for editor in x]) columns = list(Y.columns) columns[14] = datetime64_('published') columns[11] = datetime64_('issued') Y.columns = columns return data_details_return({'Y' : Y, 'info' : 'Data is a pandas data frame containing each paper, its abstract, authors, volumes and venue.'}, data_set)
python
def pmlr(volumes='all', data_set='pmlr'): """Abstracts from the Proceedings of Machine Learning Research""" if not data_available(data_set): download_data(data_set) proceedings_file = open(os.path.join(data_path, data_set, 'proceedings.yaml'), 'r') import yaml proceedings = yaml.load(proceedings_file) # Create a new resources entry for downloading contents of proceedings. data_name_full = 'pmlr_volumes' data_resources[data_name_full] = data_resources[data_set].copy() data_resources[data_name_full]['files'] = [] data_resources[data_name_full]['dirs'] = [] data_resources[data_name_full]['urls'] = [] for entry in proceedings: if volumes=='all' or entry['volume'] in volumes: file = entry['yaml'].split('/')[-1] dir = 'v' + str(entry['volume']) data_resources[data_name_full]['files'].append([file]) data_resources[data_name_full]['dirs'].append([dir]) data_resources[data_name_full]['urls'].append(data_resources[data_set]['urls'][0]) Y = [] # Download the volume data if not data_available(data_name_full): download_data(data_name_full) for entry in reversed(proceedings): volume = entry['volume'] if volumes == 'all' or volume in volumes: file = entry['yaml'].split('/')[-1] volume_file = open(os.path.join( data_path, data_name_full, 'v'+str(volume), file ), 'r') Y+=yaml.load(volume_file) if pandas_available: Y = pd.DataFrame(Y) Y['published'] = pd.to_datetime(Y['published']) #Y.columns.values[4] = json_object('authors') #Y.columns.values[7] = json_object('editors') Y['issued'] = Y['issued'].apply(lambda x: np.datetime64(datetime.datetime(*x['date-parts']))) Y['author'] = Y['author'].apply(lambda x: [str(author['given']) + ' ' + str(author['family']) for author in x]) Y['editor'] = Y['editor'].apply(lambda x: [str(editor['given']) + ' ' + str(editor['family']) for editor in x]) columns = list(Y.columns) columns[14] = datetime64_('published') columns[11] = datetime64_('issued') Y.columns = columns return data_details_return({'Y' : Y, 'info' : 'Data is a pandas data frame containing each paper, its abstract, authors, volumes and venue.'}, data_set)
[ "def", "pmlr", "(", "volumes", "=", "'all'", ",", "data_set", "=", "'pmlr'", ")", ":", "if", "not", "data_available", "(", "data_set", ")", ":", "download_data", "(", "data_set", ")", "proceedings_file", "=", "open", "(", "os", ".", "path", ".", "join", "(", "data_path", ",", "data_set", ",", "'proceedings.yaml'", ")", ",", "'r'", ")", "import", "yaml", "proceedings", "=", "yaml", ".", "load", "(", "proceedings_file", ")", "# Create a new resources entry for downloading contents of proceedings.", "data_name_full", "=", "'pmlr_volumes'", "data_resources", "[", "data_name_full", "]", "=", "data_resources", "[", "data_set", "]", ".", "copy", "(", ")", "data_resources", "[", "data_name_full", "]", "[", "'files'", "]", "=", "[", "]", "data_resources", "[", "data_name_full", "]", "[", "'dirs'", "]", "=", "[", "]", "data_resources", "[", "data_name_full", "]", "[", "'urls'", "]", "=", "[", "]", "for", "entry", "in", "proceedings", ":", "if", "volumes", "==", "'all'", "or", "entry", "[", "'volume'", "]", "in", "volumes", ":", "file", "=", "entry", "[", "'yaml'", "]", ".", "split", "(", "'/'", ")", "[", "-", "1", "]", "dir", "=", "'v'", "+", "str", "(", "entry", "[", "'volume'", "]", ")", "data_resources", "[", "data_name_full", "]", "[", "'files'", "]", ".", "append", "(", "[", "file", "]", ")", "data_resources", "[", "data_name_full", "]", "[", "'dirs'", "]", ".", "append", "(", "[", "dir", "]", ")", "data_resources", "[", "data_name_full", "]", "[", "'urls'", "]", ".", "append", "(", "data_resources", "[", "data_set", "]", "[", "'urls'", "]", "[", "0", "]", ")", "Y", "=", "[", "]", "# Download the volume data", "if", "not", "data_available", "(", "data_name_full", ")", ":", "download_data", "(", "data_name_full", ")", "for", "entry", "in", "reversed", "(", "proceedings", ")", ":", "volume", "=", "entry", "[", "'volume'", "]", "if", "volumes", "==", "'all'", "or", "volume", "in", "volumes", ":", "file", "=", "entry", "[", "'yaml'", "]", ".", "split", "(", "'/'", ")", "[", "-", "1", "]", "volume_file", "=", "open", "(", "os", ".", "path", ".", "join", "(", "data_path", ",", "data_name_full", ",", "'v'", "+", "str", "(", "volume", ")", ",", "file", ")", ",", "'r'", ")", "Y", "+=", "yaml", ".", "load", "(", "volume_file", ")", "if", "pandas_available", ":", "Y", "=", "pd", ".", "DataFrame", "(", "Y", ")", "Y", "[", "'published'", "]", "=", "pd", ".", "to_datetime", "(", "Y", "[", "'published'", "]", ")", "#Y.columns.values[4] = json_object('authors')", "#Y.columns.values[7] = json_object('editors')", "Y", "[", "'issued'", "]", "=", "Y", "[", "'issued'", "]", ".", "apply", "(", "lambda", "x", ":", "np", ".", "datetime64", "(", "datetime", ".", "datetime", "(", "*", "x", "[", "'date-parts'", "]", ")", ")", ")", "Y", "[", "'author'", "]", "=", "Y", "[", "'author'", "]", ".", "apply", "(", "lambda", "x", ":", "[", "str", "(", "author", "[", "'given'", "]", ")", "+", "' '", "+", "str", "(", "author", "[", "'family'", "]", ")", "for", "author", "in", "x", "]", ")", "Y", "[", "'editor'", "]", "=", "Y", "[", "'editor'", "]", ".", "apply", "(", "lambda", "x", ":", "[", "str", "(", "editor", "[", "'given'", "]", ")", "+", "' '", "+", "str", "(", "editor", "[", "'family'", "]", ")", "for", "editor", "in", "x", "]", ")", "columns", "=", "list", "(", "Y", ".", "columns", ")", "columns", "[", "14", "]", "=", "datetime64_", "(", "'published'", ")", "columns", "[", "11", "]", "=", "datetime64_", "(", "'issued'", ")", "Y", ".", "columns", "=", "columns", "return", "data_details_return", "(", "{", "'Y'", ":", "Y", ",", "'info'", ":", "'Data is a pandas data frame containing each paper, its abstract, authors, volumes and venue.'", "}", ",", "data_set", ")" ]
Abstracts from the Proceedings of Machine Learning Research
[ "Abstracts", "from", "the", "Proceedings", "of", "Machine", "Learning", "Research" ]
3995c659f25a0a640f6009ed7fcc2559ce659b1d
https://github.com/sods/ods/blob/3995c659f25a0a640f6009ed7fcc2559ce659b1d/pods/datasets.py#L542-L590
train
sods/ods
pods/datasets.py
football_data
def football_data(season='1617', data_set='football_data'): """Football data from English games since 1993. This downloads data from football-data.co.uk for the given season. """ league_dict = {'E0':0, 'E1':1, 'E2': 2, 'E3': 3, 'EC':4} def league2num(string): if isinstance(string, bytes): string = string.decode('utf-8') return league_dict[string] def football2num(string): if isinstance(string, bytes): string = string.decode('utf-8') if string in football_dict: return football_dict[string] else: football_dict[string] = len(football_dict)+1 return len(football_dict)+1 def datestr2num(s): import datetime from matplotlib.dates import date2num return date2num(datetime.datetime.strptime(s.decode('utf-8'),'%d/%m/%y')) data_set_season = data_set + '_' + season data_resources[data_set_season] = copy.deepcopy(data_resources[data_set]) data_resources[data_set_season]['urls'][0]+=season + '/' start_year = int(season[0:2]) end_year = int(season[2:4]) files = ['E0.csv', 'E1.csv', 'E2.csv', 'E3.csv'] if start_year>4 and start_year < 93: files += ['EC.csv'] data_resources[data_set_season]['files'] = [files] if not data_available(data_set_season): download_data(data_set_season) start = True for file in reversed(files): filename = os.path.join(data_path, data_set_season, file) # rewrite files removing blank rows. writename = os.path.join(data_path, data_set_season, 'temp.csv') input = open(filename, encoding='ISO-8859-1') output = open(writename, 'w') writer = csv.writer(output) for row in csv.reader(input): if any(field.strip() for field in row): writer.writerow(row) input.close() output.close() table = np.loadtxt(writename,skiprows=1, usecols=(0, 1, 2, 3, 4, 5), converters = {0: league2num, 1: datestr2num, 2:football2num, 3:football2num}, delimiter=',') if start: X = table[:, :4] Y = table[:, 4:] start=False else: X = np.append(X, table[:, :4], axis=0) Y = np.append(Y, table[:, 4:], axis=0) return data_details_return({'X': X, 'Y': Y, 'covariates': [discrete(league_dict, 'league'), datenum('match_day'), discrete(football_dict, 'home team'), discrete(football_dict, 'away team')], 'response': [integer('home score'), integer('away score')]}, data_set)
python
def football_data(season='1617', data_set='football_data'): """Football data from English games since 1993. This downloads data from football-data.co.uk for the given season. """ league_dict = {'E0':0, 'E1':1, 'E2': 2, 'E3': 3, 'EC':4} def league2num(string): if isinstance(string, bytes): string = string.decode('utf-8') return league_dict[string] def football2num(string): if isinstance(string, bytes): string = string.decode('utf-8') if string in football_dict: return football_dict[string] else: football_dict[string] = len(football_dict)+1 return len(football_dict)+1 def datestr2num(s): import datetime from matplotlib.dates import date2num return date2num(datetime.datetime.strptime(s.decode('utf-8'),'%d/%m/%y')) data_set_season = data_set + '_' + season data_resources[data_set_season] = copy.deepcopy(data_resources[data_set]) data_resources[data_set_season]['urls'][0]+=season + '/' start_year = int(season[0:2]) end_year = int(season[2:4]) files = ['E0.csv', 'E1.csv', 'E2.csv', 'E3.csv'] if start_year>4 and start_year < 93: files += ['EC.csv'] data_resources[data_set_season]['files'] = [files] if not data_available(data_set_season): download_data(data_set_season) start = True for file in reversed(files): filename = os.path.join(data_path, data_set_season, file) # rewrite files removing blank rows. writename = os.path.join(data_path, data_set_season, 'temp.csv') input = open(filename, encoding='ISO-8859-1') output = open(writename, 'w') writer = csv.writer(output) for row in csv.reader(input): if any(field.strip() for field in row): writer.writerow(row) input.close() output.close() table = np.loadtxt(writename,skiprows=1, usecols=(0, 1, 2, 3, 4, 5), converters = {0: league2num, 1: datestr2num, 2:football2num, 3:football2num}, delimiter=',') if start: X = table[:, :4] Y = table[:, 4:] start=False else: X = np.append(X, table[:, :4], axis=0) Y = np.append(Y, table[:, 4:], axis=0) return data_details_return({'X': X, 'Y': Y, 'covariates': [discrete(league_dict, 'league'), datenum('match_day'), discrete(football_dict, 'home team'), discrete(football_dict, 'away team')], 'response': [integer('home score'), integer('away score')]}, data_set)
[ "def", "football_data", "(", "season", "=", "'1617'", ",", "data_set", "=", "'football_data'", ")", ":", "league_dict", "=", "{", "'E0'", ":", "0", ",", "'E1'", ":", "1", ",", "'E2'", ":", "2", ",", "'E3'", ":", "3", ",", "'EC'", ":", "4", "}", "def", "league2num", "(", "string", ")", ":", "if", "isinstance", "(", "string", ",", "bytes", ")", ":", "string", "=", "string", ".", "decode", "(", "'utf-8'", ")", "return", "league_dict", "[", "string", "]", "def", "football2num", "(", "string", ")", ":", "if", "isinstance", "(", "string", ",", "bytes", ")", ":", "string", "=", "string", ".", "decode", "(", "'utf-8'", ")", "if", "string", "in", "football_dict", ":", "return", "football_dict", "[", "string", "]", "else", ":", "football_dict", "[", "string", "]", "=", "len", "(", "football_dict", ")", "+", "1", "return", "len", "(", "football_dict", ")", "+", "1", "def", "datestr2num", "(", "s", ")", ":", "import", "datetime", "from", "matplotlib", ".", "dates", "import", "date2num", "return", "date2num", "(", "datetime", ".", "datetime", ".", "strptime", "(", "s", ".", "decode", "(", "'utf-8'", ")", ",", "'%d/%m/%y'", ")", ")", "data_set_season", "=", "data_set", "+", "'_'", "+", "season", "data_resources", "[", "data_set_season", "]", "=", "copy", ".", "deepcopy", "(", "data_resources", "[", "data_set", "]", ")", "data_resources", "[", "data_set_season", "]", "[", "'urls'", "]", "[", "0", "]", "+=", "season", "+", "'/'", "start_year", "=", "int", "(", "season", "[", "0", ":", "2", "]", ")", "end_year", "=", "int", "(", "season", "[", "2", ":", "4", "]", ")", "files", "=", "[", "'E0.csv'", ",", "'E1.csv'", ",", "'E2.csv'", ",", "'E3.csv'", "]", "if", "start_year", ">", "4", "and", "start_year", "<", "93", ":", "files", "+=", "[", "'EC.csv'", "]", "data_resources", "[", "data_set_season", "]", "[", "'files'", "]", "=", "[", "files", "]", "if", "not", "data_available", "(", "data_set_season", ")", ":", "download_data", "(", "data_set_season", ")", "start", "=", "True", "for", "file", "in", "reversed", "(", "files", ")", ":", "filename", "=", "os", ".", "path", ".", "join", "(", "data_path", ",", "data_set_season", ",", "file", ")", "# rewrite files removing blank rows.", "writename", "=", "os", ".", "path", ".", "join", "(", "data_path", ",", "data_set_season", ",", "'temp.csv'", ")", "input", "=", "open", "(", "filename", ",", "encoding", "=", "'ISO-8859-1'", ")", "output", "=", "open", "(", "writename", ",", "'w'", ")", "writer", "=", "csv", ".", "writer", "(", "output", ")", "for", "row", "in", "csv", ".", "reader", "(", "input", ")", ":", "if", "any", "(", "field", ".", "strip", "(", ")", "for", "field", "in", "row", ")", ":", "writer", ".", "writerow", "(", "row", ")", "input", ".", "close", "(", ")", "output", ".", "close", "(", ")", "table", "=", "np", ".", "loadtxt", "(", "writename", ",", "skiprows", "=", "1", ",", "usecols", "=", "(", "0", ",", "1", ",", "2", ",", "3", ",", "4", ",", "5", ")", ",", "converters", "=", "{", "0", ":", "league2num", ",", "1", ":", "datestr2num", ",", "2", ":", "football2num", ",", "3", ":", "football2num", "}", ",", "delimiter", "=", "','", ")", "if", "start", ":", "X", "=", "table", "[", ":", ",", ":", "4", "]", "Y", "=", "table", "[", ":", ",", "4", ":", "]", "start", "=", "False", "else", ":", "X", "=", "np", ".", "append", "(", "X", ",", "table", "[", ":", ",", ":", "4", "]", ",", "axis", "=", "0", ")", "Y", "=", "np", ".", "append", "(", "Y", ",", "table", "[", ":", ",", "4", ":", "]", ",", "axis", "=", "0", ")", "return", "data_details_return", "(", "{", "'X'", ":", "X", ",", "'Y'", ":", "Y", ",", "'covariates'", ":", "[", "discrete", "(", "league_dict", ",", "'league'", ")", ",", "datenum", "(", "'match_day'", ")", ",", "discrete", "(", "football_dict", ",", "'home team'", ")", ",", "discrete", "(", "football_dict", ",", "'away team'", ")", "]", ",", "'response'", ":", "[", "integer", "(", "'home score'", ")", ",", "integer", "(", "'away score'", ")", "]", "}", ",", "data_set", ")" ]
Football data from English games since 1993. This downloads data from football-data.co.uk for the given season.
[ "Football", "data", "from", "English", "games", "since", "1993", ".", "This", "downloads", "data", "from", "football", "-", "data", ".", "co", ".", "uk", "for", "the", "given", "season", "." ]
3995c659f25a0a640f6009ed7fcc2559ce659b1d
https://github.com/sods/ods/blob/3995c659f25a0a640f6009ed7fcc2559ce659b1d/pods/datasets.py#L593-L646
train
sods/ods
pods/datasets.py
lee_yeast_ChIP
def lee_yeast_ChIP(data_set='lee_yeast_ChIP'): """Yeast ChIP data from Lee et al.""" if not data_available(data_set): download_data(data_set) from pandas import read_csv dir_path = os.path.join(data_path, data_set) filename = os.path.join(dir_path, 'binding_by_gene.tsv') S = read_csv(filename, header=1, index_col=0, sep='\t') transcription_factors = [col for col in S.columns if col[:7] != 'Unnamed'] annotations = S[['Unnamed: 1', 'Unnamed: 2', 'Unnamed: 3']] S = S[transcription_factors] return data_details_return({'annotations' : annotations, 'Y' : S, 'transcription_factors': transcription_factors}, data_set)
python
def lee_yeast_ChIP(data_set='lee_yeast_ChIP'): """Yeast ChIP data from Lee et al.""" if not data_available(data_set): download_data(data_set) from pandas import read_csv dir_path = os.path.join(data_path, data_set) filename = os.path.join(dir_path, 'binding_by_gene.tsv') S = read_csv(filename, header=1, index_col=0, sep='\t') transcription_factors = [col for col in S.columns if col[:7] != 'Unnamed'] annotations = S[['Unnamed: 1', 'Unnamed: 2', 'Unnamed: 3']] S = S[transcription_factors] return data_details_return({'annotations' : annotations, 'Y' : S, 'transcription_factors': transcription_factors}, data_set)
[ "def", "lee_yeast_ChIP", "(", "data_set", "=", "'lee_yeast_ChIP'", ")", ":", "if", "not", "data_available", "(", "data_set", ")", ":", "download_data", "(", "data_set", ")", "from", "pandas", "import", "read_csv", "dir_path", "=", "os", ".", "path", ".", "join", "(", "data_path", ",", "data_set", ")", "filename", "=", "os", ".", "path", ".", "join", "(", "dir_path", ",", "'binding_by_gene.tsv'", ")", "S", "=", "read_csv", "(", "filename", ",", "header", "=", "1", ",", "index_col", "=", "0", ",", "sep", "=", "'\\t'", ")", "transcription_factors", "=", "[", "col", "for", "col", "in", "S", ".", "columns", "if", "col", "[", ":", "7", "]", "!=", "'Unnamed'", "]", "annotations", "=", "S", "[", "[", "'Unnamed: 1'", ",", "'Unnamed: 2'", ",", "'Unnamed: 3'", "]", "]", "S", "=", "S", "[", "transcription_factors", "]", "return", "data_details_return", "(", "{", "'annotations'", ":", "annotations", ",", "'Y'", ":", "S", ",", "'transcription_factors'", ":", "transcription_factors", "}", ",", "data_set", ")" ]
Yeast ChIP data from Lee et al.
[ "Yeast", "ChIP", "data", "from", "Lee", "et", "al", "." ]
3995c659f25a0a640f6009ed7fcc2559ce659b1d
https://github.com/sods/ods/blob/3995c659f25a0a640f6009ed7fcc2559ce659b1d/pods/datasets.py#L684-L695
train
sods/ods
pods/datasets.py
google_trends
def google_trends(query_terms=['big data', 'machine learning', 'data science'], data_set='google_trends', refresh_data=False): """ Data downloaded from Google trends for given query terms. Warning, if you use this function multiple times in a row you get blocked due to terms of service violations. The function will cache the result of any query in an attempt to avoid this. If you wish to refresh an old query set refresh_data to True. The function is inspired by this notebook: http://nbviewer.ipython.org/github/sahuguet/notebooks/blob/master/GoogleTrends%20meet%20Notebook.ipynb """ query_terms.sort() import pandas as pd # Create directory name for data dir_path = os.path.join(data_path,'google_trends') if not os.path.isdir(dir_path): os.makedirs(dir_path) dir_name = '-'.join(query_terms) dir_name = dir_name.replace(' ', '_') dir_path = os.path.join(dir_path,dir_name) file = 'data.csv' file_name = os.path.join(dir_path,file) if not os.path.exists(file_name) or refresh_data: print("Accessing Google trends to acquire the data. Note that repeated accesses will result in a block due to a google terms of service violation. Failure at this point may be due to such blocks.") # quote the query terms. quoted_terms = [] for term in query_terms: quoted_terms.append(quote(term)) print("Query terms: ", ', '.join(query_terms)) print("Fetching query:") query = 'http://www.google.com/trends/fetchComponent?q=%s&cid=TIMESERIES_GRAPH_0&export=3' % ",".join(quoted_terms) data = urlopen(query).read().decode('utf8') print("Done.") # In the notebook they did some data cleaning: remove Javascript header+footer, and translate new Date(....,..,..) into YYYY-MM-DD. header = """// Data table response\ngoogle.visualization.Query.setResponse(""" data = data[len(header):-2] data = re.sub('new Date\((\d+),(\d+),(\d+)\)', (lambda m: '"%s-%02d-%02d"' % (m.group(1).strip(), 1+int(m.group(2)), int(m.group(3)))), data) timeseries = json.loads(data) columns = [k['label'] for k in timeseries['table']['cols']] rows = list(map(lambda x: [k['v'] for k in x['c']], timeseries['table']['rows'])) df = pd.DataFrame(rows, columns=columns) if not os.path.isdir(dir_path): os.makedirs(dir_path) df.to_csv(file_name) else: print("Reading cached data for google trends. To refresh the cache set 'refresh_data=True' when calling this function.") print("Query terms: ", ', '.join(query_terms)) df = pd.read_csv(file_name, parse_dates=[0]) columns = df.columns terms = len(query_terms) import datetime from matplotlib.dates import date2num X = np.asarray([(date2num(datetime.datetime.strptime(df.ix[row]['Date'], '%Y-%m-%d')), i) for i in range(terms) for row in df.index]) Y = np.asarray([[df.ix[row][query_terms[i]]] for i in range(terms) for row in df.index ]) output_info = columns[1:] cats = {} for i in range(terms): cats[query_terms[i]] = i return data_details_return({'data frame' : df, 'X': X, 'Y': Y, 'query_terms': query_terms, 'info': "Data downloaded from google trends with query terms: " + ', '.join(query_terms) + '.', 'covariates' : [datenum('date'), discrete(cats, 'query_terms')], 'response' : ['normalized interest']}, data_set)
python
def google_trends(query_terms=['big data', 'machine learning', 'data science'], data_set='google_trends', refresh_data=False): """ Data downloaded from Google trends for given query terms. Warning, if you use this function multiple times in a row you get blocked due to terms of service violations. The function will cache the result of any query in an attempt to avoid this. If you wish to refresh an old query set refresh_data to True. The function is inspired by this notebook: http://nbviewer.ipython.org/github/sahuguet/notebooks/blob/master/GoogleTrends%20meet%20Notebook.ipynb """ query_terms.sort() import pandas as pd # Create directory name for data dir_path = os.path.join(data_path,'google_trends') if not os.path.isdir(dir_path): os.makedirs(dir_path) dir_name = '-'.join(query_terms) dir_name = dir_name.replace(' ', '_') dir_path = os.path.join(dir_path,dir_name) file = 'data.csv' file_name = os.path.join(dir_path,file) if not os.path.exists(file_name) or refresh_data: print("Accessing Google trends to acquire the data. Note that repeated accesses will result in a block due to a google terms of service violation. Failure at this point may be due to such blocks.") # quote the query terms. quoted_terms = [] for term in query_terms: quoted_terms.append(quote(term)) print("Query terms: ", ', '.join(query_terms)) print("Fetching query:") query = 'http://www.google.com/trends/fetchComponent?q=%s&cid=TIMESERIES_GRAPH_0&export=3' % ",".join(quoted_terms) data = urlopen(query).read().decode('utf8') print("Done.") # In the notebook they did some data cleaning: remove Javascript header+footer, and translate new Date(....,..,..) into YYYY-MM-DD. header = """// Data table response\ngoogle.visualization.Query.setResponse(""" data = data[len(header):-2] data = re.sub('new Date\((\d+),(\d+),(\d+)\)', (lambda m: '"%s-%02d-%02d"' % (m.group(1).strip(), 1+int(m.group(2)), int(m.group(3)))), data) timeseries = json.loads(data) columns = [k['label'] for k in timeseries['table']['cols']] rows = list(map(lambda x: [k['v'] for k in x['c']], timeseries['table']['rows'])) df = pd.DataFrame(rows, columns=columns) if not os.path.isdir(dir_path): os.makedirs(dir_path) df.to_csv(file_name) else: print("Reading cached data for google trends. To refresh the cache set 'refresh_data=True' when calling this function.") print("Query terms: ", ', '.join(query_terms)) df = pd.read_csv(file_name, parse_dates=[0]) columns = df.columns terms = len(query_terms) import datetime from matplotlib.dates import date2num X = np.asarray([(date2num(datetime.datetime.strptime(df.ix[row]['Date'], '%Y-%m-%d')), i) for i in range(terms) for row in df.index]) Y = np.asarray([[df.ix[row][query_terms[i]]] for i in range(terms) for row in df.index ]) output_info = columns[1:] cats = {} for i in range(terms): cats[query_terms[i]] = i return data_details_return({'data frame' : df, 'X': X, 'Y': Y, 'query_terms': query_terms, 'info': "Data downloaded from google trends with query terms: " + ', '.join(query_terms) + '.', 'covariates' : [datenum('date'), discrete(cats, 'query_terms')], 'response' : ['normalized interest']}, data_set)
[ "def", "google_trends", "(", "query_terms", "=", "[", "'big data'", ",", "'machine learning'", ",", "'data science'", "]", ",", "data_set", "=", "'google_trends'", ",", "refresh_data", "=", "False", ")", ":", "query_terms", ".", "sort", "(", ")", "import", "pandas", "as", "pd", "# Create directory name for data", "dir_path", "=", "os", ".", "path", ".", "join", "(", "data_path", ",", "'google_trends'", ")", "if", "not", "os", ".", "path", ".", "isdir", "(", "dir_path", ")", ":", "os", ".", "makedirs", "(", "dir_path", ")", "dir_name", "=", "'-'", ".", "join", "(", "query_terms", ")", "dir_name", "=", "dir_name", ".", "replace", "(", "' '", ",", "'_'", ")", "dir_path", "=", "os", ".", "path", ".", "join", "(", "dir_path", ",", "dir_name", ")", "file", "=", "'data.csv'", "file_name", "=", "os", ".", "path", ".", "join", "(", "dir_path", ",", "file", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "file_name", ")", "or", "refresh_data", ":", "print", "(", "\"Accessing Google trends to acquire the data. Note that repeated accesses will result in a block due to a google terms of service violation. Failure at this point may be due to such blocks.\"", ")", "# quote the query terms.", "quoted_terms", "=", "[", "]", "for", "term", "in", "query_terms", ":", "quoted_terms", ".", "append", "(", "quote", "(", "term", ")", ")", "print", "(", "\"Query terms: \"", ",", "', '", ".", "join", "(", "query_terms", ")", ")", "print", "(", "\"Fetching query:\"", ")", "query", "=", "'http://www.google.com/trends/fetchComponent?q=%s&cid=TIMESERIES_GRAPH_0&export=3'", "%", "\",\"", ".", "join", "(", "quoted_terms", ")", "data", "=", "urlopen", "(", "query", ")", ".", "read", "(", ")", ".", "decode", "(", "'utf8'", ")", "print", "(", "\"Done.\"", ")", "# In the notebook they did some data cleaning: remove Javascript header+footer, and translate new Date(....,..,..) into YYYY-MM-DD.", "header", "=", "\"\"\"// Data table response\\ngoogle.visualization.Query.setResponse(\"\"\"", "data", "=", "data", "[", "len", "(", "header", ")", ":", "-", "2", "]", "data", "=", "re", ".", "sub", "(", "'new Date\\((\\d+),(\\d+),(\\d+)\\)'", ",", "(", "lambda", "m", ":", "'\"%s-%02d-%02d\"'", "%", "(", "m", ".", "group", "(", "1", ")", ".", "strip", "(", ")", ",", "1", "+", "int", "(", "m", ".", "group", "(", "2", ")", ")", ",", "int", "(", "m", ".", "group", "(", "3", ")", ")", ")", ")", ",", "data", ")", "timeseries", "=", "json", ".", "loads", "(", "data", ")", "columns", "=", "[", "k", "[", "'label'", "]", "for", "k", "in", "timeseries", "[", "'table'", "]", "[", "'cols'", "]", "]", "rows", "=", "list", "(", "map", "(", "lambda", "x", ":", "[", "k", "[", "'v'", "]", "for", "k", "in", "x", "[", "'c'", "]", "]", ",", "timeseries", "[", "'table'", "]", "[", "'rows'", "]", ")", ")", "df", "=", "pd", ".", "DataFrame", "(", "rows", ",", "columns", "=", "columns", ")", "if", "not", "os", ".", "path", ".", "isdir", "(", "dir_path", ")", ":", "os", ".", "makedirs", "(", "dir_path", ")", "df", ".", "to_csv", "(", "file_name", ")", "else", ":", "print", "(", "\"Reading cached data for google trends. To refresh the cache set 'refresh_data=True' when calling this function.\"", ")", "print", "(", "\"Query terms: \"", ",", "', '", ".", "join", "(", "query_terms", ")", ")", "df", "=", "pd", ".", "read_csv", "(", "file_name", ",", "parse_dates", "=", "[", "0", "]", ")", "columns", "=", "df", ".", "columns", "terms", "=", "len", "(", "query_terms", ")", "import", "datetime", "from", "matplotlib", ".", "dates", "import", "date2num", "X", "=", "np", ".", "asarray", "(", "[", "(", "date2num", "(", "datetime", ".", "datetime", ".", "strptime", "(", "df", ".", "ix", "[", "row", "]", "[", "'Date'", "]", ",", "'%Y-%m-%d'", ")", ")", ",", "i", ")", "for", "i", "in", "range", "(", "terms", ")", "for", "row", "in", "df", ".", "index", "]", ")", "Y", "=", "np", ".", "asarray", "(", "[", "[", "df", ".", "ix", "[", "row", "]", "[", "query_terms", "[", "i", "]", "]", "]", "for", "i", "in", "range", "(", "terms", ")", "for", "row", "in", "df", ".", "index", "]", ")", "output_info", "=", "columns", "[", "1", ":", "]", "cats", "=", "{", "}", "for", "i", "in", "range", "(", "terms", ")", ":", "cats", "[", "query_terms", "[", "i", "]", "]", "=", "i", "return", "data_details_return", "(", "{", "'data frame'", ":", "df", ",", "'X'", ":", "X", ",", "'Y'", ":", "Y", ",", "'query_terms'", ":", "query_terms", ",", "'info'", ":", "\"Data downloaded from google trends with query terms: \"", "+", "', '", ".", "join", "(", "query_terms", ")", "+", "'.'", ",", "'covariates'", ":", "[", "datenum", "(", "'date'", ")", ",", "discrete", "(", "cats", ",", "'query_terms'", ")", "]", ",", "'response'", ":", "[", "'normalized interest'", "]", "}", ",", "data_set", ")" ]
Data downloaded from Google trends for given query terms. Warning, if you use this function multiple times in a row you get blocked due to terms of service violations. The function will cache the result of any query in an attempt to avoid this. If you wish to refresh an old query set refresh_data to True. The function is inspired by this notebook: http://nbviewer.ipython.org/github/sahuguet/notebooks/blob/master/GoogleTrends%20meet%20Notebook.ipynb
[ "Data", "downloaded", "from", "Google", "trends", "for", "given", "query", "terms", ".", "Warning", "if", "you", "use", "this", "function", "multiple", "times", "in", "a", "row", "you", "get", "blocked", "due", "to", "terms", "of", "service", "violations", "." ]
3995c659f25a0a640f6009ed7fcc2559ce659b1d
https://github.com/sods/ods/blob/3995c659f25a0a640f6009ed7fcc2559ce659b1d/pods/datasets.py#L750-L817
train
sods/ods
pods/datasets.py
osu_run1
def osu_run1(data_set='osu_run1', sample_every=4): """Ohio State University's Run1 motion capture data set.""" path = os.path.join(data_path, data_set) if not data_available(data_set): import zipfile download_data(data_set) zip = zipfile.ZipFile(os.path.join(data_path, data_set, 'run1TXT.ZIP'), 'r') for name in zip.namelist(): zip.extract(name, path) from . import mocap Y, connect = mocap.load_text_data('Aug210106', path) Y = Y[0:-1:sample_every, :] return data_details_return({'Y': Y, 'connect' : connect}, data_set)
python
def osu_run1(data_set='osu_run1', sample_every=4): """Ohio State University's Run1 motion capture data set.""" path = os.path.join(data_path, data_set) if not data_available(data_set): import zipfile download_data(data_set) zip = zipfile.ZipFile(os.path.join(data_path, data_set, 'run1TXT.ZIP'), 'r') for name in zip.namelist(): zip.extract(name, path) from . import mocap Y, connect = mocap.load_text_data('Aug210106', path) Y = Y[0:-1:sample_every, :] return data_details_return({'Y': Y, 'connect' : connect}, data_set)
[ "def", "osu_run1", "(", "data_set", "=", "'osu_run1'", ",", "sample_every", "=", "4", ")", ":", "path", "=", "os", ".", "path", ".", "join", "(", "data_path", ",", "data_set", ")", "if", "not", "data_available", "(", "data_set", ")", ":", "import", "zipfile", "download_data", "(", "data_set", ")", "zip", "=", "zipfile", ".", "ZipFile", "(", "os", ".", "path", ".", "join", "(", "data_path", ",", "data_set", ",", "'run1TXT.ZIP'", ")", ",", "'r'", ")", "for", "name", "in", "zip", ".", "namelist", "(", ")", ":", "zip", ".", "extract", "(", "name", ",", "path", ")", "from", ".", "import", "mocap", "Y", ",", "connect", "=", "mocap", ".", "load_text_data", "(", "'Aug210106'", ",", "path", ")", "Y", "=", "Y", "[", "0", ":", "-", "1", ":", "sample_every", ",", ":", "]", "return", "data_details_return", "(", "{", "'Y'", ":", "Y", ",", "'connect'", ":", "connect", "}", ",", "data_set", ")" ]
Ohio State University's Run1 motion capture data set.
[ "Ohio", "State", "University", "s", "Run1", "motion", "capture", "data", "set", "." ]
3995c659f25a0a640f6009ed7fcc2559ce659b1d
https://github.com/sods/ods/blob/3995c659f25a0a640f6009ed7fcc2559ce659b1d/pods/datasets.py#L1009-L1021
train
sods/ods
pods/datasets.py
toy_linear_1d_classification
def toy_linear_1d_classification(seed=default_seed): """Simple classification data in one dimension for illustrating models.""" def sample_class(f): p = 1. / (1. + np.exp(-f)) c = np.random.binomial(1, p) c = np.where(c, 1, -1) return c np.random.seed(seed=seed) x1 = np.random.normal(-3, 5, 20) x2 = np.random.normal(3, 5, 20) X = (np.r_[x1, x2])[:, None] return {'X': X, 'Y': sample_class(2.*X), 'F': 2.*X, 'covariates' : ['X'], 'response': [discrete({'positive': 1, 'negative': -1})],'seed' : seed}
python
def toy_linear_1d_classification(seed=default_seed): """Simple classification data in one dimension for illustrating models.""" def sample_class(f): p = 1. / (1. + np.exp(-f)) c = np.random.binomial(1, p) c = np.where(c, 1, -1) return c np.random.seed(seed=seed) x1 = np.random.normal(-3, 5, 20) x2 = np.random.normal(3, 5, 20) X = (np.r_[x1, x2])[:, None] return {'X': X, 'Y': sample_class(2.*X), 'F': 2.*X, 'covariates' : ['X'], 'response': [discrete({'positive': 1, 'negative': -1})],'seed' : seed}
[ "def", "toy_linear_1d_classification", "(", "seed", "=", "default_seed", ")", ":", "def", "sample_class", "(", "f", ")", ":", "p", "=", "1.", "/", "(", "1.", "+", "np", ".", "exp", "(", "-", "f", ")", ")", "c", "=", "np", ".", "random", ".", "binomial", "(", "1", ",", "p", ")", "c", "=", "np", ".", "where", "(", "c", ",", "1", ",", "-", "1", ")", "return", "c", "np", ".", "random", ".", "seed", "(", "seed", "=", "seed", ")", "x1", "=", "np", ".", "random", ".", "normal", "(", "-", "3", ",", "5", ",", "20", ")", "x2", "=", "np", ".", "random", ".", "normal", "(", "3", ",", "5", ",", "20", ")", "X", "=", "(", "np", ".", "r_", "[", "x1", ",", "x2", "]", ")", "[", ":", ",", "None", "]", "return", "{", "'X'", ":", "X", ",", "'Y'", ":", "sample_class", "(", "2.", "*", "X", ")", ",", "'F'", ":", "2.", "*", "X", ",", "'covariates'", ":", "[", "'X'", "]", ",", "'response'", ":", "[", "discrete", "(", "{", "'positive'", ":", "1", ",", "'negative'", ":", "-", "1", "}", ")", "]", ",", "'seed'", ":", "seed", "}" ]
Simple classification data in one dimension for illustrating models.
[ "Simple", "classification", "data", "in", "one", "dimension", "for", "illustrating", "models", "." ]
3995c659f25a0a640f6009ed7fcc2559ce659b1d
https://github.com/sods/ods/blob/3995c659f25a0a640f6009ed7fcc2559ce659b1d/pods/datasets.py#L1108-L1120
train
sods/ods
pods/datasets.py
airline_delay
def airline_delay(data_set='airline_delay', num_train=700000, num_test=100000, seed=default_seed): """Airline delay data used in Gaussian Processes for Big Data by Hensman, Fusi and Lawrence""" if not data_available(data_set): download_data(data_set) dir_path = os.path.join(data_path, data_set) filename = os.path.join(dir_path, 'filtered_data.pickle') # 1. Load the dataset import pandas as pd data = pd.read_pickle(filename) # WARNING: removing year data.pop('Year') # Get data matrices Yall = data.pop('ArrDelay').values[:,None] Xall = data.values # Subset the data (memory!!) all_data = num_train+num_test Xall = Xall[:all_data] Yall = Yall[:all_data] # Get testing points np.random.seed(seed=seed) N_shuffled = permute(Yall.shape[0]) train, test = N_shuffled[num_test:], N_shuffled[:num_test] X, Y = Xall[train], Yall[train] Xtest, Ytest = Xall[test], Yall[test] covariates = ['month', 'day of month', 'day of week', 'departure time', 'arrival time', 'air time', 'distance to travel', 'age of aircraft / years'] response = ['delay'] return data_details_return({'X': X, 'Y': Y, 'Xtest': Xtest, 'Ytest': Ytest, 'seed' : seed, 'info': "Airline delay data used for demonstrating Gaussian processes for big data.", 'covariates': covariates, 'response': response}, data_set)
python
def airline_delay(data_set='airline_delay', num_train=700000, num_test=100000, seed=default_seed): """Airline delay data used in Gaussian Processes for Big Data by Hensman, Fusi and Lawrence""" if not data_available(data_set): download_data(data_set) dir_path = os.path.join(data_path, data_set) filename = os.path.join(dir_path, 'filtered_data.pickle') # 1. Load the dataset import pandas as pd data = pd.read_pickle(filename) # WARNING: removing year data.pop('Year') # Get data matrices Yall = data.pop('ArrDelay').values[:,None] Xall = data.values # Subset the data (memory!!) all_data = num_train+num_test Xall = Xall[:all_data] Yall = Yall[:all_data] # Get testing points np.random.seed(seed=seed) N_shuffled = permute(Yall.shape[0]) train, test = N_shuffled[num_test:], N_shuffled[:num_test] X, Y = Xall[train], Yall[train] Xtest, Ytest = Xall[test], Yall[test] covariates = ['month', 'day of month', 'day of week', 'departure time', 'arrival time', 'air time', 'distance to travel', 'age of aircraft / years'] response = ['delay'] return data_details_return({'X': X, 'Y': Y, 'Xtest': Xtest, 'Ytest': Ytest, 'seed' : seed, 'info': "Airline delay data used for demonstrating Gaussian processes for big data.", 'covariates': covariates, 'response': response}, data_set)
[ "def", "airline_delay", "(", "data_set", "=", "'airline_delay'", ",", "num_train", "=", "700000", ",", "num_test", "=", "100000", ",", "seed", "=", "default_seed", ")", ":", "if", "not", "data_available", "(", "data_set", ")", ":", "download_data", "(", "data_set", ")", "dir_path", "=", "os", ".", "path", ".", "join", "(", "data_path", ",", "data_set", ")", "filename", "=", "os", ".", "path", ".", "join", "(", "dir_path", ",", "'filtered_data.pickle'", ")", "# 1. Load the dataset", "import", "pandas", "as", "pd", "data", "=", "pd", ".", "read_pickle", "(", "filename", ")", "# WARNING: removing year", "data", ".", "pop", "(", "'Year'", ")", "# Get data matrices", "Yall", "=", "data", ".", "pop", "(", "'ArrDelay'", ")", ".", "values", "[", ":", ",", "None", "]", "Xall", "=", "data", ".", "values", "# Subset the data (memory!!)", "all_data", "=", "num_train", "+", "num_test", "Xall", "=", "Xall", "[", ":", "all_data", "]", "Yall", "=", "Yall", "[", ":", "all_data", "]", "# Get testing points", "np", ".", "random", ".", "seed", "(", "seed", "=", "seed", ")", "N_shuffled", "=", "permute", "(", "Yall", ".", "shape", "[", "0", "]", ")", "train", ",", "test", "=", "N_shuffled", "[", "num_test", ":", "]", ",", "N_shuffled", "[", ":", "num_test", "]", "X", ",", "Y", "=", "Xall", "[", "train", "]", ",", "Yall", "[", "train", "]", "Xtest", ",", "Ytest", "=", "Xall", "[", "test", "]", ",", "Yall", "[", "test", "]", "covariates", "=", "[", "'month'", ",", "'day of month'", ",", "'day of week'", ",", "'departure time'", ",", "'arrival time'", ",", "'air time'", ",", "'distance to travel'", ",", "'age of aircraft / years'", "]", "response", "=", "[", "'delay'", "]", "return", "data_details_return", "(", "{", "'X'", ":", "X", ",", "'Y'", ":", "Y", ",", "'Xtest'", ":", "Xtest", ",", "'Ytest'", ":", "Ytest", ",", "'seed'", ":", "seed", ",", "'info'", ":", "\"Airline delay data used for demonstrating Gaussian processes for big data.\"", ",", "'covariates'", ":", "covariates", ",", "'response'", ":", "response", "}", ",", "data_set", ")" ]
Airline delay data used in Gaussian Processes for Big Data by Hensman, Fusi and Lawrence
[ "Airline", "delay", "data", "used", "in", "Gaussian", "Processes", "for", "Big", "Data", "by", "Hensman", "Fusi", "and", "Lawrence" ]
3995c659f25a0a640f6009ed7fcc2559ce659b1d
https://github.com/sods/ods/blob/3995c659f25a0a640f6009ed7fcc2559ce659b1d/pods/datasets.py#L1122-L1155
train
sods/ods
pods/datasets.py
olympic_sprints
def olympic_sprints(data_set='rogers_girolami_data'): """All olympics sprint winning times for multiple output prediction.""" X = np.zeros((0, 2)) Y = np.zeros((0, 1)) cats = {} for i, dataset in enumerate([olympic_100m_men, olympic_100m_women, olympic_200m_men, olympic_200m_women, olympic_400m_men, olympic_400m_women]): data = dataset() year = data['X'] time = data['Y'] X = np.vstack((X, np.hstack((year, np.ones_like(year)*i)))) Y = np.vstack((Y, time)) cats[dataset.__name__] = i data['X'] = X data['Y'] = Y data['info'] = "Olympics sprint event winning for men and women to 2008. Data is from Rogers and Girolami's First Course in Machine Learning." return data_details_return({ 'X': X, 'Y': Y, 'covariates' : [decimalyear('year', '%Y'), discrete(cats, 'event')], 'response' : ['time'], 'info': "Olympics sprint event winning for men and women to 2008. Data is from Rogers and Girolami's First Course in Machine Learning.", 'output_info': { 0:'100m Men', 1:'100m Women', 2:'200m Men', 3:'200m Women', 4:'400m Men', 5:'400m Women'} }, data_set)
python
def olympic_sprints(data_set='rogers_girolami_data'): """All olympics sprint winning times for multiple output prediction.""" X = np.zeros((0, 2)) Y = np.zeros((0, 1)) cats = {} for i, dataset in enumerate([olympic_100m_men, olympic_100m_women, olympic_200m_men, olympic_200m_women, olympic_400m_men, olympic_400m_women]): data = dataset() year = data['X'] time = data['Y'] X = np.vstack((X, np.hstack((year, np.ones_like(year)*i)))) Y = np.vstack((Y, time)) cats[dataset.__name__] = i data['X'] = X data['Y'] = Y data['info'] = "Olympics sprint event winning for men and women to 2008. Data is from Rogers and Girolami's First Course in Machine Learning." return data_details_return({ 'X': X, 'Y': Y, 'covariates' : [decimalyear('year', '%Y'), discrete(cats, 'event')], 'response' : ['time'], 'info': "Olympics sprint event winning for men and women to 2008. Data is from Rogers and Girolami's First Course in Machine Learning.", 'output_info': { 0:'100m Men', 1:'100m Women', 2:'200m Men', 3:'200m Women', 4:'400m Men', 5:'400m Women'} }, data_set)
[ "def", "olympic_sprints", "(", "data_set", "=", "'rogers_girolami_data'", ")", ":", "X", "=", "np", ".", "zeros", "(", "(", "0", ",", "2", ")", ")", "Y", "=", "np", ".", "zeros", "(", "(", "0", ",", "1", ")", ")", "cats", "=", "{", "}", "for", "i", ",", "dataset", "in", "enumerate", "(", "[", "olympic_100m_men", ",", "olympic_100m_women", ",", "olympic_200m_men", ",", "olympic_200m_women", ",", "olympic_400m_men", ",", "olympic_400m_women", "]", ")", ":", "data", "=", "dataset", "(", ")", "year", "=", "data", "[", "'X'", "]", "time", "=", "data", "[", "'Y'", "]", "X", "=", "np", ".", "vstack", "(", "(", "X", ",", "np", ".", "hstack", "(", "(", "year", ",", "np", ".", "ones_like", "(", "year", ")", "*", "i", ")", ")", ")", ")", "Y", "=", "np", ".", "vstack", "(", "(", "Y", ",", "time", ")", ")", "cats", "[", "dataset", ".", "__name__", "]", "=", "i", "data", "[", "'X'", "]", "=", "X", "data", "[", "'Y'", "]", "=", "Y", "data", "[", "'info'", "]", "=", "\"Olympics sprint event winning for men and women to 2008. Data is from Rogers and Girolami's First Course in Machine Learning.\"", "return", "data_details_return", "(", "{", "'X'", ":", "X", ",", "'Y'", ":", "Y", ",", "'covariates'", ":", "[", "decimalyear", "(", "'year'", ",", "'%Y'", ")", ",", "discrete", "(", "cats", ",", "'event'", ")", "]", ",", "'response'", ":", "[", "'time'", "]", ",", "'info'", ":", "\"Olympics sprint event winning for men and women to 2008. Data is from Rogers and Girolami's First Course in Machine Learning.\"", ",", "'output_info'", ":", "{", "0", ":", "'100m Men'", ",", "1", ":", "'100m Women'", ",", "2", ":", "'200m Men'", ",", "3", ":", "'200m Women'", ",", "4", ":", "'400m Men'", ",", "5", ":", "'400m Women'", "}", "}", ",", "data_set", ")" ]
All olympics sprint winning times for multiple output prediction.
[ "All", "olympics", "sprint", "winning", "times", "for", "multiple", "output", "prediction", "." ]
3995c659f25a0a640f6009ed7fcc2559ce659b1d
https://github.com/sods/ods/blob/3995c659f25a0a640f6009ed7fcc2559ce659b1d/pods/datasets.py#L1271-L1304
train
sods/ods
pods/datasets.py
movie_body_count
def movie_body_count(data_set='movie_body_count'): """Data set of movies and body count for movies scraped from www.MovieBodyCounts.com created by Simon Garnier and Randy Olson for exploring differences between Python and R.""" if not data_available(data_set): download_data(data_set) from pandas import read_csv dir_path = os.path.join(data_path, data_set) filename = os.path.join(dir_path, 'film-death-counts-Python.csv') Y = read_csv(filename) Y['Actors'] = Y['Actors'].apply(lambda x: x.split('|')) Y['Genre'] = Y['Genre'].apply(lambda x: x.split('|')) Y['Director'] = Y['Director'].apply(lambda x: x.split('|')) return data_details_return({'Y': Y, 'info' : "Data set of movies and body count for movies scraped from www.MovieBodyCounts.com created by Simon Garnier and Randy Olson for exploring differences between Python and R.", }, data_set)
python
def movie_body_count(data_set='movie_body_count'): """Data set of movies and body count for movies scraped from www.MovieBodyCounts.com created by Simon Garnier and Randy Olson for exploring differences between Python and R.""" if not data_available(data_set): download_data(data_set) from pandas import read_csv dir_path = os.path.join(data_path, data_set) filename = os.path.join(dir_path, 'film-death-counts-Python.csv') Y = read_csv(filename) Y['Actors'] = Y['Actors'].apply(lambda x: x.split('|')) Y['Genre'] = Y['Genre'].apply(lambda x: x.split('|')) Y['Director'] = Y['Director'].apply(lambda x: x.split('|')) return data_details_return({'Y': Y, 'info' : "Data set of movies and body count for movies scraped from www.MovieBodyCounts.com created by Simon Garnier and Randy Olson for exploring differences between Python and R.", }, data_set)
[ "def", "movie_body_count", "(", "data_set", "=", "'movie_body_count'", ")", ":", "if", "not", "data_available", "(", "data_set", ")", ":", "download_data", "(", "data_set", ")", "from", "pandas", "import", "read_csv", "dir_path", "=", "os", ".", "path", ".", "join", "(", "data_path", ",", "data_set", ")", "filename", "=", "os", ".", "path", ".", "join", "(", "dir_path", ",", "'film-death-counts-Python.csv'", ")", "Y", "=", "read_csv", "(", "filename", ")", "Y", "[", "'Actors'", "]", "=", "Y", "[", "'Actors'", "]", ".", "apply", "(", "lambda", "x", ":", "x", ".", "split", "(", "'|'", ")", ")", "Y", "[", "'Genre'", "]", "=", "Y", "[", "'Genre'", "]", ".", "apply", "(", "lambda", "x", ":", "x", ".", "split", "(", "'|'", ")", ")", "Y", "[", "'Director'", "]", "=", "Y", "[", "'Director'", "]", ".", "apply", "(", "lambda", "x", ":", "x", ".", "split", "(", "'|'", ")", ")", "return", "data_details_return", "(", "{", "'Y'", ":", "Y", ",", "'info'", ":", "\"Data set of movies and body count for movies scraped from www.MovieBodyCounts.com created by Simon Garnier and Randy Olson for exploring differences between Python and R.\"", ",", "}", ",", "data_set", ")" ]
Data set of movies and body count for movies scraped from www.MovieBodyCounts.com created by Simon Garnier and Randy Olson for exploring differences between Python and R.
[ "Data", "set", "of", "movies", "and", "body", "count", "for", "movies", "scraped", "from", "www", ".", "MovieBodyCounts", ".", "com", "created", "by", "Simon", "Garnier", "and", "Randy", "Olson", "for", "exploring", "differences", "between", "Python", "and", "R", "." ]
3995c659f25a0a640f6009ed7fcc2559ce659b1d
https://github.com/sods/ods/blob/3995c659f25a0a640f6009ed7fcc2559ce659b1d/pods/datasets.py#L1306-L1319
train
sods/ods
pods/datasets.py
movie_body_count_r_classify
def movie_body_count_r_classify(data_set='movie_body_count'): """Data set of movies and body count for movies scraped from www.MovieBodyCounts.com created by Simon Garnier and Randy Olson for exploring differences between Python and R.""" data = movie_body_count()['Y'] import pandas as pd import numpy as np X = data[['Year', 'Body_Count']] Y = data['MPAA_Rating']=='R' # set label to be positive for R rated films. # Create series of movie genres with the relevant index s = data['Genre'].str.split('|').apply(pd.Series, 1).stack() s.index = s.index.droplevel(-1) # to line up with df's index # Extract from the series the unique list of genres. genres = s.unique() # For each genre extract the indices where it is present and add a column to X for genre in genres: index = s[s==genre].index.tolist() values = pd.Series(np.zeros(X.shape[0]), index=X.index) values[index] = 1 X[genre] = values return data_details_return({'X': X, 'Y': Y, 'info' : "Data set of movies and body count for movies scraped from www.MovieBodyCounts.com created by Simon Garnier and Randy Olson for exploring differences between Python and R. In this variant we aim to classify whether the film is rated R or not depending on the genre, the years and the body count.", }, data_set)
python
def movie_body_count_r_classify(data_set='movie_body_count'): """Data set of movies and body count for movies scraped from www.MovieBodyCounts.com created by Simon Garnier and Randy Olson for exploring differences between Python and R.""" data = movie_body_count()['Y'] import pandas as pd import numpy as np X = data[['Year', 'Body_Count']] Y = data['MPAA_Rating']=='R' # set label to be positive for R rated films. # Create series of movie genres with the relevant index s = data['Genre'].str.split('|').apply(pd.Series, 1).stack() s.index = s.index.droplevel(-1) # to line up with df's index # Extract from the series the unique list of genres. genres = s.unique() # For each genre extract the indices where it is present and add a column to X for genre in genres: index = s[s==genre].index.tolist() values = pd.Series(np.zeros(X.shape[0]), index=X.index) values[index] = 1 X[genre] = values return data_details_return({'X': X, 'Y': Y, 'info' : "Data set of movies and body count for movies scraped from www.MovieBodyCounts.com created by Simon Garnier and Randy Olson for exploring differences between Python and R. In this variant we aim to classify whether the film is rated R or not depending on the genre, the years and the body count.", }, data_set)
[ "def", "movie_body_count_r_classify", "(", "data_set", "=", "'movie_body_count'", ")", ":", "data", "=", "movie_body_count", "(", ")", "[", "'Y'", "]", "import", "pandas", "as", "pd", "import", "numpy", "as", "np", "X", "=", "data", "[", "[", "'Year'", ",", "'Body_Count'", "]", "]", "Y", "=", "data", "[", "'MPAA_Rating'", "]", "==", "'R'", "# set label to be positive for R rated films.", "# Create series of movie genres with the relevant index", "s", "=", "data", "[", "'Genre'", "]", ".", "str", ".", "split", "(", "'|'", ")", ".", "apply", "(", "pd", ".", "Series", ",", "1", ")", ".", "stack", "(", ")", "s", ".", "index", "=", "s", ".", "index", ".", "droplevel", "(", "-", "1", ")", "# to line up with df's index", "# Extract from the series the unique list of genres.", "genres", "=", "s", ".", "unique", "(", ")", "# For each genre extract the indices where it is present and add a column to X", "for", "genre", "in", "genres", ":", "index", "=", "s", "[", "s", "==", "genre", "]", ".", "index", ".", "tolist", "(", ")", "values", "=", "pd", ".", "Series", "(", "np", ".", "zeros", "(", "X", ".", "shape", "[", "0", "]", ")", ",", "index", "=", "X", ".", "index", ")", "values", "[", "index", "]", "=", "1", "X", "[", "genre", "]", "=", "values", "return", "data_details_return", "(", "{", "'X'", ":", "X", ",", "'Y'", ":", "Y", ",", "'info'", ":", "\"Data set of movies and body count for movies scraped from www.MovieBodyCounts.com created by Simon Garnier and Randy Olson for exploring differences between Python and R. In this variant we aim to classify whether the film is rated R or not depending on the genre, the years and the body count.\"", ",", "}", ",", "data_set", ")" ]
Data set of movies and body count for movies scraped from www.MovieBodyCounts.com created by Simon Garnier and Randy Olson for exploring differences between Python and R.
[ "Data", "set", "of", "movies", "and", "body", "count", "for", "movies", "scraped", "from", "www", ".", "MovieBodyCounts", ".", "com", "created", "by", "Simon", "Garnier", "and", "Randy", "Olson", "for", "exploring", "differences", "between", "Python", "and", "R", "." ]
3995c659f25a0a640f6009ed7fcc2559ce659b1d
https://github.com/sods/ods/blob/3995c659f25a0a640f6009ed7fcc2559ce659b1d/pods/datasets.py#L1321-L1343
train
sods/ods
pods/datasets.py
movielens100k
def movielens100k(data_set='movielens100k'): """Data set of movie ratings collected by the University of Minnesota and 'cleaned up' for use.""" if not data_available(data_set): import zipfile download_data(data_set) dir_path = os.path.join(data_path, data_set) zip = zipfile.ZipFile(os.path.join(dir_path, 'ml-100k.zip'), 'r') for name in zip.namelist(): zip.extract(name, dir_path) import pandas as pd encoding = 'latin-1' movie_path = os.path.join(data_path, 'movielens100k', 'ml-100k') items = pd.read_csv(os.path.join(movie_path, 'u.item'), index_col = 'index', header=None, sep='|',names=['index', 'title', 'date', 'empty', 'imdb_url', 'unknown', 'Action', 'Adventure', 'Animation', 'Children''s', 'Comedy', 'Crime', 'Documentary', 'Drama', 'Fantasy', 'Film-Noir', 'Horror', 'Musical', 'Mystery', 'Romance', 'Sci-Fi', 'Thriller', 'War', 'Western'], encoding=encoding) users = pd.read_csv(os.path.join(movie_path, 'u.user'), index_col = 'index', header=None, sep='|', names=['index', 'age', 'sex', 'job', 'id'], encoding=encoding) parts = ['u1.base', 'u1.test', 'u2.base', 'u2.test','u3.base', 'u3.test','u4.base', 'u4.test','u5.base', 'u5.test','ua.base', 'ua.test','ub.base', 'ub.test'] ratings = [] for part in parts: rate_part = pd.read_csv(os.path.join(movie_path, part), index_col = 'index', header=None, sep='\t', names=['user', 'item', 'rating', 'index'], encoding=encoding) rate_part['split'] = part ratings.append(rate_part) Y = pd.concat(ratings) return data_details_return({'Y':Y, 'film_info':items, 'user_info':users, 'info': 'The Movielens 100k data'}, data_set)
python
def movielens100k(data_set='movielens100k'): """Data set of movie ratings collected by the University of Minnesota and 'cleaned up' for use.""" if not data_available(data_set): import zipfile download_data(data_set) dir_path = os.path.join(data_path, data_set) zip = zipfile.ZipFile(os.path.join(dir_path, 'ml-100k.zip'), 'r') for name in zip.namelist(): zip.extract(name, dir_path) import pandas as pd encoding = 'latin-1' movie_path = os.path.join(data_path, 'movielens100k', 'ml-100k') items = pd.read_csv(os.path.join(movie_path, 'u.item'), index_col = 'index', header=None, sep='|',names=['index', 'title', 'date', 'empty', 'imdb_url', 'unknown', 'Action', 'Adventure', 'Animation', 'Children''s', 'Comedy', 'Crime', 'Documentary', 'Drama', 'Fantasy', 'Film-Noir', 'Horror', 'Musical', 'Mystery', 'Romance', 'Sci-Fi', 'Thriller', 'War', 'Western'], encoding=encoding) users = pd.read_csv(os.path.join(movie_path, 'u.user'), index_col = 'index', header=None, sep='|', names=['index', 'age', 'sex', 'job', 'id'], encoding=encoding) parts = ['u1.base', 'u1.test', 'u2.base', 'u2.test','u3.base', 'u3.test','u4.base', 'u4.test','u5.base', 'u5.test','ua.base', 'ua.test','ub.base', 'ub.test'] ratings = [] for part in parts: rate_part = pd.read_csv(os.path.join(movie_path, part), index_col = 'index', header=None, sep='\t', names=['user', 'item', 'rating', 'index'], encoding=encoding) rate_part['split'] = part ratings.append(rate_part) Y = pd.concat(ratings) return data_details_return({'Y':Y, 'film_info':items, 'user_info':users, 'info': 'The Movielens 100k data'}, data_set)
[ "def", "movielens100k", "(", "data_set", "=", "'movielens100k'", ")", ":", "if", "not", "data_available", "(", "data_set", ")", ":", "import", "zipfile", "download_data", "(", "data_set", ")", "dir_path", "=", "os", ".", "path", ".", "join", "(", "data_path", ",", "data_set", ")", "zip", "=", "zipfile", ".", "ZipFile", "(", "os", ".", "path", ".", "join", "(", "dir_path", ",", "'ml-100k.zip'", ")", ",", "'r'", ")", "for", "name", "in", "zip", ".", "namelist", "(", ")", ":", "zip", ".", "extract", "(", "name", ",", "dir_path", ")", "import", "pandas", "as", "pd", "encoding", "=", "'latin-1'", "movie_path", "=", "os", ".", "path", ".", "join", "(", "data_path", ",", "'movielens100k'", ",", "'ml-100k'", ")", "items", "=", "pd", ".", "read_csv", "(", "os", ".", "path", ".", "join", "(", "movie_path", ",", "'u.item'", ")", ",", "index_col", "=", "'index'", ",", "header", "=", "None", ",", "sep", "=", "'|'", ",", "names", "=", "[", "'index'", ",", "'title'", ",", "'date'", ",", "'empty'", ",", "'imdb_url'", ",", "'unknown'", ",", "'Action'", ",", "'Adventure'", ",", "'Animation'", ",", "'Children'", "'s'", ",", "'Comedy'", ",", "'Crime'", ",", "'Documentary'", ",", "'Drama'", ",", "'Fantasy'", ",", "'Film-Noir'", ",", "'Horror'", ",", "'Musical'", ",", "'Mystery'", ",", "'Romance'", ",", "'Sci-Fi'", ",", "'Thriller'", ",", "'War'", ",", "'Western'", "]", ",", "encoding", "=", "encoding", ")", "users", "=", "pd", ".", "read_csv", "(", "os", ".", "path", ".", "join", "(", "movie_path", ",", "'u.user'", ")", ",", "index_col", "=", "'index'", ",", "header", "=", "None", ",", "sep", "=", "'|'", ",", "names", "=", "[", "'index'", ",", "'age'", ",", "'sex'", ",", "'job'", ",", "'id'", "]", ",", "encoding", "=", "encoding", ")", "parts", "=", "[", "'u1.base'", ",", "'u1.test'", ",", "'u2.base'", ",", "'u2.test'", ",", "'u3.base'", ",", "'u3.test'", ",", "'u4.base'", ",", "'u4.test'", ",", "'u5.base'", ",", "'u5.test'", ",", "'ua.base'", ",", "'ua.test'", ",", "'ub.base'", ",", "'ub.test'", "]", "ratings", "=", "[", "]", "for", "part", "in", "parts", ":", "rate_part", "=", "pd", ".", "read_csv", "(", "os", ".", "path", ".", "join", "(", "movie_path", ",", "part", ")", ",", "index_col", "=", "'index'", ",", "header", "=", "None", ",", "sep", "=", "'\\t'", ",", "names", "=", "[", "'user'", ",", "'item'", ",", "'rating'", ",", "'index'", "]", ",", "encoding", "=", "encoding", ")", "rate_part", "[", "'split'", "]", "=", "part", "ratings", ".", "append", "(", "rate_part", ")", "Y", "=", "pd", ".", "concat", "(", "ratings", ")", "return", "data_details_return", "(", "{", "'Y'", ":", "Y", ",", "'film_info'", ":", "items", ",", "'user_info'", ":", "users", ",", "'info'", ":", "'The Movielens 100k data'", "}", ",", "data_set", ")" ]
Data set of movie ratings collected by the University of Minnesota and 'cleaned up' for use.
[ "Data", "set", "of", "movie", "ratings", "collected", "by", "the", "University", "of", "Minnesota", "and", "cleaned", "up", "for", "use", "." ]
3995c659f25a0a640f6009ed7fcc2559ce659b1d
https://github.com/sods/ods/blob/3995c659f25a0a640f6009ed7fcc2559ce659b1d/pods/datasets.py#L1347-L1368
train
sods/ods
pods/datasets.py
ceres
def ceres(data_set='ceres'): """Twenty two observations of the Dwarf planet Ceres as observed by Giueseppe Piazzi and published in the September edition of Monatlicher Correspondenz in 1801. These were the measurements used by Gauss to fit a model of the planets orbit through which the planet was recovered three months later.""" if not data_available(data_set): download_data(data_set) import pandas as pd data = pd.read_csv(os.path.join(data_path, data_set, 'ceresData.txt'), index_col = 'Tag', header=None, sep='\t',names=['Tag', 'Mittlere Sonnenzeit', 'Gerade Aufstig in Zeit', 'Gerade Aufstiegung in Graden', 'Nordlich Abweich', 'Geocentrische Laenger', 'Geocentrische Breite', 'Ort der Sonne + 20" Aberration', 'Logar. d. Distanz'], parse_dates=True, dayfirst=False) return data_details_return({'data': data}, data_set)
python
def ceres(data_set='ceres'): """Twenty two observations of the Dwarf planet Ceres as observed by Giueseppe Piazzi and published in the September edition of Monatlicher Correspondenz in 1801. These were the measurements used by Gauss to fit a model of the planets orbit through which the planet was recovered three months later.""" if not data_available(data_set): download_data(data_set) import pandas as pd data = pd.read_csv(os.path.join(data_path, data_set, 'ceresData.txt'), index_col = 'Tag', header=None, sep='\t',names=['Tag', 'Mittlere Sonnenzeit', 'Gerade Aufstig in Zeit', 'Gerade Aufstiegung in Graden', 'Nordlich Abweich', 'Geocentrische Laenger', 'Geocentrische Breite', 'Ort der Sonne + 20" Aberration', 'Logar. d. Distanz'], parse_dates=True, dayfirst=False) return data_details_return({'data': data}, data_set)
[ "def", "ceres", "(", "data_set", "=", "'ceres'", ")", ":", "if", "not", "data_available", "(", "data_set", ")", ":", "download_data", "(", "data_set", ")", "import", "pandas", "as", "pd", "data", "=", "pd", ".", "read_csv", "(", "os", ".", "path", ".", "join", "(", "data_path", ",", "data_set", ",", "'ceresData.txt'", ")", ",", "index_col", "=", "'Tag'", ",", "header", "=", "None", ",", "sep", "=", "'\\t'", ",", "names", "=", "[", "'Tag'", ",", "'Mittlere Sonnenzeit'", ",", "'Gerade Aufstig in Zeit'", ",", "'Gerade Aufstiegung in Graden'", ",", "'Nordlich Abweich'", ",", "'Geocentrische Laenger'", ",", "'Geocentrische Breite'", ",", "'Ort der Sonne + 20\" Aberration'", ",", "'Logar. d. Distanz'", "]", ",", "parse_dates", "=", "True", ",", "dayfirst", "=", "False", ")", "return", "data_details_return", "(", "{", "'data'", ":", "data", "}", ",", "data_set", ")" ]
Twenty two observations of the Dwarf planet Ceres as observed by Giueseppe Piazzi and published in the September edition of Monatlicher Correspondenz in 1801. These were the measurements used by Gauss to fit a model of the planets orbit through which the planet was recovered three months later.
[ "Twenty", "two", "observations", "of", "the", "Dwarf", "planet", "Ceres", "as", "observed", "by", "Giueseppe", "Piazzi", "and", "published", "in", "the", "September", "edition", "of", "Monatlicher", "Correspondenz", "in", "1801", ".", "These", "were", "the", "measurements", "used", "by", "Gauss", "to", "fit", "a", "model", "of", "the", "planets", "orbit", "through", "which", "the", "planet", "was", "recovered", "three", "months", "later", "." ]
3995c659f25a0a640f6009ed7fcc2559ce659b1d
https://github.com/sods/ods/blob/3995c659f25a0a640f6009ed7fcc2559ce659b1d/pods/datasets.py#L1432-L1438
train
rbuffat/pyepw
pyepw/calc.py
calc_horizontal_infrared_radiation_intensity
def calc_horizontal_infrared_radiation_intensity(weatherdata): """ Estimates the global horizontal infrared radiation intensity based on drybulb, dewpoint and opaque sky cover. References: Walton, G. N. 1983. Thermal Analysis Research Program Reference Manual. NBSSIR 83- 2655. National Bureau of Standards, p. 21. Clark, G. and C. Allen, "The Estimation of Atmospheric Radiation for Clear and Cloudy Skies," Proceedings 2nd National Passive Solar Conference (AS/ISES), 1978, pp. 675-678. """ temp_drybulb_K = C2K(weatherdata._dry_bulb_temperature) temp_dew_K = C2K(weatherdata.dew_point_temperature) N = weatherdata.opaque_sky_cover sky_emissivity = (0.787 + 0.764 * math.log(temp_dew_K / C2K(0.0)) * (1.0 + 0.0224 * N - 0.0035 * N ** 2 + 0.00028 * N ** 3)) hor_id = sky_emissivity * sigma * temp_drybulb_K ** 4 weatherdata.horizontal_infrared_radiation_intensity = hor_id
python
def calc_horizontal_infrared_radiation_intensity(weatherdata): """ Estimates the global horizontal infrared radiation intensity based on drybulb, dewpoint and opaque sky cover. References: Walton, G. N. 1983. Thermal Analysis Research Program Reference Manual. NBSSIR 83- 2655. National Bureau of Standards, p. 21. Clark, G. and C. Allen, "The Estimation of Atmospheric Radiation for Clear and Cloudy Skies," Proceedings 2nd National Passive Solar Conference (AS/ISES), 1978, pp. 675-678. """ temp_drybulb_K = C2K(weatherdata._dry_bulb_temperature) temp_dew_K = C2K(weatherdata.dew_point_temperature) N = weatherdata.opaque_sky_cover sky_emissivity = (0.787 + 0.764 * math.log(temp_dew_K / C2K(0.0)) * (1.0 + 0.0224 * N - 0.0035 * N ** 2 + 0.00028 * N ** 3)) hor_id = sky_emissivity * sigma * temp_drybulb_K ** 4 weatherdata.horizontal_infrared_radiation_intensity = hor_id
[ "def", "calc_horizontal_infrared_radiation_intensity", "(", "weatherdata", ")", ":", "temp_drybulb_K", "=", "C2K", "(", "weatherdata", ".", "_dry_bulb_temperature", ")", "temp_dew_K", "=", "C2K", "(", "weatherdata", ".", "dew_point_temperature", ")", "N", "=", "weatherdata", ".", "opaque_sky_cover", "sky_emissivity", "=", "(", "0.787", "+", "0.764", "*", "math", ".", "log", "(", "temp_dew_K", "/", "C2K", "(", "0.0", ")", ")", "*", "(", "1.0", "+", "0.0224", "*", "N", "-", "0.0035", "*", "N", "**", "2", "+", "0.00028", "*", "N", "**", "3", ")", ")", "hor_id", "=", "sky_emissivity", "*", "sigma", "*", "temp_drybulb_K", "**", "4", "weatherdata", ".", "horizontal_infrared_radiation_intensity", "=", "hor_id" ]
Estimates the global horizontal infrared radiation intensity based on drybulb, dewpoint and opaque sky cover. References: Walton, G. N. 1983. Thermal Analysis Research Program Reference Manual. NBSSIR 83- 2655. National Bureau of Standards, p. 21. Clark, G. and C. Allen, "The Estimation of Atmospheric Radiation for Clear and Cloudy Skies," Proceedings 2nd National Passive Solar Conference (AS/ISES), 1978, pp. 675-678.
[ "Estimates", "the", "global", "horizontal", "infrared", "radiation", "intensity", "based", "on", "drybulb", "dewpoint", "and", "opaque", "sky", "cover", ".", "References", ":", "Walton", "G", ".", "N", ".", "1983", ".", "Thermal", "Analysis", "Research", "Program", "Reference", "Manual", ".", "NBSSIR", "83", "-", "2655", ".", "National", "Bureau", "of", "Standards", "p", ".", "21", ".", "Clark", "G", ".", "and", "C", ".", "Allen", "The", "Estimation", "of", "Atmospheric", "Radiation", "for", "Clear", "and", "Cloudy", "Skies", "Proceedings", "2nd", "National", "Passive", "Solar", "Conference", "(", "AS", "/", "ISES", ")", "1978", "pp", ".", "675", "-", "678", "." ]
373d4d3c8386c8d35789f086ac5f6018c2711745
https://github.com/rbuffat/pyepw/blob/373d4d3c8386c8d35789f086ac5f6018c2711745/pyepw/calc.py#L10-L25
train
sods/ods
pods/util.py
download_url
def download_url(url, dir_name='.', save_name=None, store_directory=None, messages=True, suffix=''): """Download a file from a url and save it to disk.""" if sys.version_info>=(3,0): from urllib.parse import quote from urllib.request import urlopen from urllib.error import HTTPError, URLError else: from urllib2 import quote from urllib2 import urlopen from urllib2 import URLError as HTTPError i = url.rfind('/') file = url[i+1:] if store_directory is not None: dir_name = os.path.join(dir_name, store_directory) if save_name is None: save_name = file save_name = os.path.join(dir_name, save_name) print("Downloading ", url, "->", save_name) if not os.path.exists(dir_name): os.makedirs(dir_name) try: response = urlopen(url+suffix) except HTTPError as e: if not hasattr(e, "code"): raise if e.code > 399 and e.code<500: raise ValueError('Tried url ' + url + suffix + ' and received client error ' + str(e.code)) elif e.code > 499: raise ValueError('Tried url ' + url + suffix + ' and received server error ' + str(e.code)) except URLError as e: raise ValueError('Tried url ' + url + suffix + ' and failed with error ' + str(e.reason)) with open(save_name, 'wb') as f: meta = response.info() content_length_str = meta.get("Content-Length") if content_length_str: #if sys.version_info>=(3,0): try: file_size = int(content_length_str) except: try: file_size = int(content_length_str[0]) except: file_size = None if file_size == 1: file_size = None #else: # file_size = int(content_length_str) else: file_size = None status = "" file_size_dl = 0 block_sz = 8192 line_length = 30 percentage = 1./line_length if file_size: print("|"+"{:^{ll}}".format("Downloading {:7.3f}MB".format(file_size/(1048576.)), ll=line_length)+"|") from itertools import cycle cycle_str = cycle('>') sys.stdout.write("|") while True: buff = response.read(block_sz) if not buff: break file_size_dl += len(buff) f.write(buff) # If content_length_str was incorrect, we can end up with many too many equals signs, catches this edge case #correct_meta = float(file_size_dl)/file_size <= 1.0 if file_size: if (float(file_size_dl)/file_size) >= percentage: sys.stdout.write(next(cycle_str)) sys.stdout.flush() percentage += 1./line_length #percentage = "="*int(line_length*float(file_size_dl)/file_size) #status = r"[{perc: <{ll}}] {dl:7.3f}/{full:.3f}MB".format(dl=file_size_dl/(1048576.), full=file_size/(1048576.), ll=line_length, perc=percentage) else: sys.stdout.write(" "*(len(status)) + "\r") status = r"{dl:7.3f}MB".format(dl=file_size_dl/(1048576.), ll=line_length, perc="."*int(line_length*float(file_size_dl/(10*1048576.)))) sys.stdout.write(status) sys.stdout.flush() #sys.stdout.write(status) if file_size: sys.stdout.write("|") sys.stdout.flush() print(status)
python
def download_url(url, dir_name='.', save_name=None, store_directory=None, messages=True, suffix=''): """Download a file from a url and save it to disk.""" if sys.version_info>=(3,0): from urllib.parse import quote from urllib.request import urlopen from urllib.error import HTTPError, URLError else: from urllib2 import quote from urllib2 import urlopen from urllib2 import URLError as HTTPError i = url.rfind('/') file = url[i+1:] if store_directory is not None: dir_name = os.path.join(dir_name, store_directory) if save_name is None: save_name = file save_name = os.path.join(dir_name, save_name) print("Downloading ", url, "->", save_name) if not os.path.exists(dir_name): os.makedirs(dir_name) try: response = urlopen(url+suffix) except HTTPError as e: if not hasattr(e, "code"): raise if e.code > 399 and e.code<500: raise ValueError('Tried url ' + url + suffix + ' and received client error ' + str(e.code)) elif e.code > 499: raise ValueError('Tried url ' + url + suffix + ' and received server error ' + str(e.code)) except URLError as e: raise ValueError('Tried url ' + url + suffix + ' and failed with error ' + str(e.reason)) with open(save_name, 'wb') as f: meta = response.info() content_length_str = meta.get("Content-Length") if content_length_str: #if sys.version_info>=(3,0): try: file_size = int(content_length_str) except: try: file_size = int(content_length_str[0]) except: file_size = None if file_size == 1: file_size = None #else: # file_size = int(content_length_str) else: file_size = None status = "" file_size_dl = 0 block_sz = 8192 line_length = 30 percentage = 1./line_length if file_size: print("|"+"{:^{ll}}".format("Downloading {:7.3f}MB".format(file_size/(1048576.)), ll=line_length)+"|") from itertools import cycle cycle_str = cycle('>') sys.stdout.write("|") while True: buff = response.read(block_sz) if not buff: break file_size_dl += len(buff) f.write(buff) # If content_length_str was incorrect, we can end up with many too many equals signs, catches this edge case #correct_meta = float(file_size_dl)/file_size <= 1.0 if file_size: if (float(file_size_dl)/file_size) >= percentage: sys.stdout.write(next(cycle_str)) sys.stdout.flush() percentage += 1./line_length #percentage = "="*int(line_length*float(file_size_dl)/file_size) #status = r"[{perc: <{ll}}] {dl:7.3f}/{full:.3f}MB".format(dl=file_size_dl/(1048576.), full=file_size/(1048576.), ll=line_length, perc=percentage) else: sys.stdout.write(" "*(len(status)) + "\r") status = r"{dl:7.3f}MB".format(dl=file_size_dl/(1048576.), ll=line_length, perc="."*int(line_length*float(file_size_dl/(10*1048576.)))) sys.stdout.write(status) sys.stdout.flush() #sys.stdout.write(status) if file_size: sys.stdout.write("|") sys.stdout.flush() print(status)
[ "def", "download_url", "(", "url", ",", "dir_name", "=", "'.'", ",", "save_name", "=", "None", ",", "store_directory", "=", "None", ",", "messages", "=", "True", ",", "suffix", "=", "''", ")", ":", "if", "sys", ".", "version_info", ">=", "(", "3", ",", "0", ")", ":", "from", "urllib", ".", "parse", "import", "quote", "from", "urllib", ".", "request", "import", "urlopen", "from", "urllib", ".", "error", "import", "HTTPError", ",", "URLError", "else", ":", "from", "urllib2", "import", "quote", "from", "urllib2", "import", "urlopen", "from", "urllib2", "import", "URLError", "as", "HTTPError", "i", "=", "url", ".", "rfind", "(", "'/'", ")", "file", "=", "url", "[", "i", "+", "1", ":", "]", "if", "store_directory", "is", "not", "None", ":", "dir_name", "=", "os", ".", "path", ".", "join", "(", "dir_name", ",", "store_directory", ")", "if", "save_name", "is", "None", ":", "save_name", "=", "file", "save_name", "=", "os", ".", "path", ".", "join", "(", "dir_name", ",", "save_name", ")", "print", "(", "\"Downloading \"", ",", "url", ",", "\"->\"", ",", "save_name", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "dir_name", ")", ":", "os", ".", "makedirs", "(", "dir_name", ")", "try", ":", "response", "=", "urlopen", "(", "url", "+", "suffix", ")", "except", "HTTPError", "as", "e", ":", "if", "not", "hasattr", "(", "e", ",", "\"code\"", ")", ":", "raise", "if", "e", ".", "code", ">", "399", "and", "e", ".", "code", "<", "500", ":", "raise", "ValueError", "(", "'Tried url '", "+", "url", "+", "suffix", "+", "' and received client error '", "+", "str", "(", "e", ".", "code", ")", ")", "elif", "e", ".", "code", ">", "499", ":", "raise", "ValueError", "(", "'Tried url '", "+", "url", "+", "suffix", "+", "' and received server error '", "+", "str", "(", "e", ".", "code", ")", ")", "except", "URLError", "as", "e", ":", "raise", "ValueError", "(", "'Tried url '", "+", "url", "+", "suffix", "+", "' and failed with error '", "+", "str", "(", "e", ".", "reason", ")", ")", "with", "open", "(", "save_name", ",", "'wb'", ")", "as", "f", ":", "meta", "=", "response", ".", "info", "(", ")", "content_length_str", "=", "meta", ".", "get", "(", "\"Content-Length\"", ")", "if", "content_length_str", ":", "#if sys.version_info>=(3,0):", "try", ":", "file_size", "=", "int", "(", "content_length_str", ")", "except", ":", "try", ":", "file_size", "=", "int", "(", "content_length_str", "[", "0", "]", ")", "except", ":", "file_size", "=", "None", "if", "file_size", "==", "1", ":", "file_size", "=", "None", "#else:", "# file_size = int(content_length_str)", "else", ":", "file_size", "=", "None", "status", "=", "\"\"", "file_size_dl", "=", "0", "block_sz", "=", "8192", "line_length", "=", "30", "percentage", "=", "1.", "/", "line_length", "if", "file_size", ":", "print", "(", "\"|\"", "+", "\"{:^{ll}}\"", ".", "format", "(", "\"Downloading {:7.3f}MB\"", ".", "format", "(", "file_size", "/", "(", "1048576.", ")", ")", ",", "ll", "=", "line_length", ")", "+", "\"|\"", ")", "from", "itertools", "import", "cycle", "cycle_str", "=", "cycle", "(", "'>'", ")", "sys", ".", "stdout", ".", "write", "(", "\"|\"", ")", "while", "True", ":", "buff", "=", "response", ".", "read", "(", "block_sz", ")", "if", "not", "buff", ":", "break", "file_size_dl", "+=", "len", "(", "buff", ")", "f", ".", "write", "(", "buff", ")", "# If content_length_str was incorrect, we can end up with many too many equals signs, catches this edge case", "#correct_meta = float(file_size_dl)/file_size <= 1.0", "if", "file_size", ":", "if", "(", "float", "(", "file_size_dl", ")", "/", "file_size", ")", ">=", "percentage", ":", "sys", ".", "stdout", ".", "write", "(", "next", "(", "cycle_str", ")", ")", "sys", ".", "stdout", ".", "flush", "(", ")", "percentage", "+=", "1.", "/", "line_length", "#percentage = \"=\"*int(line_length*float(file_size_dl)/file_size)", "#status = r\"[{perc: <{ll}}] {dl:7.3f}/{full:.3f}MB\".format(dl=file_size_dl/(1048576.), full=file_size/(1048576.), ll=line_length, perc=percentage)", "else", ":", "sys", ".", "stdout", ".", "write", "(", "\" \"", "*", "(", "len", "(", "status", ")", ")", "+", "\"\\r\"", ")", "status", "=", "r\"{dl:7.3f}MB\"", ".", "format", "(", "dl", "=", "file_size_dl", "/", "(", "1048576.", ")", ",", "ll", "=", "line_length", ",", "perc", "=", "\".\"", "*", "int", "(", "line_length", "*", "float", "(", "file_size_dl", "/", "(", "10", "*", "1048576.", ")", ")", ")", ")", "sys", ".", "stdout", ".", "write", "(", "status", ")", "sys", ".", "stdout", ".", "flush", "(", ")", "#sys.stdout.write(status)", "if", "file_size", ":", "sys", ".", "stdout", ".", "write", "(", "\"|\"", ")", "sys", ".", "stdout", ".", "flush", "(", ")", "print", "(", "status", ")" ]
Download a file from a url and save it to disk.
[ "Download", "a", "file", "from", "a", "url", "and", "save", "it", "to", "disk", "." ]
3995c659f25a0a640f6009ed7fcc2559ce659b1d
https://github.com/sods/ods/blob/3995c659f25a0a640f6009ed7fcc2559ce659b1d/pods/util.py#L9-L102
train
CloudGenix/sdk-python
cloudgenix/get_api.py
Get.access_elementusers
def access_elementusers(self, elementuser_id, access_id=None, tenant_id=None, api_version="v2.0"): """ Get all accesses for a particular user **Parameters:**: - **elementuser_id**: Element User ID - **access_id**: (optional) Access ID - **tenant_id**: Tenant ID - **api_version**: API version to use (default v2.0) **Returns:** requests.Response object extended with cgx_status and cgx_content properties. """ if tenant_id is None and self._parent_class.tenant_id: # Pull tenant_id from parent namespace cache. tenant_id = self._parent_class.tenant_id elif not tenant_id: # No value for tenant_id. raise TypeError("tenant_id is required but not set or cached.") cur_ctlr = self._parent_class.controller if not access_id: url = str(cur_ctlr) + "/{}/api/tenants/{}/elementusers/{}/access".format(api_version, tenant_id, elementuser_id) else: url = str(cur_ctlr) + "/{}/api/tenants/{}/elementusers/{}/access/{}".format(api_version, tenant_id, elementuser_id, access_id) api_logger.debug("URL = %s", url) return self._parent_class.rest_call(url, "get")
python
def access_elementusers(self, elementuser_id, access_id=None, tenant_id=None, api_version="v2.0"): """ Get all accesses for a particular user **Parameters:**: - **elementuser_id**: Element User ID - **access_id**: (optional) Access ID - **tenant_id**: Tenant ID - **api_version**: API version to use (default v2.0) **Returns:** requests.Response object extended with cgx_status and cgx_content properties. """ if tenant_id is None and self._parent_class.tenant_id: # Pull tenant_id from parent namespace cache. tenant_id = self._parent_class.tenant_id elif not tenant_id: # No value for tenant_id. raise TypeError("tenant_id is required but not set or cached.") cur_ctlr = self._parent_class.controller if not access_id: url = str(cur_ctlr) + "/{}/api/tenants/{}/elementusers/{}/access".format(api_version, tenant_id, elementuser_id) else: url = str(cur_ctlr) + "/{}/api/tenants/{}/elementusers/{}/access/{}".format(api_version, tenant_id, elementuser_id, access_id) api_logger.debug("URL = %s", url) return self._parent_class.rest_call(url, "get")
[ "def", "access_elementusers", "(", "self", ",", "elementuser_id", ",", "access_id", "=", "None", ",", "tenant_id", "=", "None", ",", "api_version", "=", "\"v2.0\"", ")", ":", "if", "tenant_id", "is", "None", "and", "self", ".", "_parent_class", ".", "tenant_id", ":", "# Pull tenant_id from parent namespace cache.", "tenant_id", "=", "self", ".", "_parent_class", ".", "tenant_id", "elif", "not", "tenant_id", ":", "# No value for tenant_id.", "raise", "TypeError", "(", "\"tenant_id is required but not set or cached.\"", ")", "cur_ctlr", "=", "self", ".", "_parent_class", ".", "controller", "if", "not", "access_id", ":", "url", "=", "str", "(", "cur_ctlr", ")", "+", "\"/{}/api/tenants/{}/elementusers/{}/access\"", ".", "format", "(", "api_version", ",", "tenant_id", ",", "elementuser_id", ")", "else", ":", "url", "=", "str", "(", "cur_ctlr", ")", "+", "\"/{}/api/tenants/{}/elementusers/{}/access/{}\"", ".", "format", "(", "api_version", ",", "tenant_id", ",", "elementuser_id", ",", "access_id", ")", "api_logger", ".", "debug", "(", "\"URL = %s\"", ",", "url", ")", "return", "self", ".", "_parent_class", ".", "rest_call", "(", "url", ",", "\"get\"", ")" ]
Get all accesses for a particular user **Parameters:**: - **elementuser_id**: Element User ID - **access_id**: (optional) Access ID - **tenant_id**: Tenant ID - **api_version**: API version to use (default v2.0) **Returns:** requests.Response object extended with cgx_status and cgx_content properties.
[ "Get", "all", "accesses", "for", "a", "particular", "user" ]
1b2f92582b6a19769134914793bfd00e4caa074b
https://github.com/CloudGenix/sdk-python/blob/1b2f92582b6a19769134914793bfd00e4caa074b/cloudgenix/get_api.py#L55-L88
train
CloudGenix/sdk-python
cloudgenix/get_api.py
Get.logout
def logout(self, api_version="v2.0"): """ Logout current session **Parameters:**: - **api_version**: API version to use (default v2.0) **Returns:** requests.Response object extended with cgx_status and cgx_content properties. """ cur_ctlr = self._parent_class.controller url = str(cur_ctlr) + "/{}/api/logout".format(api_version) api_logger.debug("URL = %s", url) return self._parent_class.rest_call(url, "get")
python
def logout(self, api_version="v2.0"): """ Logout current session **Parameters:**: - **api_version**: API version to use (default v2.0) **Returns:** requests.Response object extended with cgx_status and cgx_content properties. """ cur_ctlr = self._parent_class.controller url = str(cur_ctlr) + "/{}/api/logout".format(api_version) api_logger.debug("URL = %s", url) return self._parent_class.rest_call(url, "get")
[ "def", "logout", "(", "self", ",", "api_version", "=", "\"v2.0\"", ")", ":", "cur_ctlr", "=", "self", ".", "_parent_class", ".", "controller", "url", "=", "str", "(", "cur_ctlr", ")", "+", "\"/{}/api/logout\"", ".", "format", "(", "api_version", ")", "api_logger", ".", "debug", "(", "\"URL = %s\"", ",", "url", ")", "return", "self", ".", "_parent_class", ".", "rest_call", "(", "url", ",", "\"get\"", ")" ]
Logout current session **Parameters:**: - **api_version**: API version to use (default v2.0) **Returns:** requests.Response object extended with cgx_status and cgx_content properties.
[ "Logout", "current", "session" ]
1b2f92582b6a19769134914793bfd00e4caa074b
https://github.com/CloudGenix/sdk-python/blob/1b2f92582b6a19769134914793bfd00e4caa074b/cloudgenix/get_api.py#L1459-L1475
train
CloudGenix/sdk-python
cloudgenix/interactive.py
Interactive.login
def login(self, email=None, password=None): """ Interactive login using the `cloudgenix.API` object. This function is more robust and handles SAML and MSP accounts. Expects interactive capability. if this is not available, use `cloudenix.API.post.login` directly. **Parameters:**: - **email**: Email to log in for, will prompt if not entered. - **password**: Password to log in with, will prompt if not entered. Ignored for SAML v2.0 users. **Returns:** Bool. In addition the function will mutate the `cloudgenix.API` constructor items as needed. """ # if email not given in function, or if first login fails, prompt. if email is None: # If user is not set, pull from cache. If not in cache, prompt. if self._parent_class.email: email = self._parent_class.email else: email = compat_input("login: ") if password is None: # if pass not given on function, or if first login fails, prompt. if self._parent_class._password: password = self._parent_class._password else: password = getpass.getpass() # Try and login # For SAML 2.0 support, set the Referer URL prior to logging in. # add referer header to the session. self._parent_class.add_headers({'Referer': "{}/v2.0/api/login".format(self._parent_class.controller)}) # call the login API. response = self._parent_class.post.login({"email": email, "password": password}) if response.cgx_status: # Check for SAML 2.0 login if not response.cgx_content.get('x_auth_token'): urlpath = response.cgx_content.get("urlpath", "") request_id = response.cgx_content.get("requestId", "") if urlpath and request_id: # SAML 2.0 print('SAML 2.0: To finish login open the following link in a browser\n\n{0}\n\n'.format(urlpath)) found_auth_token = False for i in range(20): print('Waiting for {0} seconds for authentication...'.format((20 - i) * 5)) saml_response = self.check_sso_login(email, request_id) if saml_response.cgx_status and saml_response.cgx_content.get('x_auth_token'): found_auth_token = True break # wait before retry. time.sleep(5) if not found_auth_token: print("Login time expired! Please re-login.\n") # log response when debug try: api_logger.debug("LOGIN_FAIL_RESPONSE = %s", json.dumps(response, indent=4)) except (TypeError, ValueError): # not JSON response, don't pretty print log. api_logger.debug("LOGIN_FAIL_RESPONSE = %s", str(response)) # print login error print('Login failed, please try again', response) # Flush command-line entered login info if failure. self._parent_class.email = None self._parent_class.password = None return False api_logger.info('Login successful:') # if we got here, we either got an x_auth_token in the original login, or # we got an auth_token cookie set via SAML. Figure out which. auth_token = response.cgx_content.get('x_auth_token') if auth_token: # token in the original login (not saml) means region parsing has not been done. # do now, and recheck if cookie needs set. auth_region = self._parent_class.parse_region(response) self._parent_class.update_region_to_controller(auth_region) self._parent_class.reparse_login_cookie_after_region_update(response) # debug info if needed api_logger.debug("AUTH_TOKEN=%s", response.cgx_content.get('x_auth_token')) # Step 2: Get operator profile for tenant ID and other info. if self.interactive_update_profile_vars(): # pull tenant detail if self._parent_class.tenant_id: # add tenant values to API() object if self.interactive_tenant_update_vars(): # Step 3: Check for ESP/MSP. If so, ask which tenant this session should be for. if self._parent_class.is_esp: # ESP/MSP! choose_status, chosen_client_id = self.interactive_client_choice() if choose_status: # attempt to login as client clogin_resp = self._parent_class.post.login_clients(chosen_client_id, {}) if clogin_resp.cgx_status: # login successful, update profile and tenant info c_profile = self.interactive_update_profile_vars() t_profile = self.interactive_tenant_update_vars() if c_profile and t_profile: # successful full client login. self._parent_class._password = None # remove referer header prior to continuing. self._parent_class.remove_header('Referer') return True else: if t_profile: print("ESP Client Tenant detail retrieval failed.") # clear password out of memory self._parent_class.email = None self._parent_class._password = None # remove referer header prior to continuing. self._parent_class.remove_header('Referer') return False else: print("ESP Client Login failed.") # clear password out of memory self._parent_class.email = None self._parent_class._password = None # remove referer header prior to continuing. self._parent_class.remove_header('Referer') return False else: print("ESP Client Choice failed.") # clear password out of memory self._parent_class.email = None self._parent_class._password = None # remove referer header prior to continuing. self._parent_class.remove_header('Referer') return False # successful! # clear password out of memory self._parent_class._password = None # remove referer header prior to continuing. self._parent_class.remove_header('Referer') return True else: print("Tenant detail retrieval failed.") # clear password out of memory self._parent_class.email = None self._parent_class._password = None # remove referer header prior to continuing. self._parent_class.remove_header('Referer') return False else: # Profile detail retrieval failed self._parent_class.email = None self._parent_class._password = None return False api_logger.info("EMAIL = %s", self._parent_class.email) api_logger.info("USER_ID = %s", self._parent_class._user_id) api_logger.info("USER ROLES = %s", json.dumps(self._parent_class.roles)) api_logger.info("TENANT_ID = %s", self._parent_class.tenant_id) api_logger.info("TENANT_NAME = %s", self._parent_class.tenant_name) api_logger.info("TOKEN_SESSION = %s", self._parent_class.token_session) # remove referer header prior to continuing. self._parent_class.remove_header('Referer') else: # log response when debug api_logger.debug("LOGIN_FAIL_RESPONSE = %s", json.dumps(response.cgx_content, indent=4)) # print login error print('Login failed, please try again:', response.cgx_content) # Flush command-line entered login info if failure. self._parent_class.email = None self._parent_class.password = None # remove referer header prior to continuing. self._parent_class.remove_header('Referer') return False
python
def login(self, email=None, password=None): """ Interactive login using the `cloudgenix.API` object. This function is more robust and handles SAML and MSP accounts. Expects interactive capability. if this is not available, use `cloudenix.API.post.login` directly. **Parameters:**: - **email**: Email to log in for, will prompt if not entered. - **password**: Password to log in with, will prompt if not entered. Ignored for SAML v2.0 users. **Returns:** Bool. In addition the function will mutate the `cloudgenix.API` constructor items as needed. """ # if email not given in function, or if first login fails, prompt. if email is None: # If user is not set, pull from cache. If not in cache, prompt. if self._parent_class.email: email = self._parent_class.email else: email = compat_input("login: ") if password is None: # if pass not given on function, or if first login fails, prompt. if self._parent_class._password: password = self._parent_class._password else: password = getpass.getpass() # Try and login # For SAML 2.0 support, set the Referer URL prior to logging in. # add referer header to the session. self._parent_class.add_headers({'Referer': "{}/v2.0/api/login".format(self._parent_class.controller)}) # call the login API. response = self._parent_class.post.login({"email": email, "password": password}) if response.cgx_status: # Check for SAML 2.0 login if not response.cgx_content.get('x_auth_token'): urlpath = response.cgx_content.get("urlpath", "") request_id = response.cgx_content.get("requestId", "") if urlpath and request_id: # SAML 2.0 print('SAML 2.0: To finish login open the following link in a browser\n\n{0}\n\n'.format(urlpath)) found_auth_token = False for i in range(20): print('Waiting for {0} seconds for authentication...'.format((20 - i) * 5)) saml_response = self.check_sso_login(email, request_id) if saml_response.cgx_status and saml_response.cgx_content.get('x_auth_token'): found_auth_token = True break # wait before retry. time.sleep(5) if not found_auth_token: print("Login time expired! Please re-login.\n") # log response when debug try: api_logger.debug("LOGIN_FAIL_RESPONSE = %s", json.dumps(response, indent=4)) except (TypeError, ValueError): # not JSON response, don't pretty print log. api_logger.debug("LOGIN_FAIL_RESPONSE = %s", str(response)) # print login error print('Login failed, please try again', response) # Flush command-line entered login info if failure. self._parent_class.email = None self._parent_class.password = None return False api_logger.info('Login successful:') # if we got here, we either got an x_auth_token in the original login, or # we got an auth_token cookie set via SAML. Figure out which. auth_token = response.cgx_content.get('x_auth_token') if auth_token: # token in the original login (not saml) means region parsing has not been done. # do now, and recheck if cookie needs set. auth_region = self._parent_class.parse_region(response) self._parent_class.update_region_to_controller(auth_region) self._parent_class.reparse_login_cookie_after_region_update(response) # debug info if needed api_logger.debug("AUTH_TOKEN=%s", response.cgx_content.get('x_auth_token')) # Step 2: Get operator profile for tenant ID and other info. if self.interactive_update_profile_vars(): # pull tenant detail if self._parent_class.tenant_id: # add tenant values to API() object if self.interactive_tenant_update_vars(): # Step 3: Check for ESP/MSP. If so, ask which tenant this session should be for. if self._parent_class.is_esp: # ESP/MSP! choose_status, chosen_client_id = self.interactive_client_choice() if choose_status: # attempt to login as client clogin_resp = self._parent_class.post.login_clients(chosen_client_id, {}) if clogin_resp.cgx_status: # login successful, update profile and tenant info c_profile = self.interactive_update_profile_vars() t_profile = self.interactive_tenant_update_vars() if c_profile and t_profile: # successful full client login. self._parent_class._password = None # remove referer header prior to continuing. self._parent_class.remove_header('Referer') return True else: if t_profile: print("ESP Client Tenant detail retrieval failed.") # clear password out of memory self._parent_class.email = None self._parent_class._password = None # remove referer header prior to continuing. self._parent_class.remove_header('Referer') return False else: print("ESP Client Login failed.") # clear password out of memory self._parent_class.email = None self._parent_class._password = None # remove referer header prior to continuing. self._parent_class.remove_header('Referer') return False else: print("ESP Client Choice failed.") # clear password out of memory self._parent_class.email = None self._parent_class._password = None # remove referer header prior to continuing. self._parent_class.remove_header('Referer') return False # successful! # clear password out of memory self._parent_class._password = None # remove referer header prior to continuing. self._parent_class.remove_header('Referer') return True else: print("Tenant detail retrieval failed.") # clear password out of memory self._parent_class.email = None self._parent_class._password = None # remove referer header prior to continuing. self._parent_class.remove_header('Referer') return False else: # Profile detail retrieval failed self._parent_class.email = None self._parent_class._password = None return False api_logger.info("EMAIL = %s", self._parent_class.email) api_logger.info("USER_ID = %s", self._parent_class._user_id) api_logger.info("USER ROLES = %s", json.dumps(self._parent_class.roles)) api_logger.info("TENANT_ID = %s", self._parent_class.tenant_id) api_logger.info("TENANT_NAME = %s", self._parent_class.tenant_name) api_logger.info("TOKEN_SESSION = %s", self._parent_class.token_session) # remove referer header prior to continuing. self._parent_class.remove_header('Referer') else: # log response when debug api_logger.debug("LOGIN_FAIL_RESPONSE = %s", json.dumps(response.cgx_content, indent=4)) # print login error print('Login failed, please try again:', response.cgx_content) # Flush command-line entered login info if failure. self._parent_class.email = None self._parent_class.password = None # remove referer header prior to continuing. self._parent_class.remove_header('Referer') return False
[ "def", "login", "(", "self", ",", "email", "=", "None", ",", "password", "=", "None", ")", ":", "# if email not given in function, or if first login fails, prompt.", "if", "email", "is", "None", ":", "# If user is not set, pull from cache. If not in cache, prompt.", "if", "self", ".", "_parent_class", ".", "email", ":", "email", "=", "self", ".", "_parent_class", ".", "email", "else", ":", "email", "=", "compat_input", "(", "\"login: \"", ")", "if", "password", "is", "None", ":", "# if pass not given on function, or if first login fails, prompt.", "if", "self", ".", "_parent_class", ".", "_password", ":", "password", "=", "self", ".", "_parent_class", ".", "_password", "else", ":", "password", "=", "getpass", ".", "getpass", "(", ")", "# Try and login", "# For SAML 2.0 support, set the Referer URL prior to logging in.", "# add referer header to the session.", "self", ".", "_parent_class", ".", "add_headers", "(", "{", "'Referer'", ":", "\"{}/v2.0/api/login\"", ".", "format", "(", "self", ".", "_parent_class", ".", "controller", ")", "}", ")", "# call the login API.", "response", "=", "self", ".", "_parent_class", ".", "post", ".", "login", "(", "{", "\"email\"", ":", "email", ",", "\"password\"", ":", "password", "}", ")", "if", "response", ".", "cgx_status", ":", "# Check for SAML 2.0 login", "if", "not", "response", ".", "cgx_content", ".", "get", "(", "'x_auth_token'", ")", ":", "urlpath", "=", "response", ".", "cgx_content", ".", "get", "(", "\"urlpath\"", ",", "\"\"", ")", "request_id", "=", "response", ".", "cgx_content", ".", "get", "(", "\"requestId\"", ",", "\"\"", ")", "if", "urlpath", "and", "request_id", ":", "# SAML 2.0", "print", "(", "'SAML 2.0: To finish login open the following link in a browser\\n\\n{0}\\n\\n'", ".", "format", "(", "urlpath", ")", ")", "found_auth_token", "=", "False", "for", "i", "in", "range", "(", "20", ")", ":", "print", "(", "'Waiting for {0} seconds for authentication...'", ".", "format", "(", "(", "20", "-", "i", ")", "*", "5", ")", ")", "saml_response", "=", "self", ".", "check_sso_login", "(", "email", ",", "request_id", ")", "if", "saml_response", ".", "cgx_status", "and", "saml_response", ".", "cgx_content", ".", "get", "(", "'x_auth_token'", ")", ":", "found_auth_token", "=", "True", "break", "# wait before retry.", "time", ".", "sleep", "(", "5", ")", "if", "not", "found_auth_token", ":", "print", "(", "\"Login time expired! Please re-login.\\n\"", ")", "# log response when debug", "try", ":", "api_logger", ".", "debug", "(", "\"LOGIN_FAIL_RESPONSE = %s\"", ",", "json", ".", "dumps", "(", "response", ",", "indent", "=", "4", ")", ")", "except", "(", "TypeError", ",", "ValueError", ")", ":", "# not JSON response, don't pretty print log.", "api_logger", ".", "debug", "(", "\"LOGIN_FAIL_RESPONSE = %s\"", ",", "str", "(", "response", ")", ")", "# print login error", "print", "(", "'Login failed, please try again'", ",", "response", ")", "# Flush command-line entered login info if failure.", "self", ".", "_parent_class", ".", "email", "=", "None", "self", ".", "_parent_class", ".", "password", "=", "None", "return", "False", "api_logger", ".", "info", "(", "'Login successful:'", ")", "# if we got here, we either got an x_auth_token in the original login, or", "# we got an auth_token cookie set via SAML. Figure out which.", "auth_token", "=", "response", ".", "cgx_content", ".", "get", "(", "'x_auth_token'", ")", "if", "auth_token", ":", "# token in the original login (not saml) means region parsing has not been done.", "# do now, and recheck if cookie needs set.", "auth_region", "=", "self", ".", "_parent_class", ".", "parse_region", "(", "response", ")", "self", ".", "_parent_class", ".", "update_region_to_controller", "(", "auth_region", ")", "self", ".", "_parent_class", ".", "reparse_login_cookie_after_region_update", "(", "response", ")", "# debug info if needed", "api_logger", ".", "debug", "(", "\"AUTH_TOKEN=%s\"", ",", "response", ".", "cgx_content", ".", "get", "(", "'x_auth_token'", ")", ")", "# Step 2: Get operator profile for tenant ID and other info.", "if", "self", ".", "interactive_update_profile_vars", "(", ")", ":", "# pull tenant detail", "if", "self", ".", "_parent_class", ".", "tenant_id", ":", "# add tenant values to API() object", "if", "self", ".", "interactive_tenant_update_vars", "(", ")", ":", "# Step 3: Check for ESP/MSP. If so, ask which tenant this session should be for.", "if", "self", ".", "_parent_class", ".", "is_esp", ":", "# ESP/MSP!", "choose_status", ",", "chosen_client_id", "=", "self", ".", "interactive_client_choice", "(", ")", "if", "choose_status", ":", "# attempt to login as client", "clogin_resp", "=", "self", ".", "_parent_class", ".", "post", ".", "login_clients", "(", "chosen_client_id", ",", "{", "}", ")", "if", "clogin_resp", ".", "cgx_status", ":", "# login successful, update profile and tenant info", "c_profile", "=", "self", ".", "interactive_update_profile_vars", "(", ")", "t_profile", "=", "self", ".", "interactive_tenant_update_vars", "(", ")", "if", "c_profile", "and", "t_profile", ":", "# successful full client login.", "self", ".", "_parent_class", ".", "_password", "=", "None", "# remove referer header prior to continuing.", "self", ".", "_parent_class", ".", "remove_header", "(", "'Referer'", ")", "return", "True", "else", ":", "if", "t_profile", ":", "print", "(", "\"ESP Client Tenant detail retrieval failed.\"", ")", "# clear password out of memory", "self", ".", "_parent_class", ".", "email", "=", "None", "self", ".", "_parent_class", ".", "_password", "=", "None", "# remove referer header prior to continuing.", "self", ".", "_parent_class", ".", "remove_header", "(", "'Referer'", ")", "return", "False", "else", ":", "print", "(", "\"ESP Client Login failed.\"", ")", "# clear password out of memory", "self", ".", "_parent_class", ".", "email", "=", "None", "self", ".", "_parent_class", ".", "_password", "=", "None", "# remove referer header prior to continuing.", "self", ".", "_parent_class", ".", "remove_header", "(", "'Referer'", ")", "return", "False", "else", ":", "print", "(", "\"ESP Client Choice failed.\"", ")", "# clear password out of memory", "self", ".", "_parent_class", ".", "email", "=", "None", "self", ".", "_parent_class", ".", "_password", "=", "None", "# remove referer header prior to continuing.", "self", ".", "_parent_class", ".", "remove_header", "(", "'Referer'", ")", "return", "False", "# successful!", "# clear password out of memory", "self", ".", "_parent_class", ".", "_password", "=", "None", "# remove referer header prior to continuing.", "self", ".", "_parent_class", ".", "remove_header", "(", "'Referer'", ")", "return", "True", "else", ":", "print", "(", "\"Tenant detail retrieval failed.\"", ")", "# clear password out of memory", "self", ".", "_parent_class", ".", "email", "=", "None", "self", ".", "_parent_class", ".", "_password", "=", "None", "# remove referer header prior to continuing.", "self", ".", "_parent_class", ".", "remove_header", "(", "'Referer'", ")", "return", "False", "else", ":", "# Profile detail retrieval failed", "self", ".", "_parent_class", ".", "email", "=", "None", "self", ".", "_parent_class", ".", "_password", "=", "None", "return", "False", "api_logger", ".", "info", "(", "\"EMAIL = %s\"", ",", "self", ".", "_parent_class", ".", "email", ")", "api_logger", ".", "info", "(", "\"USER_ID = %s\"", ",", "self", ".", "_parent_class", ".", "_user_id", ")", "api_logger", ".", "info", "(", "\"USER ROLES = %s\"", ",", "json", ".", "dumps", "(", "self", ".", "_parent_class", ".", "roles", ")", ")", "api_logger", ".", "info", "(", "\"TENANT_ID = %s\"", ",", "self", ".", "_parent_class", ".", "tenant_id", ")", "api_logger", ".", "info", "(", "\"TENANT_NAME = %s\"", ",", "self", ".", "_parent_class", ".", "tenant_name", ")", "api_logger", ".", "info", "(", "\"TOKEN_SESSION = %s\"", ",", "self", ".", "_parent_class", ".", "token_session", ")", "# remove referer header prior to continuing.", "self", ".", "_parent_class", ".", "remove_header", "(", "'Referer'", ")", "else", ":", "# log response when debug", "api_logger", ".", "debug", "(", "\"LOGIN_FAIL_RESPONSE = %s\"", ",", "json", ".", "dumps", "(", "response", ".", "cgx_content", ",", "indent", "=", "4", ")", ")", "# print login error", "print", "(", "'Login failed, please try again:'", ",", "response", ".", "cgx_content", ")", "# Flush command-line entered login info if failure.", "self", ".", "_parent_class", ".", "email", "=", "None", "self", ".", "_parent_class", ".", "password", "=", "None", "# remove referer header prior to continuing.", "self", ".", "_parent_class", ".", "remove_header", "(", "'Referer'", ")", "return", "False" ]
Interactive login using the `cloudgenix.API` object. This function is more robust and handles SAML and MSP accounts. Expects interactive capability. if this is not available, use `cloudenix.API.post.login` directly. **Parameters:**: - **email**: Email to log in for, will prompt if not entered. - **password**: Password to log in with, will prompt if not entered. Ignored for SAML v2.0 users. **Returns:** Bool. In addition the function will mutate the `cloudgenix.API` constructor items as needed.
[ "Interactive", "login", "using", "the", "cloudgenix", ".", "API", "object", ".", "This", "function", "is", "more", "robust", "and", "handles", "SAML", "and", "MSP", "accounts", ".", "Expects", "interactive", "capability", ".", "if", "this", "is", "not", "available", "use", "cloudenix", ".", "API", ".", "post", ".", "login", "directly", "." ]
1b2f92582b6a19769134914793bfd00e4caa074b
https://github.com/CloudGenix/sdk-python/blob/1b2f92582b6a19769134914793bfd00e4caa074b/cloudgenix/interactive.py#L72-L254
train
CloudGenix/sdk-python
cloudgenix/interactive.py
Interactive.use_token
def use_token(self, token=None): """ Function to use static AUTH_TOKEN as auth for the constructor instead of full login process. **Parameters:**: - **token**: Static AUTH_TOKEN **Returns:** Bool on success or failure. In addition the function will mutate the `cloudgenix.API` constructor items as needed. """ api_logger.info('use_token function:') # check token is a string. if not isinstance(token, (text_type, binary_type)): api_logger.debug('"token" was not a text-style string: {}'.format(text_type(token))) return False # Start setup of constructor. session = self._parent_class.expose_session() # clear cookies session.cookies.clear() # Static Token uses X-Auth-Token header instead of cookies. self._parent_class.add_headers({ 'X-Auth-Token': token }) # Step 2: Get operator profile for tenant ID and other info. if self.interactive_update_profile_vars(): # pull tenant detail if self._parent_class.tenant_id: # add tenant values to API() object if self.interactive_tenant_update_vars(): # Step 3: Check for ESP/MSP. If so, ask which tenant this session should be for. if self._parent_class.is_esp: # ESP/MSP! choose_status, chosen_client_id = self.interactive_client_choice() if choose_status: # attempt to login as client clogin_resp = self._parent_class.post.login_clients(chosen_client_id, {}) if clogin_resp.cgx_status: # login successful, update profile and tenant info c_profile = self.interactive_update_profile_vars() t_profile = self.interactive_tenant_update_vars() if c_profile and t_profile: # successful full client login. self._parent_class._password = None return True else: if t_profile: print("ESP Client Tenant detail retrieval failed.") # clear password out of memory self._parent_class.email = None self._parent_class._password = None return False else: print("ESP Client Login failed.") # clear password out of memory self._parent_class.email = None self._parent_class._password = None return False else: print("ESP Client Choice failed.") # clear password out of memory self._parent_class.email = None self._parent_class._password = None return False # successful! # clear password out of memory self._parent_class._password = None return True else: print("Tenant detail retrieval failed.") # clear password out of memory self._parent_class.email = None self._parent_class._password = None return False else: # Profile detail retrieval failed self._parent_class.email = None self._parent_class._password = None return False api_logger.info("EMAIL = %s", self._parent_class.email) api_logger.info("USER_ID = %s", self._parent_class._user_id) api_logger.info("USER ROLES = %s", json.dumps(self._parent_class.roles)) api_logger.info("TENANT_ID = %s", self._parent_class.tenant_id) api_logger.info("TENANT_NAME = %s", self._parent_class.tenant_name) api_logger.info("TOKEN_SESSION = %s", self._parent_class.token_session) return True
python
def use_token(self, token=None): """ Function to use static AUTH_TOKEN as auth for the constructor instead of full login process. **Parameters:**: - **token**: Static AUTH_TOKEN **Returns:** Bool on success or failure. In addition the function will mutate the `cloudgenix.API` constructor items as needed. """ api_logger.info('use_token function:') # check token is a string. if not isinstance(token, (text_type, binary_type)): api_logger.debug('"token" was not a text-style string: {}'.format(text_type(token))) return False # Start setup of constructor. session = self._parent_class.expose_session() # clear cookies session.cookies.clear() # Static Token uses X-Auth-Token header instead of cookies. self._parent_class.add_headers({ 'X-Auth-Token': token }) # Step 2: Get operator profile for tenant ID and other info. if self.interactive_update_profile_vars(): # pull tenant detail if self._parent_class.tenant_id: # add tenant values to API() object if self.interactive_tenant_update_vars(): # Step 3: Check for ESP/MSP. If so, ask which tenant this session should be for. if self._parent_class.is_esp: # ESP/MSP! choose_status, chosen_client_id = self.interactive_client_choice() if choose_status: # attempt to login as client clogin_resp = self._parent_class.post.login_clients(chosen_client_id, {}) if clogin_resp.cgx_status: # login successful, update profile and tenant info c_profile = self.interactive_update_profile_vars() t_profile = self.interactive_tenant_update_vars() if c_profile and t_profile: # successful full client login. self._parent_class._password = None return True else: if t_profile: print("ESP Client Tenant detail retrieval failed.") # clear password out of memory self._parent_class.email = None self._parent_class._password = None return False else: print("ESP Client Login failed.") # clear password out of memory self._parent_class.email = None self._parent_class._password = None return False else: print("ESP Client Choice failed.") # clear password out of memory self._parent_class.email = None self._parent_class._password = None return False # successful! # clear password out of memory self._parent_class._password = None return True else: print("Tenant detail retrieval failed.") # clear password out of memory self._parent_class.email = None self._parent_class._password = None return False else: # Profile detail retrieval failed self._parent_class.email = None self._parent_class._password = None return False api_logger.info("EMAIL = %s", self._parent_class.email) api_logger.info("USER_ID = %s", self._parent_class._user_id) api_logger.info("USER ROLES = %s", json.dumps(self._parent_class.roles)) api_logger.info("TENANT_ID = %s", self._parent_class.tenant_id) api_logger.info("TENANT_NAME = %s", self._parent_class.tenant_name) api_logger.info("TOKEN_SESSION = %s", self._parent_class.token_session) return True
[ "def", "use_token", "(", "self", ",", "token", "=", "None", ")", ":", "api_logger", ".", "info", "(", "'use_token function:'", ")", "# check token is a string.", "if", "not", "isinstance", "(", "token", ",", "(", "text_type", ",", "binary_type", ")", ")", ":", "api_logger", ".", "debug", "(", "'\"token\" was not a text-style string: {}'", ".", "format", "(", "text_type", "(", "token", ")", ")", ")", "return", "False", "# Start setup of constructor.", "session", "=", "self", ".", "_parent_class", ".", "expose_session", "(", ")", "# clear cookies", "session", ".", "cookies", ".", "clear", "(", ")", "# Static Token uses X-Auth-Token header instead of cookies.", "self", ".", "_parent_class", ".", "add_headers", "(", "{", "'X-Auth-Token'", ":", "token", "}", ")", "# Step 2: Get operator profile for tenant ID and other info.", "if", "self", ".", "interactive_update_profile_vars", "(", ")", ":", "# pull tenant detail", "if", "self", ".", "_parent_class", ".", "tenant_id", ":", "# add tenant values to API() object", "if", "self", ".", "interactive_tenant_update_vars", "(", ")", ":", "# Step 3: Check for ESP/MSP. If so, ask which tenant this session should be for.", "if", "self", ".", "_parent_class", ".", "is_esp", ":", "# ESP/MSP!", "choose_status", ",", "chosen_client_id", "=", "self", ".", "interactive_client_choice", "(", ")", "if", "choose_status", ":", "# attempt to login as client", "clogin_resp", "=", "self", ".", "_parent_class", ".", "post", ".", "login_clients", "(", "chosen_client_id", ",", "{", "}", ")", "if", "clogin_resp", ".", "cgx_status", ":", "# login successful, update profile and tenant info", "c_profile", "=", "self", ".", "interactive_update_profile_vars", "(", ")", "t_profile", "=", "self", ".", "interactive_tenant_update_vars", "(", ")", "if", "c_profile", "and", "t_profile", ":", "# successful full client login.", "self", ".", "_parent_class", ".", "_password", "=", "None", "return", "True", "else", ":", "if", "t_profile", ":", "print", "(", "\"ESP Client Tenant detail retrieval failed.\"", ")", "# clear password out of memory", "self", ".", "_parent_class", ".", "email", "=", "None", "self", ".", "_parent_class", ".", "_password", "=", "None", "return", "False", "else", ":", "print", "(", "\"ESP Client Login failed.\"", ")", "# clear password out of memory", "self", ".", "_parent_class", ".", "email", "=", "None", "self", ".", "_parent_class", ".", "_password", "=", "None", "return", "False", "else", ":", "print", "(", "\"ESP Client Choice failed.\"", ")", "# clear password out of memory", "self", ".", "_parent_class", ".", "email", "=", "None", "self", ".", "_parent_class", ".", "_password", "=", "None", "return", "False", "# successful!", "# clear password out of memory", "self", ".", "_parent_class", ".", "_password", "=", "None", "return", "True", "else", ":", "print", "(", "\"Tenant detail retrieval failed.\"", ")", "# clear password out of memory", "self", ".", "_parent_class", ".", "email", "=", "None", "self", ".", "_parent_class", ".", "_password", "=", "None", "return", "False", "else", ":", "# Profile detail retrieval failed", "self", ".", "_parent_class", ".", "email", "=", "None", "self", ".", "_parent_class", ".", "_password", "=", "None", "return", "False", "api_logger", ".", "info", "(", "\"EMAIL = %s\"", ",", "self", ".", "_parent_class", ".", "email", ")", "api_logger", ".", "info", "(", "\"USER_ID = %s\"", ",", "self", ".", "_parent_class", ".", "_user_id", ")", "api_logger", ".", "info", "(", "\"USER ROLES = %s\"", ",", "json", ".", "dumps", "(", "self", ".", "_parent_class", ".", "roles", ")", ")", "api_logger", ".", "info", "(", "\"TENANT_ID = %s\"", ",", "self", ".", "_parent_class", ".", "tenant_id", ")", "api_logger", ".", "info", "(", "\"TENANT_NAME = %s\"", ",", "self", ".", "_parent_class", ".", "tenant_name", ")", "api_logger", ".", "info", "(", "\"TOKEN_SESSION = %s\"", ",", "self", ".", "_parent_class", ".", "token_session", ")", "return", "True" ]
Function to use static AUTH_TOKEN as auth for the constructor instead of full login process. **Parameters:**: - **token**: Static AUTH_TOKEN **Returns:** Bool on success or failure. In addition the function will mutate the `cloudgenix.API` constructor items as needed.
[ "Function", "to", "use", "static", "AUTH_TOKEN", "as", "auth", "for", "the", "constructor", "instead", "of", "full", "login", "process", "." ]
1b2f92582b6a19769134914793bfd00e4caa074b
https://github.com/CloudGenix/sdk-python/blob/1b2f92582b6a19769134914793bfd00e4caa074b/cloudgenix/interactive.py#L256-L360
train
CloudGenix/sdk-python
cloudgenix/interactive.py
Interactive.interactive_tenant_update_vars
def interactive_tenant_update_vars(self): """ Function to update the `cloudgenix.API` object with tenant login info. Run after login or client login. **Returns:** Boolean on success/failure, """ api_logger.info('interactive_tenant_update_vars function:') tenant_resp = self._parent_class.get.tenants(self._parent_class.tenant_id) status = tenant_resp.cgx_status tenant_dict = tenant_resp.cgx_content if status: api_logger.debug("new tenant_dict: %s", tenant_dict) # Get Tenant info. self._parent_class.tenant_name = tenant_dict.get('name', self._parent_class.tenant_id) # is ESP/MSP? self._parent_class.is_esp = tenant_dict.get('is_esp') # grab tenant address for location. address_lookup = tenant_dict.get('address', None) if address_lookup: tenant_address = address_lookup.get('street', "") + ", " tenant_address += (str(address_lookup.get('street2', "")) + ", ") tenant_address += (str(address_lookup.get('city', "")) + ", ") tenant_address += (str(address_lookup.get('state', "")) + ", ") tenant_address += (str(address_lookup.get('post_code', "")) + ", ") tenant_address += (str(address_lookup.get('country', "")) + ", ") else: tenant_address = "Unknown" self._parent_class.address = tenant_address return True else: # update failed return False
python
def interactive_tenant_update_vars(self): """ Function to update the `cloudgenix.API` object with tenant login info. Run after login or client login. **Returns:** Boolean on success/failure, """ api_logger.info('interactive_tenant_update_vars function:') tenant_resp = self._parent_class.get.tenants(self._parent_class.tenant_id) status = tenant_resp.cgx_status tenant_dict = tenant_resp.cgx_content if status: api_logger.debug("new tenant_dict: %s", tenant_dict) # Get Tenant info. self._parent_class.tenant_name = tenant_dict.get('name', self._parent_class.tenant_id) # is ESP/MSP? self._parent_class.is_esp = tenant_dict.get('is_esp') # grab tenant address for location. address_lookup = tenant_dict.get('address', None) if address_lookup: tenant_address = address_lookup.get('street', "") + ", " tenant_address += (str(address_lookup.get('street2', "")) + ", ") tenant_address += (str(address_lookup.get('city', "")) + ", ") tenant_address += (str(address_lookup.get('state', "")) + ", ") tenant_address += (str(address_lookup.get('post_code', "")) + ", ") tenant_address += (str(address_lookup.get('country', "")) + ", ") else: tenant_address = "Unknown" self._parent_class.address = tenant_address return True else: # update failed return False
[ "def", "interactive_tenant_update_vars", "(", "self", ")", ":", "api_logger", ".", "info", "(", "'interactive_tenant_update_vars function:'", ")", "tenant_resp", "=", "self", ".", "_parent_class", ".", "get", ".", "tenants", "(", "self", ".", "_parent_class", ".", "tenant_id", ")", "status", "=", "tenant_resp", ".", "cgx_status", "tenant_dict", "=", "tenant_resp", ".", "cgx_content", "if", "status", ":", "api_logger", ".", "debug", "(", "\"new tenant_dict: %s\"", ",", "tenant_dict", ")", "# Get Tenant info.", "self", ".", "_parent_class", ".", "tenant_name", "=", "tenant_dict", ".", "get", "(", "'name'", ",", "self", ".", "_parent_class", ".", "tenant_id", ")", "# is ESP/MSP?", "self", ".", "_parent_class", ".", "is_esp", "=", "tenant_dict", ".", "get", "(", "'is_esp'", ")", "# grab tenant address for location.", "address_lookup", "=", "tenant_dict", ".", "get", "(", "'address'", ",", "None", ")", "if", "address_lookup", ":", "tenant_address", "=", "address_lookup", ".", "get", "(", "'street'", ",", "\"\"", ")", "+", "\", \"", "tenant_address", "+=", "(", "str", "(", "address_lookup", ".", "get", "(", "'street2'", ",", "\"\"", ")", ")", "+", "\", \"", ")", "tenant_address", "+=", "(", "str", "(", "address_lookup", ".", "get", "(", "'city'", ",", "\"\"", ")", ")", "+", "\", \"", ")", "tenant_address", "+=", "(", "str", "(", "address_lookup", ".", "get", "(", "'state'", ",", "\"\"", ")", ")", "+", "\", \"", ")", "tenant_address", "+=", "(", "str", "(", "address_lookup", ".", "get", "(", "'post_code'", ",", "\"\"", ")", ")", "+", "\", \"", ")", "tenant_address", "+=", "(", "str", "(", "address_lookup", ".", "get", "(", "'country'", ",", "\"\"", ")", ")", "+", "\", \"", ")", "else", ":", "tenant_address", "=", "\"Unknown\"", "self", ".", "_parent_class", ".", "address", "=", "tenant_address", "return", "True", "else", ":", "# update failed", "return", "False" ]
Function to update the `cloudgenix.API` object with tenant login info. Run after login or client login. **Returns:** Boolean on success/failure,
[ "Function", "to", "update", "the", "cloudgenix", ".", "API", "object", "with", "tenant", "login", "info", ".", "Run", "after", "login", "or", "client", "login", "." ]
1b2f92582b6a19769134914793bfd00e4caa074b
https://github.com/CloudGenix/sdk-python/blob/1b2f92582b6a19769134914793bfd00e4caa074b/cloudgenix/interactive.py#L362-L396
train
CloudGenix/sdk-python
cloudgenix/interactive.py
Interactive.interactive_update_profile_vars
def interactive_update_profile_vars(self): """ Function to update the `cloudgenix.API` object with profile info. Run after login or client login. **Returns:** Boolean on success/failure, """ profile = self._parent_class.get.profile() if profile.cgx_status: # if successful, save tenant id and email info to cli state. self._parent_class.tenant_id = profile.cgx_content.get('tenant_id') self._parent_class.email = profile.cgx_content.get('email') self._parent_class._user_id = profile.cgx_content.get('id') self._parent_class.roles = profile.cgx_content.get('roles', []) self._parent_class.token_session = profile.cgx_content.get('token_session') return True else: print("Profile retrieval failed.") # clear password out of memory self._parent_class._password = None return False
python
def interactive_update_profile_vars(self): """ Function to update the `cloudgenix.API` object with profile info. Run after login or client login. **Returns:** Boolean on success/failure, """ profile = self._parent_class.get.profile() if profile.cgx_status: # if successful, save tenant id and email info to cli state. self._parent_class.tenant_id = profile.cgx_content.get('tenant_id') self._parent_class.email = profile.cgx_content.get('email') self._parent_class._user_id = profile.cgx_content.get('id') self._parent_class.roles = profile.cgx_content.get('roles', []) self._parent_class.token_session = profile.cgx_content.get('token_session') return True else: print("Profile retrieval failed.") # clear password out of memory self._parent_class._password = None return False
[ "def", "interactive_update_profile_vars", "(", "self", ")", ":", "profile", "=", "self", ".", "_parent_class", ".", "get", ".", "profile", "(", ")", "if", "profile", ".", "cgx_status", ":", "# if successful, save tenant id and email info to cli state.", "self", ".", "_parent_class", ".", "tenant_id", "=", "profile", ".", "cgx_content", ".", "get", "(", "'tenant_id'", ")", "self", ".", "_parent_class", ".", "email", "=", "profile", ".", "cgx_content", ".", "get", "(", "'email'", ")", "self", ".", "_parent_class", ".", "_user_id", "=", "profile", ".", "cgx_content", ".", "get", "(", "'id'", ")", "self", ".", "_parent_class", ".", "roles", "=", "profile", ".", "cgx_content", ".", "get", "(", "'roles'", ",", "[", "]", ")", "self", ".", "_parent_class", ".", "token_session", "=", "profile", ".", "cgx_content", ".", "get", "(", "'token_session'", ")", "return", "True", "else", ":", "print", "(", "\"Profile retrieval failed.\"", ")", "# clear password out of memory", "self", ".", "_parent_class", ".", "_password", "=", "None", "return", "False" ]
Function to update the `cloudgenix.API` object with profile info. Run after login or client login. **Returns:** Boolean on success/failure,
[ "Function", "to", "update", "the", "cloudgenix", ".", "API", "object", "with", "profile", "info", ".", "Run", "after", "login", "or", "client", "login", "." ]
1b2f92582b6a19769134914793bfd00e4caa074b
https://github.com/CloudGenix/sdk-python/blob/1b2f92582b6a19769134914793bfd00e4caa074b/cloudgenix/interactive.py#L398-L422
train
CloudGenix/sdk-python
cloudgenix/interactive.py
Interactive.interactive_client_choice
def interactive_client_choice(self): """ Present a menu for user to select from ESP/MSP managed clients they have permission to. **Returns:** Tuple with (Boolean success, selected client ID). """ clients = self._parent_class.get.clients_t() clients_perms = self._parent_class.get.permissions_clients_d(self._parent_class._user_id) client_status = clients.cgx_status clients_dict = clients.cgx_content c_perms_status = clients_perms.cgx_status c_perms_dict = clients_perms.cgx_content # Build MSP/ESP id-name dict, get list of allowed tenants. if client_status and c_perms_status: client_id_name = {} for client in clients_dict.get('items', []): if type(client) is dict: # create client ID to name map table. client_id_name[client.get('id', "err")] = client.get('canonical_name') # Valid clients w/permissions - create list of tuples for menu menu_list = [] for client in c_perms_dict.get('items', []): if type(client) is dict: # add entry client_id = client.get('client_id') # create tuple of ( client name, client id ) to append to list menu_list.append( (client_id_name.get(client_id, client_id), client_id) ) # empty menu? if not menu_list: # no clients print("No ESP/MSP clients allowed for user.") return False, {} # ask user to select client _, chosen_client_id = self.quick_menu("ESP/MSP Detected. Select a client to use:", "{0}) {1}", menu_list) return True, chosen_client_id else: print("ESP/MSP detail retrieval failed.") return False, {}
python
def interactive_client_choice(self): """ Present a menu for user to select from ESP/MSP managed clients they have permission to. **Returns:** Tuple with (Boolean success, selected client ID). """ clients = self._parent_class.get.clients_t() clients_perms = self._parent_class.get.permissions_clients_d(self._parent_class._user_id) client_status = clients.cgx_status clients_dict = clients.cgx_content c_perms_status = clients_perms.cgx_status c_perms_dict = clients_perms.cgx_content # Build MSP/ESP id-name dict, get list of allowed tenants. if client_status and c_perms_status: client_id_name = {} for client in clients_dict.get('items', []): if type(client) is dict: # create client ID to name map table. client_id_name[client.get('id', "err")] = client.get('canonical_name') # Valid clients w/permissions - create list of tuples for menu menu_list = [] for client in c_perms_dict.get('items', []): if type(client) is dict: # add entry client_id = client.get('client_id') # create tuple of ( client name, client id ) to append to list menu_list.append( (client_id_name.get(client_id, client_id), client_id) ) # empty menu? if not menu_list: # no clients print("No ESP/MSP clients allowed for user.") return False, {} # ask user to select client _, chosen_client_id = self.quick_menu("ESP/MSP Detected. Select a client to use:", "{0}) {1}", menu_list) return True, chosen_client_id else: print("ESP/MSP detail retrieval failed.") return False, {}
[ "def", "interactive_client_choice", "(", "self", ")", ":", "clients", "=", "self", ".", "_parent_class", ".", "get", ".", "clients_t", "(", ")", "clients_perms", "=", "self", ".", "_parent_class", ".", "get", ".", "permissions_clients_d", "(", "self", ".", "_parent_class", ".", "_user_id", ")", "client_status", "=", "clients", ".", "cgx_status", "clients_dict", "=", "clients", ".", "cgx_content", "c_perms_status", "=", "clients_perms", ".", "cgx_status", "c_perms_dict", "=", "clients_perms", ".", "cgx_content", "# Build MSP/ESP id-name dict, get list of allowed tenants.", "if", "client_status", "and", "c_perms_status", ":", "client_id_name", "=", "{", "}", "for", "client", "in", "clients_dict", ".", "get", "(", "'items'", ",", "[", "]", ")", ":", "if", "type", "(", "client", ")", "is", "dict", ":", "# create client ID to name map table.", "client_id_name", "[", "client", ".", "get", "(", "'id'", ",", "\"err\"", ")", "]", "=", "client", ".", "get", "(", "'canonical_name'", ")", "# Valid clients w/permissions - create list of tuples for menu", "menu_list", "=", "[", "]", "for", "client", "in", "c_perms_dict", ".", "get", "(", "'items'", ",", "[", "]", ")", ":", "if", "type", "(", "client", ")", "is", "dict", ":", "# add entry", "client_id", "=", "client", ".", "get", "(", "'client_id'", ")", "# create tuple of ( client name, client id ) to append to list", "menu_list", ".", "append", "(", "(", "client_id_name", ".", "get", "(", "client_id", ",", "client_id", ")", ",", "client_id", ")", ")", "# empty menu?", "if", "not", "menu_list", ":", "# no clients", "print", "(", "\"No ESP/MSP clients allowed for user.\"", ")", "return", "False", ",", "{", "}", "# ask user to select client", "_", ",", "chosen_client_id", "=", "self", ".", "quick_menu", "(", "\"ESP/MSP Detected. Select a client to use:\"", ",", "\"{0}) {1}\"", ",", "menu_list", ")", "return", "True", ",", "chosen_client_id", "else", ":", "print", "(", "\"ESP/MSP detail retrieval failed.\"", ")", "return", "False", ",", "{", "}" ]
Present a menu for user to select from ESP/MSP managed clients they have permission to. **Returns:** Tuple with (Boolean success, selected client ID).
[ "Present", "a", "menu", "for", "user", "to", "select", "from", "ESP", "/", "MSP", "managed", "clients", "they", "have", "permission", "to", "." ]
1b2f92582b6a19769134914793bfd00e4caa074b
https://github.com/CloudGenix/sdk-python/blob/1b2f92582b6a19769134914793bfd00e4caa074b/cloudgenix/interactive.py#L424-L470
train
CloudGenix/sdk-python
cloudgenix/interactive.py
Interactive.quick_menu
def quick_menu(self, banner, list_line_format, choice_list): """ Function to display a quick menu for user input **Parameters:** - **banner:** Text to display before menu - **list_line_format:** Print'ing string with format spots for index + tuple values - **choice_list:** List of tuple values that you want returned if selected (and printed) **Returns:** Tuple that was selected. """ # Setup menu invalid = True menu_int = -1 # loop until valid while invalid: print(banner) for item_index, item_value in enumerate(choice_list): print(list_line_format.format(item_index + 1, *item_value)) menu_choice = compat_input("\nChoose a Number or (Q)uit: ") if str(menu_choice).lower() in ['q']: # exit print("Exiting..") # best effort logout self._parent_class.get.logout() sys.exit(0) # verify number entered try: menu_int = int(menu_choice) sanity = True except ValueError: # not a number print("ERROR: ", menu_choice) sanity = False # validate number chosen if sanity and 1 <= menu_int <= len(choice_list): invalid = False else: print("Invalid input, needs to be between 1 and {0}.\n".format(len(choice_list))) # return the choice_list tuple that matches the entry. return choice_list[int(menu_int) - 1]
python
def quick_menu(self, banner, list_line_format, choice_list): """ Function to display a quick menu for user input **Parameters:** - **banner:** Text to display before menu - **list_line_format:** Print'ing string with format spots for index + tuple values - **choice_list:** List of tuple values that you want returned if selected (and printed) **Returns:** Tuple that was selected. """ # Setup menu invalid = True menu_int = -1 # loop until valid while invalid: print(banner) for item_index, item_value in enumerate(choice_list): print(list_line_format.format(item_index + 1, *item_value)) menu_choice = compat_input("\nChoose a Number or (Q)uit: ") if str(menu_choice).lower() in ['q']: # exit print("Exiting..") # best effort logout self._parent_class.get.logout() sys.exit(0) # verify number entered try: menu_int = int(menu_choice) sanity = True except ValueError: # not a number print("ERROR: ", menu_choice) sanity = False # validate number chosen if sanity and 1 <= menu_int <= len(choice_list): invalid = False else: print("Invalid input, needs to be between 1 and {0}.\n".format(len(choice_list))) # return the choice_list tuple that matches the entry. return choice_list[int(menu_int) - 1]
[ "def", "quick_menu", "(", "self", ",", "banner", ",", "list_line_format", ",", "choice_list", ")", ":", "# Setup menu", "invalid", "=", "True", "menu_int", "=", "-", "1", "# loop until valid", "while", "invalid", ":", "print", "(", "banner", ")", "for", "item_index", ",", "item_value", "in", "enumerate", "(", "choice_list", ")", ":", "print", "(", "list_line_format", ".", "format", "(", "item_index", "+", "1", ",", "*", "item_value", ")", ")", "menu_choice", "=", "compat_input", "(", "\"\\nChoose a Number or (Q)uit: \"", ")", "if", "str", "(", "menu_choice", ")", ".", "lower", "(", ")", "in", "[", "'q'", "]", ":", "# exit", "print", "(", "\"Exiting..\"", ")", "# best effort logout", "self", ".", "_parent_class", ".", "get", ".", "logout", "(", ")", "sys", ".", "exit", "(", "0", ")", "# verify number entered", "try", ":", "menu_int", "=", "int", "(", "menu_choice", ")", "sanity", "=", "True", "except", "ValueError", ":", "# not a number", "print", "(", "\"ERROR: \"", ",", "menu_choice", ")", "sanity", "=", "False", "# validate number chosen", "if", "sanity", "and", "1", "<=", "menu_int", "<=", "len", "(", "choice_list", ")", ":", "invalid", "=", "False", "else", ":", "print", "(", "\"Invalid input, needs to be between 1 and {0}.\\n\"", ".", "format", "(", "len", "(", "choice_list", ")", ")", ")", "# return the choice_list tuple that matches the entry.", "return", "choice_list", "[", "int", "(", "menu_int", ")", "-", "1", "]" ]
Function to display a quick menu for user input **Parameters:** - **banner:** Text to display before menu - **list_line_format:** Print'ing string with format spots for index + tuple values - **choice_list:** List of tuple values that you want returned if selected (and printed) **Returns:** Tuple that was selected.
[ "Function", "to", "display", "a", "quick", "menu", "for", "user", "input" ]
1b2f92582b6a19769134914793bfd00e4caa074b
https://github.com/CloudGenix/sdk-python/blob/1b2f92582b6a19769134914793bfd00e4caa074b/cloudgenix/interactive.py#L472-L520
train
CloudGenix/sdk-python
cloudgenix/interactive.py
Interactive.check_sso_login
def check_sso_login(self, operator_email, request_id): """ Login to the CloudGenix API, and see if SAML SSO has occurred. This function is used to check and see if SAML SSO has succeeded while waiting. **Parameters:** - **operator_email:** String with the username to log in with - **request_id:** String containing the SAML 2.0 Request ID from previous login attempt. **Returns:** Tuple (Boolean success, Token on success, JSON response on error.) """ data = { "email": operator_email, "requestId": request_id } # If debug is set.. api_logger.info('check_sso_login function:') response = self._parent_class.post.login(data=data) # If valid response, but no token. if not response.cgx_content.get('x_auth_token'): # no valid login yet. return response # update with token and region auth_region = self._parent_class.parse_region(response) self._parent_class.update_region_to_controller(auth_region) self._parent_class.reparse_login_cookie_after_region_update(response) return response
python
def check_sso_login(self, operator_email, request_id): """ Login to the CloudGenix API, and see if SAML SSO has occurred. This function is used to check and see if SAML SSO has succeeded while waiting. **Parameters:** - **operator_email:** String with the username to log in with - **request_id:** String containing the SAML 2.0 Request ID from previous login attempt. **Returns:** Tuple (Boolean success, Token on success, JSON response on error.) """ data = { "email": operator_email, "requestId": request_id } # If debug is set.. api_logger.info('check_sso_login function:') response = self._parent_class.post.login(data=data) # If valid response, but no token. if not response.cgx_content.get('x_auth_token'): # no valid login yet. return response # update with token and region auth_region = self._parent_class.parse_region(response) self._parent_class.update_region_to_controller(auth_region) self._parent_class.reparse_login_cookie_after_region_update(response) return response
[ "def", "check_sso_login", "(", "self", ",", "operator_email", ",", "request_id", ")", ":", "data", "=", "{", "\"email\"", ":", "operator_email", ",", "\"requestId\"", ":", "request_id", "}", "# If debug is set..", "api_logger", ".", "info", "(", "'check_sso_login function:'", ")", "response", "=", "self", ".", "_parent_class", ".", "post", ".", "login", "(", "data", "=", "data", ")", "# If valid response, but no token.", "if", "not", "response", ".", "cgx_content", ".", "get", "(", "'x_auth_token'", ")", ":", "# no valid login yet.", "return", "response", "# update with token and region", "auth_region", "=", "self", ".", "_parent_class", ".", "parse_region", "(", "response", ")", "self", ".", "_parent_class", ".", "update_region_to_controller", "(", "auth_region", ")", "self", ".", "_parent_class", ".", "reparse_login_cookie_after_region_update", "(", "response", ")", "return", "response" ]
Login to the CloudGenix API, and see if SAML SSO has occurred. This function is used to check and see if SAML SSO has succeeded while waiting. **Parameters:** - **operator_email:** String with the username to log in with - **request_id:** String containing the SAML 2.0 Request ID from previous login attempt. **Returns:** Tuple (Boolean success, Token on success, JSON response on error.)
[ "Login", "to", "the", "CloudGenix", "API", "and", "see", "if", "SAML", "SSO", "has", "occurred", ".", "This", "function", "is", "used", "to", "check", "and", "see", "if", "SAML", "SSO", "has", "succeeded", "while", "waiting", "." ]
1b2f92582b6a19769134914793bfd00e4caa074b
https://github.com/CloudGenix/sdk-python/blob/1b2f92582b6a19769134914793bfd00e4caa074b/cloudgenix/interactive.py#L522-L555
train
CloudGenix/sdk-python
cloudgenix/interactive.py
Interactive.logout
def logout(self, force=False): """ Interactive logout - ensures uid/tid cleared so `cloudgenix.API` object/ requests.Session can be re-used. **Parameters:**: - **force**: Bool, force logout API call, even when using a static AUTH_TOKEN. **Returns:** Bool of whether the operation succeeded. """ # Extract requests session for manipulation. session = self._parent_class.expose_session() # if force = True, or token_session = None/False, call logout API. if force or not self._parent_class.token_session: # Call Logout result = self._parent_class.get.logout() if result.cgx_status: # clear info from session. self._parent_class.tenant_id = None self._parent_class.tenant_name = None self._parent_class.is_esp = None self._parent_class.client_id = None self._parent_class.address_string = None self._parent_class.email = None self._parent_class._user_id = None self._parent_class._password = None self._parent_class.roles = None self._parent_class.token_session = None # Cookies are removed via LOGOUT API call. if X-Auth-Token set, clear. if session.headers.get('X-Auth-Token'): self._parent_class.remove_header('X-Auth-Token') return result.cgx_status else: # Token Session and not forced. api_logger.debug('TOKEN SESSION, LOGOUT API NOT CALLED.') # clear info from session. self._parent_class.tenant_id = None self._parent_class.tenant_name = None self._parent_class.is_esp = None self._parent_class.client_id = None self._parent_class.address_string = None self._parent_class.email = None self._parent_class._user_id = None self._parent_class._password = None self._parent_class.roles = None self._parent_class.token_session = None # if X-Auth-Token set, clear. if session.headers.get('X-Auth-Token'): self._parent_class.remove_header('X-Auth-Token') return True
python
def logout(self, force=False): """ Interactive logout - ensures uid/tid cleared so `cloudgenix.API` object/ requests.Session can be re-used. **Parameters:**: - **force**: Bool, force logout API call, even when using a static AUTH_TOKEN. **Returns:** Bool of whether the operation succeeded. """ # Extract requests session for manipulation. session = self._parent_class.expose_session() # if force = True, or token_session = None/False, call logout API. if force or not self._parent_class.token_session: # Call Logout result = self._parent_class.get.logout() if result.cgx_status: # clear info from session. self._parent_class.tenant_id = None self._parent_class.tenant_name = None self._parent_class.is_esp = None self._parent_class.client_id = None self._parent_class.address_string = None self._parent_class.email = None self._parent_class._user_id = None self._parent_class._password = None self._parent_class.roles = None self._parent_class.token_session = None # Cookies are removed via LOGOUT API call. if X-Auth-Token set, clear. if session.headers.get('X-Auth-Token'): self._parent_class.remove_header('X-Auth-Token') return result.cgx_status else: # Token Session and not forced. api_logger.debug('TOKEN SESSION, LOGOUT API NOT CALLED.') # clear info from session. self._parent_class.tenant_id = None self._parent_class.tenant_name = None self._parent_class.is_esp = None self._parent_class.client_id = None self._parent_class.address_string = None self._parent_class.email = None self._parent_class._user_id = None self._parent_class._password = None self._parent_class.roles = None self._parent_class.token_session = None # if X-Auth-Token set, clear. if session.headers.get('X-Auth-Token'): self._parent_class.remove_header('X-Auth-Token') return True
[ "def", "logout", "(", "self", ",", "force", "=", "False", ")", ":", "# Extract requests session for manipulation.", "session", "=", "self", ".", "_parent_class", ".", "expose_session", "(", ")", "# if force = True, or token_session = None/False, call logout API.", "if", "force", "or", "not", "self", ".", "_parent_class", ".", "token_session", ":", "# Call Logout", "result", "=", "self", ".", "_parent_class", ".", "get", ".", "logout", "(", ")", "if", "result", ".", "cgx_status", ":", "# clear info from session.", "self", ".", "_parent_class", ".", "tenant_id", "=", "None", "self", ".", "_parent_class", ".", "tenant_name", "=", "None", "self", ".", "_parent_class", ".", "is_esp", "=", "None", "self", ".", "_parent_class", ".", "client_id", "=", "None", "self", ".", "_parent_class", ".", "address_string", "=", "None", "self", ".", "_parent_class", ".", "email", "=", "None", "self", ".", "_parent_class", ".", "_user_id", "=", "None", "self", ".", "_parent_class", ".", "_password", "=", "None", "self", ".", "_parent_class", ".", "roles", "=", "None", "self", ".", "_parent_class", ".", "token_session", "=", "None", "# Cookies are removed via LOGOUT API call. if X-Auth-Token set, clear.", "if", "session", ".", "headers", ".", "get", "(", "'X-Auth-Token'", ")", ":", "self", ".", "_parent_class", ".", "remove_header", "(", "'X-Auth-Token'", ")", "return", "result", ".", "cgx_status", "else", ":", "# Token Session and not forced.", "api_logger", ".", "debug", "(", "'TOKEN SESSION, LOGOUT API NOT CALLED.'", ")", "# clear info from session.", "self", ".", "_parent_class", ".", "tenant_id", "=", "None", "self", ".", "_parent_class", ".", "tenant_name", "=", "None", "self", ".", "_parent_class", ".", "is_esp", "=", "None", "self", ".", "_parent_class", ".", "client_id", "=", "None", "self", ".", "_parent_class", ".", "address_string", "=", "None", "self", ".", "_parent_class", ".", "email", "=", "None", "self", ".", "_parent_class", ".", "_user_id", "=", "None", "self", ".", "_parent_class", ".", "_password", "=", "None", "self", ".", "_parent_class", ".", "roles", "=", "None", "self", ".", "_parent_class", ".", "token_session", "=", "None", "# if X-Auth-Token set, clear.", "if", "session", ".", "headers", ".", "get", "(", "'X-Auth-Token'", ")", ":", "self", ".", "_parent_class", ".", "remove_header", "(", "'X-Auth-Token'", ")", "return", "True" ]
Interactive logout - ensures uid/tid cleared so `cloudgenix.API` object/ requests.Session can be re-used. **Parameters:**: - **force**: Bool, force logout API call, even when using a static AUTH_TOKEN. **Returns:** Bool of whether the operation succeeded.
[ "Interactive", "logout", "-", "ensures", "uid", "/", "tid", "cleared", "so", "cloudgenix", ".", "API", "object", "/", "requests", ".", "Session", "can", "be", "re", "-", "used", "." ]
1b2f92582b6a19769134914793bfd00e4caa074b
https://github.com/CloudGenix/sdk-python/blob/1b2f92582b6a19769134914793bfd00e4caa074b/cloudgenix/interactive.py#L557-L610
train
CloudGenix/sdk-python
cloudgenix/interactive.py
Interactive.jd
def jd(api_response): """ JD (JSON Dump) function. Meant for quick pretty-printing of CloudGenix Response objects. Example: `jd(cgx_sess.get.sites())` **Returns:** No Return, directly prints all output. """ try: # attempt to print the cgx_content. should always be a Dict if it exists. print(json.dumps(api_response.cgx_content, indent=4)) except (TypeError, ValueError, AttributeError): # cgx_content did not exist, or was not JSON serializable. Try pretty printing the base obj. try: print(json.dumps(api_response, indent=4)) except (TypeError, ValueError, AttributeError): # Same issue, just raw print the passed data. Let any exceptions happen here. print(api_response) return
python
def jd(api_response): """ JD (JSON Dump) function. Meant for quick pretty-printing of CloudGenix Response objects. Example: `jd(cgx_sess.get.sites())` **Returns:** No Return, directly prints all output. """ try: # attempt to print the cgx_content. should always be a Dict if it exists. print(json.dumps(api_response.cgx_content, indent=4)) except (TypeError, ValueError, AttributeError): # cgx_content did not exist, or was not JSON serializable. Try pretty printing the base obj. try: print(json.dumps(api_response, indent=4)) except (TypeError, ValueError, AttributeError): # Same issue, just raw print the passed data. Let any exceptions happen here. print(api_response) return
[ "def", "jd", "(", "api_response", ")", ":", "try", ":", "# attempt to print the cgx_content. should always be a Dict if it exists.", "print", "(", "json", ".", "dumps", "(", "api_response", ".", "cgx_content", ",", "indent", "=", "4", ")", ")", "except", "(", "TypeError", ",", "ValueError", ",", "AttributeError", ")", ":", "# cgx_content did not exist, or was not JSON serializable. Try pretty printing the base obj.", "try", ":", "print", "(", "json", ".", "dumps", "(", "api_response", ",", "indent", "=", "4", ")", ")", "except", "(", "TypeError", ",", "ValueError", ",", "AttributeError", ")", ":", "# Same issue, just raw print the passed data. Let any exceptions happen here.", "print", "(", "api_response", ")", "return" ]
JD (JSON Dump) function. Meant for quick pretty-printing of CloudGenix Response objects. Example: `jd(cgx_sess.get.sites())` **Returns:** No Return, directly prints all output.
[ "JD", "(", "JSON", "Dump", ")", "function", ".", "Meant", "for", "quick", "pretty", "-", "printing", "of", "CloudGenix", "Response", "objects", "." ]
1b2f92582b6a19769134914793bfd00e4caa074b
https://github.com/CloudGenix/sdk-python/blob/1b2f92582b6a19769134914793bfd00e4caa074b/cloudgenix/interactive.py#L613-L631
train
CloudGenix/sdk-python
cloudgenix/interactive.py
Interactive.quick_confirm
def quick_confirm(prompt, default_value): """ Function to display a quick confirmation for user input **Parameters:** - **prompt:** Text to display before confirm - **default_value:** Default value for no entry **Returns:** 'y', 'n', or Default value. """ valid = False value = default_value.lower() while not valid: input_val = compat_input(prompt + "[{0}]: ".format(default_value)) if input_val == "": value = default_value.lower() valid = True else: try: if input_val.lower() in ['y', 'n']: value = input_val.lower() valid = True else: print("ERROR: enter 'Y' or 'N'.") valid = False except ValueError: print("ERROR: enter 'Y' or 'N'.") valid = False return value
python
def quick_confirm(prompt, default_value): """ Function to display a quick confirmation for user input **Parameters:** - **prompt:** Text to display before confirm - **default_value:** Default value for no entry **Returns:** 'y', 'n', or Default value. """ valid = False value = default_value.lower() while not valid: input_val = compat_input(prompt + "[{0}]: ".format(default_value)) if input_val == "": value = default_value.lower() valid = True else: try: if input_val.lower() in ['y', 'n']: value = input_val.lower() valid = True else: print("ERROR: enter 'Y' or 'N'.") valid = False except ValueError: print("ERROR: enter 'Y' or 'N'.") valid = False return value
[ "def", "quick_confirm", "(", "prompt", ",", "default_value", ")", ":", "valid", "=", "False", "value", "=", "default_value", ".", "lower", "(", ")", "while", "not", "valid", ":", "input_val", "=", "compat_input", "(", "prompt", "+", "\"[{0}]: \"", ".", "format", "(", "default_value", ")", ")", "if", "input_val", "==", "\"\"", ":", "value", "=", "default_value", ".", "lower", "(", ")", "valid", "=", "True", "else", ":", "try", ":", "if", "input_val", ".", "lower", "(", ")", "in", "[", "'y'", ",", "'n'", "]", ":", "value", "=", "input_val", ".", "lower", "(", ")", "valid", "=", "True", "else", ":", "print", "(", "\"ERROR: enter 'Y' or 'N'.\"", ")", "valid", "=", "False", "except", "ValueError", ":", "print", "(", "\"ERROR: enter 'Y' or 'N'.\"", ")", "valid", "=", "False", "return", "value" ]
Function to display a quick confirmation for user input **Parameters:** - **prompt:** Text to display before confirm - **default_value:** Default value for no entry **Returns:** 'y', 'n', or Default value.
[ "Function", "to", "display", "a", "quick", "confirmation", "for", "user", "input" ]
1b2f92582b6a19769134914793bfd00e4caa074b
https://github.com/CloudGenix/sdk-python/blob/1b2f92582b6a19769134914793bfd00e4caa074b/cloudgenix/interactive.py#L634-L666
train
CloudGenix/sdk-python
cloudgenix/interactive.py
Interactive.quick_int_input
def quick_int_input(prompt, default_value, min_val=1, max_val=30): """ Function to display a quick question for integer user input **Parameters:** - **prompt:** Text / question to display - **default_value:** Default value for no entry - **min_val:** Lowest allowed integer - **max_val:** Highest allowed integer **Returns:** integer or default_value. """ valid = False num_val = default_value while not valid: input_val = compat_input(prompt + "[{0}]: ".format(default_value)) if input_val == "": num_val = default_value valid = True else: try: num_val = int(input_val) if min_val <= num_val <= max_val: valid = True else: print("ERROR: must be between {0} and {1}.".format(min, max)) valid = False except ValueError: print("ERROR: must be a number.") valid = False return num_val
python
def quick_int_input(prompt, default_value, min_val=1, max_val=30): """ Function to display a quick question for integer user input **Parameters:** - **prompt:** Text / question to display - **default_value:** Default value for no entry - **min_val:** Lowest allowed integer - **max_val:** Highest allowed integer **Returns:** integer or default_value. """ valid = False num_val = default_value while not valid: input_val = compat_input(prompt + "[{0}]: ".format(default_value)) if input_val == "": num_val = default_value valid = True else: try: num_val = int(input_val) if min_val <= num_val <= max_val: valid = True else: print("ERROR: must be between {0} and {1}.".format(min, max)) valid = False except ValueError: print("ERROR: must be a number.") valid = False return num_val
[ "def", "quick_int_input", "(", "prompt", ",", "default_value", ",", "min_val", "=", "1", ",", "max_val", "=", "30", ")", ":", "valid", "=", "False", "num_val", "=", "default_value", "while", "not", "valid", ":", "input_val", "=", "compat_input", "(", "prompt", "+", "\"[{0}]: \"", ".", "format", "(", "default_value", ")", ")", "if", "input_val", "==", "\"\"", ":", "num_val", "=", "default_value", "valid", "=", "True", "else", ":", "try", ":", "num_val", "=", "int", "(", "input_val", ")", "if", "min_val", "<=", "num_val", "<=", "max_val", ":", "valid", "=", "True", "else", ":", "print", "(", "\"ERROR: must be between {0} and {1}.\"", ".", "format", "(", "min", ",", "max", ")", ")", "valid", "=", "False", "except", "ValueError", ":", "print", "(", "\"ERROR: must be a number.\"", ")", "valid", "=", "False", "return", "num_val" ]
Function to display a quick question for integer user input **Parameters:** - **prompt:** Text / question to display - **default_value:** Default value for no entry - **min_val:** Lowest allowed integer - **max_val:** Highest allowed integer **Returns:** integer or default_value.
[ "Function", "to", "display", "a", "quick", "question", "for", "integer", "user", "input" ]
1b2f92582b6a19769134914793bfd00e4caa074b
https://github.com/CloudGenix/sdk-python/blob/1b2f92582b6a19769134914793bfd00e4caa074b/cloudgenix/interactive.py#L669-L703
train
CloudGenix/sdk-python
cloudgenix/interactive.py
Interactive.quick_str_input
def quick_str_input(prompt, default_value): """ Function to display a quick question for text input. **Parameters:** - **prompt:** Text / question to display - **default_value:** Default value for no entry **Returns:** text_type() or default_value. """ valid = False str_val = default_value while not valid: input_val = raw_input(prompt + "[{0}]: ".format(default_value)) if input_val == "": str_val = default_value valid = True else: try: str_val = text_type(input_val) valid = True except ValueError: print("ERROR: must be text.") valid = False return str_val
python
def quick_str_input(prompt, default_value): """ Function to display a quick question for text input. **Parameters:** - **prompt:** Text / question to display - **default_value:** Default value for no entry **Returns:** text_type() or default_value. """ valid = False str_val = default_value while not valid: input_val = raw_input(prompt + "[{0}]: ".format(default_value)) if input_val == "": str_val = default_value valid = True else: try: str_val = text_type(input_val) valid = True except ValueError: print("ERROR: must be text.") valid = False return str_val
[ "def", "quick_str_input", "(", "prompt", ",", "default_value", ")", ":", "valid", "=", "False", "str_val", "=", "default_value", "while", "not", "valid", ":", "input_val", "=", "raw_input", "(", "prompt", "+", "\"[{0}]: \"", ".", "format", "(", "default_value", ")", ")", "if", "input_val", "==", "\"\"", ":", "str_val", "=", "default_value", "valid", "=", "True", "else", ":", "try", ":", "str_val", "=", "text_type", "(", "input_val", ")", "valid", "=", "True", "except", "ValueError", ":", "print", "(", "\"ERROR: must be text.\"", ")", "valid", "=", "False", "return", "str_val" ]
Function to display a quick question for text input. **Parameters:** - **prompt:** Text / question to display - **default_value:** Default value for no entry **Returns:** text_type() or default_value.
[ "Function", "to", "display", "a", "quick", "question", "for", "text", "input", "." ]
1b2f92582b6a19769134914793bfd00e4caa074b
https://github.com/CloudGenix/sdk-python/blob/1b2f92582b6a19769134914793bfd00e4caa074b/cloudgenix/interactive.py#L706-L734
train
diffeo/py-nilsimsa
nilsimsa/__init__.py
compare_digests
def compare_digests(digest_1, digest_2, is_hex_1=True, is_hex_2=True, threshold=None): """ computes bit difference between two nilsisa digests takes params for format, default is hex string but can accept list of 32 length ints Optimized method originally from https://gist.github.com/michelp/6255490 If `threshold` is set, and the comparison will be less than `threshold`, then bail out early and return a value just below the threshold. This is a speed optimization that accelerates comparisons of very different items; e.g. tests show a ~20-30% speed up. `threshold` must be an integer in the range [-128, 128]. """ # if we have both hexes use optimized method if threshold is not None: threshold -= 128 threshold *= -1 if is_hex_1 and is_hex_2: bits = 0 for i in range_(0, 63, 2): bits += POPC[255 & int(digest_1[i:i+2], 16) ^ int(digest_2[i:i+2], 16)] if threshold is not None and bits > threshold: break return 128 - bits else: # at least one of the inputs is a list of unsigned ints if is_hex_1: digest_1 = convert_hex_to_ints(digest_1) if is_hex_2: digest_2 = convert_hex_to_ints(digest_2) bit_diff = 0 for i in range(len(digest_1)): bit_diff += POPC[255 & digest_1[i] ^ digest_2[i]] if threshold is not None and bit_diff > threshold: break return 128 - bit_diff
python
def compare_digests(digest_1, digest_2, is_hex_1=True, is_hex_2=True, threshold=None): """ computes bit difference between two nilsisa digests takes params for format, default is hex string but can accept list of 32 length ints Optimized method originally from https://gist.github.com/michelp/6255490 If `threshold` is set, and the comparison will be less than `threshold`, then bail out early and return a value just below the threshold. This is a speed optimization that accelerates comparisons of very different items; e.g. tests show a ~20-30% speed up. `threshold` must be an integer in the range [-128, 128]. """ # if we have both hexes use optimized method if threshold is not None: threshold -= 128 threshold *= -1 if is_hex_1 and is_hex_2: bits = 0 for i in range_(0, 63, 2): bits += POPC[255 & int(digest_1[i:i+2], 16) ^ int(digest_2[i:i+2], 16)] if threshold is not None and bits > threshold: break return 128 - bits else: # at least one of the inputs is a list of unsigned ints if is_hex_1: digest_1 = convert_hex_to_ints(digest_1) if is_hex_2: digest_2 = convert_hex_to_ints(digest_2) bit_diff = 0 for i in range(len(digest_1)): bit_diff += POPC[255 & digest_1[i] ^ digest_2[i]] if threshold is not None and bit_diff > threshold: break return 128 - bit_diff
[ "def", "compare_digests", "(", "digest_1", ",", "digest_2", ",", "is_hex_1", "=", "True", ",", "is_hex_2", "=", "True", ",", "threshold", "=", "None", ")", ":", "# if we have both hexes use optimized method", "if", "threshold", "is", "not", "None", ":", "threshold", "-=", "128", "threshold", "*=", "-", "1", "if", "is_hex_1", "and", "is_hex_2", ":", "bits", "=", "0", "for", "i", "in", "range_", "(", "0", ",", "63", ",", "2", ")", ":", "bits", "+=", "POPC", "[", "255", "&", "int", "(", "digest_1", "[", "i", ":", "i", "+", "2", "]", ",", "16", ")", "^", "int", "(", "digest_2", "[", "i", ":", "i", "+", "2", "]", ",", "16", ")", "]", "if", "threshold", "is", "not", "None", "and", "bits", ">", "threshold", ":", "break", "return", "128", "-", "bits", "else", ":", "# at least one of the inputs is a list of unsigned ints", "if", "is_hex_1", ":", "digest_1", "=", "convert_hex_to_ints", "(", "digest_1", ")", "if", "is_hex_2", ":", "digest_2", "=", "convert_hex_to_ints", "(", "digest_2", ")", "bit_diff", "=", "0", "for", "i", "in", "range", "(", "len", "(", "digest_1", ")", ")", ":", "bit_diff", "+=", "POPC", "[", "255", "&", "digest_1", "[", "i", "]", "^", "digest_2", "[", "i", "]", "]", "if", "threshold", "is", "not", "None", "and", "bit_diff", ">", "threshold", ":", "break", "return", "128", "-", "bit_diff" ]
computes bit difference between two nilsisa digests takes params for format, default is hex string but can accept list of 32 length ints Optimized method originally from https://gist.github.com/michelp/6255490 If `threshold` is set, and the comparison will be less than `threshold`, then bail out early and return a value just below the threshold. This is a speed optimization that accelerates comparisons of very different items; e.g. tests show a ~20-30% speed up. `threshold` must be an integer in the range [-128, 128].
[ "computes", "bit", "difference", "between", "two", "nilsisa", "digests", "takes", "params", "for", "format", "default", "is", "hex", "string", "but", "can", "accept", "list", "of", "32", "length", "ints", "Optimized", "method", "originally", "from", "https", ":", "//", "gist", ".", "github", ".", "com", "/", "michelp", "/", "6255490" ]
c652f4bbfd836f7aebf292dcea676cc925ec315a
https://github.com/diffeo/py-nilsimsa/blob/c652f4bbfd836f7aebf292dcea676cc925ec315a/nilsimsa/__init__.py#L208-L240
train
diffeo/py-nilsimsa
nilsimsa/__init__.py
Nilsimsa.tran_hash
def tran_hash(self, a, b, c, n): """implementation of the tran53 hash function""" return (((TRAN[(a+n)&255]^TRAN[b]*(n+n+1))+TRAN[(c)^TRAN[n]])&255)
python
def tran_hash(self, a, b, c, n): """implementation of the tran53 hash function""" return (((TRAN[(a+n)&255]^TRAN[b]*(n+n+1))+TRAN[(c)^TRAN[n]])&255)
[ "def", "tran_hash", "(", "self", ",", "a", ",", "b", ",", "c", ",", "n", ")", ":", "return", "(", "(", "(", "TRAN", "[", "(", "a", "+", "n", ")", "&", "255", "]", "^", "TRAN", "[", "b", "]", "*", "(", "n", "+", "n", "+", "1", ")", ")", "+", "TRAN", "[", "(", "c", ")", "^", "TRAN", "[", "n", "]", "]", ")", "&", "255", ")" ]
implementation of the tran53 hash function
[ "implementation", "of", "the", "tran53", "hash", "function" ]
c652f4bbfd836f7aebf292dcea676cc925ec315a
https://github.com/diffeo/py-nilsimsa/blob/c652f4bbfd836f7aebf292dcea676cc925ec315a/nilsimsa/__init__.py#L99-L101
train