Search is not available for this dataset
identifier
stringlengths
1
155
parameters
stringlengths
2
6.09k
docstring
stringlengths
11
63.4k
docstring_summary
stringlengths
0
63.4k
function
stringlengths
29
99.8k
function_tokens
sequence
start_point
sequence
end_point
sequence
language
stringclasses
1 value
docstring_language
stringlengths
2
7
docstring_language_predictions
stringlengths
18
23
is_langid_reliable
stringclasses
2 values
OnvifFlowHandler.async_step_auth
(self, user_input=None)
Username and Password configuration for ONVIF device.
Username and Password configuration for ONVIF device.
async def async_step_auth(self, user_input=None): """Username and Password configuration for ONVIF device.""" if user_input: self.onvif_config[CONF_USERNAME] = user_input[CONF_USERNAME] self.onvif_config[CONF_PASSWORD] = user_input[CONF_PASSWORD] return await self.async_step_profiles() # Username and Password are optional and default empty # due to some cameras not allowing you to change ONVIF user settings. # See https://github.com/home-assistant/core/issues/39182 # and https://github.com/home-assistant/core/issues/35904 return self.async_show_form( step_id="auth", data_schema=vol.Schema( { vol.Optional(CONF_USERNAME, default=""): str, vol.Optional(CONF_PASSWORD, default=""): str, } ), )
[ "async", "def", "async_step_auth", "(", "self", ",", "user_input", "=", "None", ")", ":", "if", "user_input", ":", "self", ".", "onvif_config", "[", "CONF_USERNAME", "]", "=", "user_input", "[", "CONF_USERNAME", "]", "self", ".", "onvif_config", "[", "CONF_PASSWORD", "]", "=", "user_input", "[", "CONF_PASSWORD", "]", "return", "await", "self", ".", "async_step_profiles", "(", ")", "# Username and Password are optional and default empty", "# due to some cameras not allowing you to change ONVIF user settings.", "# See https://github.com/home-assistant/core/issues/39182", "# and https://github.com/home-assistant/core/issues/35904", "return", "self", ".", "async_show_form", "(", "step_id", "=", "\"auth\"", ",", "data_schema", "=", "vol", ".", "Schema", "(", "{", "vol", ".", "Optional", "(", "CONF_USERNAME", ",", "default", "=", "\"\"", ")", ":", "str", ",", "vol", ".", "Optional", "(", "CONF_PASSWORD", ",", "default", "=", "\"\"", ")", ":", "str", ",", "}", ")", ",", ")" ]
[ 164, 4 ]
[ 183, 9 ]
python
en
['en', 'en', 'en']
True
OnvifFlowHandler.async_step_profiles
(self, user_input=None)
Fetch ONVIF device profiles.
Fetch ONVIF device profiles.
async def async_step_profiles(self, user_input=None): """Fetch ONVIF device profiles.""" errors = {} LOGGER.debug( "Fetching profiles from ONVIF device %s", pformat(self.onvif_config) ) device = get_device( self.hass, self.onvif_config[CONF_HOST], self.onvif_config[CONF_PORT], self.onvif_config[CONF_USERNAME], self.onvif_config[CONF_PASSWORD], ) try: await device.update_xaddrs() device_mgmt = device.create_devicemgmt_service() # Get the MAC address to use as the unique ID for the config flow if not self.device_id: try: network_interfaces = await device_mgmt.GetNetworkInterfaces() for interface in network_interfaces: if interface.Enabled: self.device_id = interface.Info.HwAddress except Fault as fault: if "not implemented" not in fault.message: raise fault LOGGER.debug( "Couldn't get network interfaces from ONVIF deivice '%s'. Error: %s", self.onvif_config[CONF_NAME], fault, ) # If no network interfaces are exposed, fallback to serial number if not self.device_id: device_info = await device_mgmt.GetDeviceInformation() self.device_id = device_info.SerialNumber if not self.device_id: return self.async_abort(reason="no_mac") await self.async_set_unique_id(self.device_id, raise_on_progress=False) self._abort_if_unique_id_configured( updates={ CONF_HOST: self.onvif_config[CONF_HOST], CONF_PORT: self.onvif_config[CONF_PORT], CONF_NAME: self.onvif_config[CONF_NAME], } ) # Verify there is an H264 profile media_service = device.create_media_service() profiles = await media_service.GetProfiles() h264 = any( profile.VideoEncoderConfiguration and profile.VideoEncoderConfiguration.Encoding == "H264" for profile in profiles ) if not h264: return self.async_abort(reason="no_h264") await device.close() title = f"{self.onvif_config[CONF_NAME]} - {self.device_id}" return self.async_create_entry(title=title, data=self.onvif_config) except ONVIFError as err: LOGGER.error( "Couldn't setup ONVIF device '%s'. Error: %s", self.onvif_config[CONF_NAME], err, ) await device.close() return self.async_abort(reason="onvif_error") except Fault: errors["base"] = "cannot_connect" await device.close() return self.async_show_form(step_id="auth", errors=errors)
[ "async", "def", "async_step_profiles", "(", "self", ",", "user_input", "=", "None", ")", ":", "errors", "=", "{", "}", "LOGGER", ".", "debug", "(", "\"Fetching profiles from ONVIF device %s\"", ",", "pformat", "(", "self", ".", "onvif_config", ")", ")", "device", "=", "get_device", "(", "self", ".", "hass", ",", "self", ".", "onvif_config", "[", "CONF_HOST", "]", ",", "self", ".", "onvif_config", "[", "CONF_PORT", "]", ",", "self", ".", "onvif_config", "[", "CONF_USERNAME", "]", ",", "self", ".", "onvif_config", "[", "CONF_PASSWORD", "]", ",", ")", "try", ":", "await", "device", ".", "update_xaddrs", "(", ")", "device_mgmt", "=", "device", ".", "create_devicemgmt_service", "(", ")", "# Get the MAC address to use as the unique ID for the config flow", "if", "not", "self", ".", "device_id", ":", "try", ":", "network_interfaces", "=", "await", "device_mgmt", ".", "GetNetworkInterfaces", "(", ")", "for", "interface", "in", "network_interfaces", ":", "if", "interface", ".", "Enabled", ":", "self", ".", "device_id", "=", "interface", ".", "Info", ".", "HwAddress", "except", "Fault", "as", "fault", ":", "if", "\"not implemented\"", "not", "in", "fault", ".", "message", ":", "raise", "fault", "LOGGER", ".", "debug", "(", "\"Couldn't get network interfaces from ONVIF deivice '%s'. Error: %s\"", ",", "self", ".", "onvif_config", "[", "CONF_NAME", "]", ",", "fault", ",", ")", "# If no network interfaces are exposed, fallback to serial number", "if", "not", "self", ".", "device_id", ":", "device_info", "=", "await", "device_mgmt", ".", "GetDeviceInformation", "(", ")", "self", ".", "device_id", "=", "device_info", ".", "SerialNumber", "if", "not", "self", ".", "device_id", ":", "return", "self", ".", "async_abort", "(", "reason", "=", "\"no_mac\"", ")", "await", "self", ".", "async_set_unique_id", "(", "self", ".", "device_id", ",", "raise_on_progress", "=", "False", ")", "self", ".", "_abort_if_unique_id_configured", "(", "updates", "=", "{", "CONF_HOST", ":", "self", ".", "onvif_config", "[", "CONF_HOST", "]", ",", "CONF_PORT", ":", "self", ".", "onvif_config", "[", "CONF_PORT", "]", ",", "CONF_NAME", ":", "self", ".", "onvif_config", "[", "CONF_NAME", "]", ",", "}", ")", "# Verify there is an H264 profile", "media_service", "=", "device", ".", "create_media_service", "(", ")", "profiles", "=", "await", "media_service", ".", "GetProfiles", "(", ")", "h264", "=", "any", "(", "profile", ".", "VideoEncoderConfiguration", "and", "profile", ".", "VideoEncoderConfiguration", ".", "Encoding", "==", "\"H264\"", "for", "profile", "in", "profiles", ")", "if", "not", "h264", ":", "return", "self", ".", "async_abort", "(", "reason", "=", "\"no_h264\"", ")", "await", "device", ".", "close", "(", ")", "title", "=", "f\"{self.onvif_config[CONF_NAME]} - {self.device_id}\"", "return", "self", ".", "async_create_entry", "(", "title", "=", "title", ",", "data", "=", "self", ".", "onvif_config", ")", "except", "ONVIFError", "as", "err", ":", "LOGGER", ".", "error", "(", "\"Couldn't setup ONVIF device '%s'. Error: %s\"", ",", "self", ".", "onvif_config", "[", "CONF_NAME", "]", ",", "err", ",", ")", "await", "device", ".", "close", "(", ")", "return", "self", ".", "async_abort", "(", "reason", "=", "\"onvif_error\"", ")", "except", "Fault", ":", "errors", "[", "\"base\"", "]", "=", "\"cannot_connect\"", "await", "device", ".", "close", "(", ")", "return", "self", ".", "async_show_form", "(", "step_id", "=", "\"auth\"", ",", "errors", "=", "errors", ")" ]
[ 185, 4 ]
[ 269, 66 ]
python
de
['de', 'mk', 'en']
False
OnvifFlowHandler.async_step_import
(self, user_input)
Handle import.
Handle import.
async def async_step_import(self, user_input): """Handle import.""" self.onvif_config = user_input return await self.async_step_profiles()
[ "async", "def", "async_step_import", "(", "self", ",", "user_input", ")", ":", "self", ".", "onvif_config", "=", "user_input", "return", "await", "self", ".", "async_step_profiles", "(", ")" ]
[ 271, 4 ]
[ 274, 47 ]
python
en
['en', 'ja', 'en']
False
OnvifOptionsFlowHandler.__init__
(self, config_entry)
Initialize ONVIF options flow.
Initialize ONVIF options flow.
def __init__(self, config_entry): """Initialize ONVIF options flow.""" self.config_entry = config_entry self.options = dict(config_entry.options)
[ "def", "__init__", "(", "self", ",", "config_entry", ")", ":", "self", ".", "config_entry", "=", "config_entry", "self", ".", "options", "=", "dict", "(", "config_entry", ".", "options", ")" ]
[ 280, 4 ]
[ 283, 49 ]
python
en
['en', 'en', 'en']
True
OnvifOptionsFlowHandler.async_step_init
(self, user_input=None)
Manage the ONVIF options.
Manage the ONVIF options.
async def async_step_init(self, user_input=None): """Manage the ONVIF options.""" return await self.async_step_onvif_devices()
[ "async", "def", "async_step_init", "(", "self", ",", "user_input", "=", "None", ")", ":", "return", "await", "self", ".", "async_step_onvif_devices", "(", ")" ]
[ 285, 4 ]
[ 287, 52 ]
python
en
['en', 'en', 'en']
True
OnvifOptionsFlowHandler.async_step_onvif_devices
(self, user_input=None)
Manage the ONVIF devices options.
Manage the ONVIF devices options.
async def async_step_onvif_devices(self, user_input=None): """Manage the ONVIF devices options.""" if user_input is not None: self.options[CONF_EXTRA_ARGUMENTS] = user_input[CONF_EXTRA_ARGUMENTS] self.options[CONF_RTSP_TRANSPORT] = user_input[CONF_RTSP_TRANSPORT] return self.async_create_entry(title="", data=self.options) return self.async_show_form( step_id="onvif_devices", data_schema=vol.Schema( { vol.Optional( CONF_EXTRA_ARGUMENTS, default=self.config_entry.options.get( CONF_EXTRA_ARGUMENTS, DEFAULT_ARGUMENTS ), ): str, vol.Optional( CONF_RTSP_TRANSPORT, default=self.config_entry.options.get( CONF_RTSP_TRANSPORT, RTSP_TRANS_PROTOCOLS[0] ), ): vol.In(RTSP_TRANS_PROTOCOLS), } ), )
[ "async", "def", "async_step_onvif_devices", "(", "self", ",", "user_input", "=", "None", ")", ":", "if", "user_input", "is", "not", "None", ":", "self", ".", "options", "[", "CONF_EXTRA_ARGUMENTS", "]", "=", "user_input", "[", "CONF_EXTRA_ARGUMENTS", "]", "self", ".", "options", "[", "CONF_RTSP_TRANSPORT", "]", "=", "user_input", "[", "CONF_RTSP_TRANSPORT", "]", "return", "self", ".", "async_create_entry", "(", "title", "=", "\"\"", ",", "data", "=", "self", ".", "options", ")", "return", "self", ".", "async_show_form", "(", "step_id", "=", "\"onvif_devices\"", ",", "data_schema", "=", "vol", ".", "Schema", "(", "{", "vol", ".", "Optional", "(", "CONF_EXTRA_ARGUMENTS", ",", "default", "=", "self", ".", "config_entry", ".", "options", ".", "get", "(", "CONF_EXTRA_ARGUMENTS", ",", "DEFAULT_ARGUMENTS", ")", ",", ")", ":", "str", ",", "vol", ".", "Optional", "(", "CONF_RTSP_TRANSPORT", ",", "default", "=", "self", ".", "config_entry", ".", "options", ".", "get", "(", "CONF_RTSP_TRANSPORT", ",", "RTSP_TRANS_PROTOCOLS", "[", "0", "]", ")", ",", ")", ":", "vol", ".", "In", "(", "RTSP_TRANS_PROTOCOLS", ")", ",", "}", ")", ",", ")" ]
[ 289, 4 ]
[ 314, 9 ]
python
en
['en', 'en', 'en']
True
setup_platform
(hass, config, add_entities, discovery_info=None)
Set up the Radarr platform.
Set up the Radarr platform.
def setup_platform(hass, config, add_entities, discovery_info=None): """Set up the Radarr platform.""" conditions = config.get(CONF_MONITORED_CONDITIONS) add_entities([RadarrSensor(hass, config, sensor) for sensor in conditions], True)
[ "def", "setup_platform", "(", "hass", ",", "config", ",", "add_entities", ",", "discovery_info", "=", "None", ")", ":", "conditions", "=", "config", ".", "get", "(", "CONF_MONITORED_CONDITIONS", ")", "add_entities", "(", "[", "RadarrSensor", "(", "hass", ",", "config", ",", "sensor", ")", "for", "sensor", "in", "conditions", "]", ",", "True", ")" ]
[ 91, 0 ]
[ 94, 85 ]
python
en
['en', 'pt', 'en']
True
get_date
(zone, offset=0)
Get date based on timezone and offset of days.
Get date based on timezone and offset of days.
def get_date(zone, offset=0): """Get date based on timezone and offset of days.""" day = 60 * 60 * 24 return datetime.date(datetime.fromtimestamp(time.time() + day * offset, tz=zone))
[ "def", "get_date", "(", "zone", ",", "offset", "=", "0", ")", ":", "day", "=", "60", "*", "60", "*", "24", "return", "datetime", ".", "date", "(", "datetime", ".", "fromtimestamp", "(", "time", ".", "time", "(", ")", "+", "day", "*", "offset", ",", "tz", "=", "zone", ")", ")" ]
[ 218, 0 ]
[ 221, 85 ]
python
en
['en', 'en', 'en']
True
get_release_date
(data)
Get release date.
Get release date.
def get_release_date(data): """Get release date.""" date = data.get("physicalRelease") if not date: date = data.get("inCinemas") return date
[ "def", "get_release_date", "(", "data", ")", ":", "date", "=", "data", ".", "get", "(", "\"physicalRelease\"", ")", "if", "not", "date", ":", "date", "=", "data", ".", "get", "(", "\"inCinemas\"", ")", "return", "date" ]
[ 224, 0 ]
[ 229, 15 ]
python
en
['en', 'nl', 'en']
True
to_unit
(value, unit)
Convert bytes to give unit.
Convert bytes to give unit.
def to_unit(value, unit): """Convert bytes to give unit.""" return value / 1024 ** BYTE_SIZES.index(unit)
[ "def", "to_unit", "(", "value", ",", "unit", ")", ":", "return", "value", "/", "1024", "**", "BYTE_SIZES", ".", "index", "(", "unit", ")" ]
[ 237, 0 ]
[ 239, 49 ]
python
en
['en', 'en', 'en']
True
RadarrSensor.__init__
(self, hass, conf, sensor_type)
Create Radarr entity.
Create Radarr entity.
def __init__(self, hass, conf, sensor_type): """Create Radarr entity.""" self.conf = conf self.host = conf.get(CONF_HOST) self.port = conf.get(CONF_PORT) self.urlbase = conf.get(CONF_URLBASE) if self.urlbase: self.urlbase = f"{self.urlbase.strip('/')}/" self.apikey = conf.get(CONF_API_KEY) self.included = conf.get(CONF_INCLUDED) self.days = int(conf.get(CONF_DAYS)) self.ssl = "https" if conf.get(CONF_SSL) else "http" self._state = None self.data = [] self._tz = timezone(str(hass.config.time_zone)) self.type = sensor_type self._name = SENSOR_TYPES[self.type][0] if self.type == "diskspace": self._unit = conf.get(CONF_UNIT) else: self._unit = SENSOR_TYPES[self.type][1] self._icon = SENSOR_TYPES[self.type][2] self._available = False
[ "def", "__init__", "(", "self", ",", "hass", ",", "conf", ",", "sensor_type", ")", ":", "self", ".", "conf", "=", "conf", "self", ".", "host", "=", "conf", ".", "get", "(", "CONF_HOST", ")", "self", ".", "port", "=", "conf", ".", "get", "(", "CONF_PORT", ")", "self", ".", "urlbase", "=", "conf", ".", "get", "(", "CONF_URLBASE", ")", "if", "self", ".", "urlbase", ":", "self", ".", "urlbase", "=", "f\"{self.urlbase.strip('/')}/\"", "self", ".", "apikey", "=", "conf", ".", "get", "(", "CONF_API_KEY", ")", "self", ".", "included", "=", "conf", ".", "get", "(", "CONF_INCLUDED", ")", "self", ".", "days", "=", "int", "(", "conf", ".", "get", "(", "CONF_DAYS", ")", ")", "self", ".", "ssl", "=", "\"https\"", "if", "conf", ".", "get", "(", "CONF_SSL", ")", "else", "\"http\"", "self", ".", "_state", "=", "None", "self", ".", "data", "=", "[", "]", "self", ".", "_tz", "=", "timezone", "(", "str", "(", "hass", ".", "config", ".", "time_zone", ")", ")", "self", ".", "type", "=", "sensor_type", "self", ".", "_name", "=", "SENSOR_TYPES", "[", "self", ".", "type", "]", "[", "0", "]", "if", "self", ".", "type", "==", "\"diskspace\"", ":", "self", ".", "_unit", "=", "conf", ".", "get", "(", "CONF_UNIT", ")", "else", ":", "self", ".", "_unit", "=", "SENSOR_TYPES", "[", "self", ".", "type", "]", "[", "1", "]", "self", ".", "_icon", "=", "SENSOR_TYPES", "[", "self", ".", "type", "]", "[", "2", "]", "self", ".", "_available", "=", "False" ]
[ 100, 4 ]
[ 123, 31 ]
python
cy
['es', 'cy', 'en']
False
RadarrSensor.name
(self)
Return the name of the sensor.
Return the name of the sensor.
def name(self): """Return the name of the sensor.""" return "{} {}".format("Radarr", self._name)
[ "def", "name", "(", "self", ")", ":", "return", "\"{} {}\"", ".", "format", "(", "\"Radarr\"", ",", "self", ".", "_name", ")" ]
[ 126, 4 ]
[ 128, 51 ]
python
en
['en', 'mi', 'en']
True
RadarrSensor.state
(self)
Return sensor state.
Return sensor state.
def state(self): """Return sensor state.""" return self._state
[ "def", "state", "(", "self", ")", ":", "return", "self", ".", "_state" ]
[ 131, 4 ]
[ 133, 26 ]
python
en
['en', 'bs', 'en']
True
RadarrSensor.available
(self)
Return sensor availability.
Return sensor availability.
def available(self): """Return sensor availability.""" return self._available
[ "def", "available", "(", "self", ")", ":", "return", "self", ".", "_available" ]
[ 136, 4 ]
[ 138, 30 ]
python
en
['fr', 'ga', 'en']
False
RadarrSensor.unit_of_measurement
(self)
Return the unit of the sensor.
Return the unit of the sensor.
def unit_of_measurement(self): """Return the unit of the sensor.""" return self._unit
[ "def", "unit_of_measurement", "(", "self", ")", ":", "return", "self", ".", "_unit" ]
[ 141, 4 ]
[ 143, 25 ]
python
en
['en', 'sq', 'en']
True
RadarrSensor.device_state_attributes
(self)
Return the state attributes of the sensor.
Return the state attributes of the sensor.
def device_state_attributes(self): """Return the state attributes of the sensor.""" attributes = {} if self.type == "upcoming": for movie in self.data: attributes[to_key(movie)] = get_release_date(movie) elif self.type == "commands": for command in self.data: attributes[command["name"]] = command["state"] elif self.type == "diskspace": for data in self.data: free_space = to_unit(data["freeSpace"], self._unit) total_space = to_unit(data["totalSpace"], self._unit) percentage_used = ( 0 if total_space == 0 else free_space / total_space * 100 ) attributes[data["path"]] = "{:.2f}/{:.2f}{} ({:.2f}%)".format( free_space, total_space, self._unit, percentage_used ) elif self.type == "movies": for movie in self.data: attributes[to_key(movie)] = movie["downloaded"] elif self.type == "status": attributes = self.data return attributes
[ "def", "device_state_attributes", "(", "self", ")", ":", "attributes", "=", "{", "}", "if", "self", ".", "type", "==", "\"upcoming\"", ":", "for", "movie", "in", "self", ".", "data", ":", "attributes", "[", "to_key", "(", "movie", ")", "]", "=", "get_release_date", "(", "movie", ")", "elif", "self", ".", "type", "==", "\"commands\"", ":", "for", "command", "in", "self", ".", "data", ":", "attributes", "[", "command", "[", "\"name\"", "]", "]", "=", "command", "[", "\"state\"", "]", "elif", "self", ".", "type", "==", "\"diskspace\"", ":", "for", "data", "in", "self", ".", "data", ":", "free_space", "=", "to_unit", "(", "data", "[", "\"freeSpace\"", "]", ",", "self", ".", "_unit", ")", "total_space", "=", "to_unit", "(", "data", "[", "\"totalSpace\"", "]", ",", "self", ".", "_unit", ")", "percentage_used", "=", "(", "0", "if", "total_space", "==", "0", "else", "free_space", "/", "total_space", "*", "100", ")", "attributes", "[", "data", "[", "\"path\"", "]", "]", "=", "\"{:.2f}/{:.2f}{} ({:.2f}%)\"", ".", "format", "(", "free_space", ",", "total_space", ",", "self", ".", "_unit", ",", "percentage_used", ")", "elif", "self", ".", "type", "==", "\"movies\"", ":", "for", "movie", "in", "self", ".", "data", ":", "attributes", "[", "to_key", "(", "movie", ")", "]", "=", "movie", "[", "\"downloaded\"", "]", "elif", "self", ".", "type", "==", "\"status\"", ":", "attributes", "=", "self", ".", "data", "return", "attributes" ]
[ 146, 4 ]
[ 171, 25 ]
python
en
['en', 'en', 'en']
True
RadarrSensor.icon
(self)
Return the icon of the sensor.
Return the icon of the sensor.
def icon(self): """Return the icon of the sensor.""" return self._icon
[ "def", "icon", "(", "self", ")", ":", "return", "self", ".", "_icon" ]
[ 174, 4 ]
[ 176, 25 ]
python
en
['en', 'en', 'en']
True
RadarrSensor.update
(self)
Update the data for the sensor.
Update the data for the sensor.
def update(self): """Update the data for the sensor.""" start = get_date(self._tz) end = get_date(self._tz, self.days) try: res = requests.get( ENDPOINTS[self.type].format( self.ssl, self.host, self.port, self.urlbase, start, end ), headers={"X-Api-Key": self.apikey}, timeout=10, ) except OSError: _LOGGER.warning("Host %s is not available", self.host) self._available = False self._state = None return if res.status_code == HTTP_OK: if self.type in ["upcoming", "movies", "commands"]: self.data = res.json() self._state = len(self.data) elif self.type == "diskspace": # If included paths are not provided, use all data if self.included == []: self.data = res.json() else: # Filter to only show lists that are included self.data = list( filter(lambda x: x["path"] in self.included, res.json()) ) self._state = "{:.2f}".format( to_unit(sum([data["freeSpace"] for data in self.data]), self._unit) ) elif self.type == "status": self.data = res.json() self._state = self.data["version"] self._available = True
[ "def", "update", "(", "self", ")", ":", "start", "=", "get_date", "(", "self", ".", "_tz", ")", "end", "=", "get_date", "(", "self", ".", "_tz", ",", "self", ".", "days", ")", "try", ":", "res", "=", "requests", ".", "get", "(", "ENDPOINTS", "[", "self", ".", "type", "]", ".", "format", "(", "self", ".", "ssl", ",", "self", ".", "host", ",", "self", ".", "port", ",", "self", ".", "urlbase", ",", "start", ",", "end", ")", ",", "headers", "=", "{", "\"X-Api-Key\"", ":", "self", ".", "apikey", "}", ",", "timeout", "=", "10", ",", ")", "except", "OSError", ":", "_LOGGER", ".", "warning", "(", "\"Host %s is not available\"", ",", "self", ".", "host", ")", "self", ".", "_available", "=", "False", "self", ".", "_state", "=", "None", "return", "if", "res", ".", "status_code", "==", "HTTP_OK", ":", "if", "self", ".", "type", "in", "[", "\"upcoming\"", ",", "\"movies\"", ",", "\"commands\"", "]", ":", "self", ".", "data", "=", "res", ".", "json", "(", ")", "self", ".", "_state", "=", "len", "(", "self", ".", "data", ")", "elif", "self", ".", "type", "==", "\"diskspace\"", ":", "# If included paths are not provided, use all data", "if", "self", ".", "included", "==", "[", "]", ":", "self", ".", "data", "=", "res", ".", "json", "(", ")", "else", ":", "# Filter to only show lists that are included", "self", ".", "data", "=", "list", "(", "filter", "(", "lambda", "x", ":", "x", "[", "\"path\"", "]", "in", "self", ".", "included", ",", "res", ".", "json", "(", ")", ")", ")", "self", ".", "_state", "=", "\"{:.2f}\"", ".", "format", "(", "to_unit", "(", "sum", "(", "[", "data", "[", "\"freeSpace\"", "]", "for", "data", "in", "self", ".", "data", "]", ")", ",", "self", ".", "_unit", ")", ")", "elif", "self", ".", "type", "==", "\"status\"", ":", "self", ".", "data", "=", "res", ".", "json", "(", ")", "self", ".", "_state", "=", "self", ".", "data", "[", "\"version\"", "]", "self", ".", "_available", "=", "True" ]
[ 178, 4 ]
[ 215, 34 ]
python
en
['en', 'no', 'en']
True
load_corpus
(name, download=True)
Loads and wrangles the passed in text corpus by name. If download is specified, this method will download any missing files. Note: This function is slightly different to the `load_data` function used above to load pandas dataframes into memory.
Loads and wrangles the passed in text corpus by name. If download is specified, this method will download any missing files.
def load_corpus(name, download=True): """ Loads and wrangles the passed in text corpus by name. If download is specified, this method will download any missing files. Note: This function is slightly different to the `load_data` function used above to load pandas dataframes into memory. """ # Get the path from the datasets path = corpora[name] # Check if the data exists, otherwise download or raise if not os.path.exists(path): raise ValueError(( "'{}' dataset has not been downloaded, " "use the download.py module to fetch datasets" ).format(name)) # Read the directories in the directory as the categories. categories = [ cat for cat in os.listdir(path) if os.path.isdir(os.path.join(path, cat)) ] files = [] # holds the file names relative to the root data = [] # holds the text read from the file target = [] # holds the string of the category # Load the data from the files in the corpus for cat in categories: for name in os.listdir(os.path.join(path, cat)): files.append(os.path.join(path, cat, name)) target.append(cat) with open(os.path.join(path, cat, name), 'r') as f: data.append(f.read()) # Return the data bunch for use similar to the newsgroups example return Bunch( categories=categories, files=files, data=data, target=target, )
[ "def", "load_corpus", "(", "name", ",", "download", "=", "True", ")", ":", "# Get the path from the datasets", "path", "=", "corpora", "[", "name", "]", "# Check if the data exists, otherwise download or raise", "if", "not", "os", ".", "path", ".", "exists", "(", "path", ")", ":", "raise", "ValueError", "(", "(", "\"'{}' dataset has not been downloaded, \"", "\"use the download.py module to fetch datasets\"", ")", ".", "format", "(", "name", ")", ")", "# Read the directories in the directory as the categories.", "categories", "=", "[", "cat", "for", "cat", "in", "os", ".", "listdir", "(", "path", ")", "if", "os", ".", "path", ".", "isdir", "(", "os", ".", "path", ".", "join", "(", "path", ",", "cat", ")", ")", "]", "files", "=", "[", "]", "# holds the file names relative to the root", "data", "=", "[", "]", "# holds the text read from the file", "target", "=", "[", "]", "# holds the string of the category", "# Load the data from the files in the corpus", "for", "cat", "in", "categories", ":", "for", "name", "in", "os", ".", "listdir", "(", "os", ".", "path", ".", "join", "(", "path", ",", "cat", ")", ")", ":", "files", ".", "append", "(", "os", ".", "path", ".", "join", "(", "path", ",", "cat", ",", "name", ")", ")", "target", ".", "append", "(", "cat", ")", "with", "open", "(", "os", ".", "path", ".", "join", "(", "path", ",", "cat", ",", "name", ")", ",", "'r'", ")", "as", "f", ":", "data", ".", "append", "(", "f", ".", "read", "(", ")", ")", "# Return the data bunch for use similar to the newsgroups example", "return", "Bunch", "(", "categories", "=", "categories", ",", "files", "=", "files", ",", "data", "=", "data", ",", "target", "=", "target", ",", ")" ]
[ 16, 0 ]
[ 60, 5 ]
python
en
['en', 'error', 'th']
False
HTMLCorpusReader.__init__
(self, root, fileids=DOC_PATTERN, encoding='utf8', tags=TAGS, **kwargs)
Initialize the corpus reader. Categorization arguments (``cat_pattern``, ``cat_map``, and ``cat_file``) are passed to the ``CategorizedCorpusReader`` constructor. The remaining arguments are passed to the ``CorpusReader`` constructor.
Initialize the corpus reader. Categorization arguments (``cat_pattern``, ``cat_map``, and ``cat_file``) are passed to the ``CategorizedCorpusReader`` constructor. The remaining arguments are passed to the ``CorpusReader`` constructor.
def __init__(self, root, fileids=DOC_PATTERN, encoding='utf8', tags=TAGS, **kwargs): """ Initialize the corpus reader. Categorization arguments (``cat_pattern``, ``cat_map``, and ``cat_file``) are passed to the ``CategorizedCorpusReader`` constructor. The remaining arguments are passed to the ``CorpusReader`` constructor. """ # Add the default category pattern if not passed into the class. if not any(key.startswith('cat_') for key in kwargs.keys()): kwargs['cat_pattern'] = CAT_PATTERN # Initialize the NLTK corpus reader objects CategorizedCorpusReader.__init__(self, kwargs) CorpusReader.__init__(self, root, fileids, encoding) # Save the tags that we specifically want to extract. self.tags = tags
[ "def", "__init__", "(", "self", ",", "root", ",", "fileids", "=", "DOC_PATTERN", ",", "encoding", "=", "'utf8'", ",", "tags", "=", "TAGS", ",", "*", "*", "kwargs", ")", ":", "# Add the default category pattern if not passed into the class.", "if", "not", "any", "(", "key", ".", "startswith", "(", "'cat_'", ")", "for", "key", "in", "kwargs", ".", "keys", "(", ")", ")", ":", "kwargs", "[", "'cat_pattern'", "]", "=", "CAT_PATTERN", "# Initialize the NLTK corpus reader objects", "CategorizedCorpusReader", ".", "__init__", "(", "self", ",", "kwargs", ")", "CorpusReader", ".", "__init__", "(", "self", ",", "root", ",", "fileids", ",", "encoding", ")", "# Save the tags that we specifically want to extract.", "self", ".", "tags", "=", "tags" ]
[ 30, 4 ]
[ 47, 24 ]
python
en
['en', 'error', 'th']
False
HTMLCorpusReader.resolve
(self, fileids, categories)
Returns a list of fileids or categories depending on what is passed to each internal corpus reader function. Implemented similarly to the NLTK ``CategorizedPlaintextCorpusReader``.
Returns a list of fileids or categories depending on what is passed to each internal corpus reader function. Implemented similarly to the NLTK ``CategorizedPlaintextCorpusReader``.
def resolve(self, fileids, categories): """ Returns a list of fileids or categories depending on what is passed to each internal corpus reader function. Implemented similarly to the NLTK ``CategorizedPlaintextCorpusReader``. """ if fileids is not None and categories is not None: raise ValueError("Specify fileids or categories, not both") if categories is not None: return self.fileids(categories) return fileids
[ "def", "resolve", "(", "self", ",", "fileids", ",", "categories", ")", ":", "if", "fileids", "is", "not", "None", "and", "categories", "is", "not", "None", ":", "raise", "ValueError", "(", "\"Specify fileids or categories, not both\"", ")", "if", "categories", "is", "not", "None", ":", "return", "self", ".", "fileids", "(", "categories", ")", "return", "fileids" ]
[ 49, 4 ]
[ 60, 22 ]
python
en
['en', 'error', 'th']
False
HTMLCorpusReader.docs
(self, fileids=None, categories=None)
Returns the complete text of an HTML document, closing the document after we are done reading it and yielding it in a memory safe fashion.
Returns the complete text of an HTML document, closing the document after we are done reading it and yielding it in a memory safe fashion.
def docs(self, fileids=None, categories=None): """ Returns the complete text of an HTML document, closing the document after we are done reading it and yielding it in a memory safe fashion. """ # Resolve the fileids and the categories fileids = self.resolve(fileids, categories) # Create a generator, loading one document into memory at a time. for path, encoding in self.abspaths(fileids, include_encoding=True): with codecs.open(path, 'r', encoding=encoding) as f: yield f.read()
[ "def", "docs", "(", "self", ",", "fileids", "=", "None", ",", "categories", "=", "None", ")", ":", "# Resolve the fileids and the categories", "fileids", "=", "self", ".", "resolve", "(", "fileids", ",", "categories", ")", "# Create a generator, loading one document into memory at a time.", "for", "path", ",", "encoding", "in", "self", ".", "abspaths", "(", "fileids", ",", "include_encoding", "=", "True", ")", ":", "with", "codecs", ".", "open", "(", "path", ",", "'r'", ",", "encoding", "=", "encoding", ")", "as", "f", ":", "yield", "f", ".", "read", "(", ")" ]
[ 62, 4 ]
[ 73, 30 ]
python
en
['en', 'error', 'th']
False
HTMLCorpusReader.sizes
(self, fileids=None, categories=None)
Returns a list of tuples, the fileid and size on disk of the file. This function is used to detect oddly large files in the corpus.
Returns a list of tuples, the fileid and size on disk of the file. This function is used to detect oddly large files in the corpus.
def sizes(self, fileids=None, categories=None): """ Returns a list of tuples, the fileid and size on disk of the file. This function is used to detect oddly large files in the corpus. """ # Resolve the fileids and the categories fileids = self.resolve(fileids, categories) # Create a generator, getting every path and computing filesize for path in self.abspaths(fileids): yield os.path.getsize(path)
[ "def", "sizes", "(", "self", ",", "fileids", "=", "None", ",", "categories", "=", "None", ")", ":", "# Resolve the fileids and the categories", "fileids", "=", "self", ".", "resolve", "(", "fileids", ",", "categories", ")", "# Create a generator, getting every path and computing filesize", "for", "path", "in", "self", ".", "abspaths", "(", "fileids", ")", ":", "yield", "os", ".", "path", ".", "getsize", "(", "path", ")" ]
[ 75, 4 ]
[ 85, 39 ]
python
en
['en', 'error', 'th']
False
HTMLCorpusReader.html
(self, fileids=None, categories=None)
Returns the HTML content of each document, cleaning it using the readability-lxml library.
Returns the HTML content of each document, cleaning it using the readability-lxml library.
def html(self, fileids=None, categories=None): """ Returns the HTML content of each document, cleaning it using the readability-lxml library. """ for doc in self.docs(fileids, categories): try: yield Paper(doc).summary() except Unparseable as e: print("Could not parse HTML: {}".format(e)) continue
[ "def", "html", "(", "self", ",", "fileids", "=", "None", ",", "categories", "=", "None", ")", ":", "for", "doc", "in", "self", ".", "docs", "(", "fileids", ",", "categories", ")", ":", "try", ":", "yield", "Paper", "(", "doc", ")", ".", "summary", "(", ")", "except", "Unparseable", "as", "e", ":", "print", "(", "\"Could not parse HTML: {}\"", ".", "format", "(", "e", ")", ")", "continue" ]
[ 87, 4 ]
[ 97, 24 ]
python
en
['en', 'error', 'th']
False
HTMLCorpusReader.paras
(self, fileids=None, categories=None)
Uses BeautifulSoup to parse the paragraphs from the HTML.
Uses BeautifulSoup to parse the paragraphs from the HTML.
def paras(self, fileids=None, categories=None): """ Uses BeautifulSoup to parse the paragraphs from the HTML. """ for html in self.html(fileids, categories): soup = bs4.BeautifulSoup(html, 'lxml') for element in soup.find_all(self.tags): yield element.text soup.decompose()
[ "def", "paras", "(", "self", ",", "fileids", "=", "None", ",", "categories", "=", "None", ")", ":", "for", "html", "in", "self", ".", "html", "(", "fileids", ",", "categories", ")", ":", "soup", "=", "bs4", ".", "BeautifulSoup", "(", "html", ",", "'lxml'", ")", "for", "element", "in", "soup", ".", "find_all", "(", "self", ".", "tags", ")", ":", "yield", "element", ".", "text", "soup", ".", "decompose", "(", ")" ]
[ 99, 4 ]
[ 107, 28 ]
python
en
['en', 'error', 'th']
False
HTMLCorpusReader.sents
(self, fileids=None, categories=None)
Uses the built in sentence tokenizer to extract sentences from the paragraphs. Note that this method uses BeautifulSoup to parse HTML.
Uses the built in sentence tokenizer to extract sentences from the paragraphs. Note that this method uses BeautifulSoup to parse HTML.
def sents(self, fileids=None, categories=None): """ Uses the built in sentence tokenizer to extract sentences from the paragraphs. Note that this method uses BeautifulSoup to parse HTML. """ for paragraph in self.paras(fileids, categories): for sentence in sent_tokenize(paragraph): yield sentence
[ "def", "sents", "(", "self", ",", "fileids", "=", "None", ",", "categories", "=", "None", ")", ":", "for", "paragraph", "in", "self", ".", "paras", "(", "fileids", ",", "categories", ")", ":", "for", "sentence", "in", "sent_tokenize", "(", "paragraph", ")", ":", "yield", "sentence" ]
[ 109, 4 ]
[ 116, 30 ]
python
en
['en', 'error', 'th']
False
HTMLCorpusReader.words
(self, fileids=None, categories=None)
Uses the built in word tokenizer to extract tokens from sentences. Note that this method uses BeautifulSoup to parse HTML content.
Uses the built in word tokenizer to extract tokens from sentences. Note that this method uses BeautifulSoup to parse HTML content.
def words(self, fileids=None, categories=None): """ Uses the built in word tokenizer to extract tokens from sentences. Note that this method uses BeautifulSoup to parse HTML content. """ for sentence in self.sents(fileids, categories): for token in wordpunct_tokenize(sentence): yield token
[ "def", "words", "(", "self", ",", "fileids", "=", "None", ",", "categories", "=", "None", ")", ":", "for", "sentence", "in", "self", ".", "sents", "(", "fileids", ",", "categories", ")", ":", "for", "token", "in", "wordpunct_tokenize", "(", "sentence", ")", ":", "yield", "token" ]
[ 118, 4 ]
[ 125, 27 ]
python
en
['en', 'error', 'th']
False
HTMLCorpusReader.tokenize
(self, fileids=None, categories=None)
Segments, tokenizes, and tags a document in the corpus.
Segments, tokenizes, and tags a document in the corpus.
def tokenize(self, fileids=None, categories=None): """ Segments, tokenizes, and tags a document in the corpus. """ for paragraph in self.paras(fileids, categories): yield [ pos_tag(wordpunct_tokenize(sent)) for sent in sent_tokenize(paragraph) ]
[ "def", "tokenize", "(", "self", ",", "fileids", "=", "None", ",", "categories", "=", "None", ")", ":", "for", "paragraph", "in", "self", ".", "paras", "(", "fileids", ",", "categories", ")", ":", "yield", "[", "pos_tag", "(", "wordpunct_tokenize", "(", "sent", ")", ")", "for", "sent", "in", "sent_tokenize", "(", "paragraph", ")", "]" ]
[ 127, 4 ]
[ 135, 13 ]
python
en
['en', 'error', 'th']
False
HTMLCorpusReader.describe
(self, fileids=None, categories=None)
Performs a single pass of the corpus and returns a dictionary with a variety of metrics concerning the state of the corpus.
Performs a single pass of the corpus and returns a dictionary with a variety of metrics concerning the state of the corpus.
def describe(self, fileids=None, categories=None): """ Performs a single pass of the corpus and returns a dictionary with a variety of metrics concerning the state of the corpus. """ started = time.time() # Structures to perform counting. counts = nltk.FreqDist() tokens = nltk.FreqDist() # Perform single pass over paragraphs, tokenize and count for para in self.paras(fileids, categories): counts['paras'] += 1 for sent in sent_tokenize(para): counts['sents'] += 1 for word in wordpunct_tokenize(sent): counts['words'] += 1 tokens[word] += 1 # Compute the number of files and categories in the corpus n_fileids = len(self.resolve(fileids, categories) or self.fileids()) n_topics = len(self.categories(self.resolve(fileids, categories))) # Return data structure with information return { 'files': n_fileids, 'topics': n_topics, 'paras': counts['paras'], 'sents': counts['sents'], 'words': counts['words'], 'vocab': len(tokens), 'lexdiv': float(counts['words']) / float(len(tokens)), 'ppdoc': float(counts['paras']) / float(n_fileids), 'sppar': float(counts['sents']) / float(counts['paras']), 'secs': time.time() - started, }
[ "def", "describe", "(", "self", ",", "fileids", "=", "None", ",", "categories", "=", "None", ")", ":", "started", "=", "time", ".", "time", "(", ")", "# Structures to perform counting.", "counts", "=", "nltk", ".", "FreqDist", "(", ")", "tokens", "=", "nltk", ".", "FreqDist", "(", ")", "# Perform single pass over paragraphs, tokenize and count", "for", "para", "in", "self", ".", "paras", "(", "fileids", ",", "categories", ")", ":", "counts", "[", "'paras'", "]", "+=", "1", "for", "sent", "in", "sent_tokenize", "(", "para", ")", ":", "counts", "[", "'sents'", "]", "+=", "1", "for", "word", "in", "wordpunct_tokenize", "(", "sent", ")", ":", "counts", "[", "'words'", "]", "+=", "1", "tokens", "[", "word", "]", "+=", "1", "# Compute the number of files and categories in the corpus", "n_fileids", "=", "len", "(", "self", ".", "resolve", "(", "fileids", ",", "categories", ")", "or", "self", ".", "fileids", "(", ")", ")", "n_topics", "=", "len", "(", "self", ".", "categories", "(", "self", ".", "resolve", "(", "fileids", ",", "categories", ")", ")", ")", "# Return data structure with information", "return", "{", "'files'", ":", "n_fileids", ",", "'topics'", ":", "n_topics", ",", "'paras'", ":", "counts", "[", "'paras'", "]", ",", "'sents'", ":", "counts", "[", "'sents'", "]", ",", "'words'", ":", "counts", "[", "'words'", "]", ",", "'vocab'", ":", "len", "(", "tokens", ")", ",", "'lexdiv'", ":", "float", "(", "counts", "[", "'words'", "]", ")", "/", "float", "(", "len", "(", "tokens", ")", ")", ",", "'ppdoc'", ":", "float", "(", "counts", "[", "'paras'", "]", ")", "/", "float", "(", "n_fileids", ")", ",", "'sppar'", ":", "float", "(", "counts", "[", "'sents'", "]", ")", "/", "float", "(", "counts", "[", "'paras'", "]", ")", ",", "'secs'", ":", "time", ".", "time", "(", ")", "-", "started", ",", "}" ]
[ 137, 4 ]
[ 176, 9 ]
python
en
['en', 'error', 'th']
False
PickledCorpusReader.__init__
(self, root, fileids=PKL_PATTERN, **kwargs)
Initialize the corpus reader. Categorization arguments (``cat_pattern``, ``cat_map``, and ``cat_file``) are passed to the ``CategorizedCorpusReader`` constructor. The remaining arguments are passed to the ``CorpusReader`` constructor.
Initialize the corpus reader. Categorization arguments (``cat_pattern``, ``cat_map``, and ``cat_file``) are passed to the ``CategorizedCorpusReader`` constructor. The remaining arguments are passed to the ``CorpusReader`` constructor.
def __init__(self, root, fileids=PKL_PATTERN, **kwargs): """ Initialize the corpus reader. Categorization arguments (``cat_pattern``, ``cat_map``, and ``cat_file``) are passed to the ``CategorizedCorpusReader`` constructor. The remaining arguments are passed to the ``CorpusReader`` constructor. """ # Add the default category pattern if not passed into the class. if not any(key.startswith('cat_') for key in kwargs.keys()): kwargs['cat_pattern'] = CAT_PATTERN CategorizedCorpusReader.__init__(self, kwargs) CorpusReader.__init__(self, root, fileids)
[ "def", "__init__", "(", "self", ",", "root", ",", "fileids", "=", "PKL_PATTERN", ",", "*", "*", "kwargs", ")", ":", "# Add the default category pattern if not passed into the class.", "if", "not", "any", "(", "key", ".", "startswith", "(", "'cat_'", ")", "for", "key", "in", "kwargs", ".", "keys", "(", ")", ")", ":", "kwargs", "[", "'cat_pattern'", "]", "=", "CAT_PATTERN", "CategorizedCorpusReader", ".", "__init__", "(", "self", ",", "kwargs", ")", "CorpusReader", ".", "__init__", "(", "self", ",", "root", ",", "fileids", ")" ]
[ 181, 4 ]
[ 193, 50 ]
python
en
['en', 'error', 'th']
False
PickledCorpusReader.resolve
(self, fileids, categories)
Returns a list of fileids or categories depending on what is passed to each internal corpus reader function. This primarily bubbles up to the high level ``docs`` method, but is implemented here similar to the nltk ``CategorizedPlaintextCorpusReader``.
Returns a list of fileids or categories depending on what is passed to each internal corpus reader function. This primarily bubbles up to the high level ``docs`` method, but is implemented here similar to the nltk ``CategorizedPlaintextCorpusReader``.
def resolve(self, fileids, categories): """ Returns a list of fileids or categories depending on what is passed to each internal corpus reader function. This primarily bubbles up to the high level ``docs`` method, but is implemented here similar to the nltk ``CategorizedPlaintextCorpusReader``. """ if fileids is not None and categories is not None: raise ValueError("Specify fileids or categories, not both") if categories is not None: return self.fileids(categories) return fileids
[ "def", "resolve", "(", "self", ",", "fileids", ",", "categories", ")", ":", "if", "fileids", "is", "not", "None", "and", "categories", "is", "not", "None", ":", "raise", "ValueError", "(", "\"Specify fileids or categories, not both\"", ")", "if", "categories", "is", "not", "None", ":", "return", "self", ".", "fileids", "(", "categories", ")", "return", "fileids" ]
[ 195, 4 ]
[ 207, 22 ]
python
en
['en', 'error', 'th']
False
PickledCorpusReader.docs
(self, fileids=None, categories=None)
Returns the document loaded from a pickled object for every file in the corpus. Similar to the BaleenCorpusReader, this uses a generator to acheive memory safe iteration.
Returns the document loaded from a pickled object for every file in the corpus. Similar to the BaleenCorpusReader, this uses a generator to acheive memory safe iteration.
def docs(self, fileids=None, categories=None): """ Returns the document loaded from a pickled object for every file in the corpus. Similar to the BaleenCorpusReader, this uses a generator to acheive memory safe iteration. """ # Resolve the fileids and the categories fileids = self.resolve(fileids, categories) # Create a generator, loading one document into memory at a time. for path, enc, fileid in self.abspaths(fileids, True, True): with open(path, 'rb') as f: yield pickle.load(f)
[ "def", "docs", "(", "self", ",", "fileids", "=", "None", ",", "categories", "=", "None", ")", ":", "# Resolve the fileids and the categories", "fileids", "=", "self", ".", "resolve", "(", "fileids", ",", "categories", ")", "# Create a generator, loading one document into memory at a time.", "for", "path", ",", "enc", ",", "fileid", "in", "self", ".", "abspaths", "(", "fileids", ",", "True", ",", "True", ")", ":", "with", "open", "(", "path", ",", "'rb'", ")", "as", "f", ":", "yield", "pickle", ".", "load", "(", "f", ")" ]
[ 209, 4 ]
[ 221, 36 ]
python
en
['en', 'error', 'th']
False
PickledCorpusReader.paras
(self, fileids=None, categories=None)
Returns a generator of paragraphs where each paragraph is a list of sentences, which is in turn a list of (token, tag) tuples.
Returns a generator of paragraphs where each paragraph is a list of sentences, which is in turn a list of (token, tag) tuples.
def paras(self, fileids=None, categories=None): """ Returns a generator of paragraphs where each paragraph is a list of sentences, which is in turn a list of (token, tag) tuples. """ for doc in self.docs(fileids, categories): for paragraph in doc: yield paragraph
[ "def", "paras", "(", "self", ",", "fileids", "=", "None", ",", "categories", "=", "None", ")", ":", "for", "doc", "in", "self", ".", "docs", "(", "fileids", ",", "categories", ")", ":", "for", "paragraph", "in", "doc", ":", "yield", "paragraph" ]
[ 223, 4 ]
[ 230, 31 ]
python
en
['en', 'error', 'th']
False
PickledCorpusReader.sents
(self, fileids=None, categories=None)
Returns a generator of sentences where each sentence is a list of (token, tag) tuples.
Returns a generator of sentences where each sentence is a list of (token, tag) tuples.
def sents(self, fileids=None, categories=None): """ Returns a generator of sentences where each sentence is a list of (token, tag) tuples. """ for paragraph in self.paras(fileids, categories): for sentence in paragraph: yield sentence
[ "def", "sents", "(", "self", ",", "fileids", "=", "None", ",", "categories", "=", "None", ")", ":", "for", "paragraph", "in", "self", ".", "paras", "(", "fileids", ",", "categories", ")", ":", "for", "sentence", "in", "paragraph", ":", "yield", "sentence" ]
[ 232, 4 ]
[ 239, 30 ]
python
en
['en', 'error', 'th']
False
PickledCorpusReader.words
(self, fileids=None, categories=None)
Returns a generator of (token, tag) tuples.
Returns a generator of (token, tag) tuples.
def words(self, fileids=None, categories=None): """ Returns a generator of (token, tag) tuples. """ for token in self.tagged(fileids, categories): yield token[0]
[ "def", "words", "(", "self", ",", "fileids", "=", "None", ",", "categories", "=", "None", ")", ":", "for", "token", "in", "self", ".", "tagged", "(", "fileids", ",", "categories", ")", ":", "yield", "token", "[", "0", "]" ]
[ 246, 4 ]
[ 251, 26 ]
python
en
['en', 'error', 'th']
False
conv2d
(x_input, w_matrix)
conv2d returns a 2d convolution layer with full stride.
conv2d returns a 2d convolution layer with full stride.
def conv2d(x_input, w_matrix): """conv2d returns a 2d convolution layer with full stride.""" return tf.nn.conv2d(x_input, w_matrix, strides=[1, 1, 1, 1], padding='SAME' )
[ "def", "conv2d", "(", "x_input", ",", "w_matrix", ")", ":", "return", "tf", ".", "nn", ".", "conv2d", "(", "x_input", ",", "w_matrix", ",", "strides", "=", "[", "1", ",", "1", ",", "1", ",", "1", "]", ",", "padding", "=", "'SAME'", ")" ]
[ 104, 0 ]
[ 107, 9 ]
python
en
['en', 'en', 'en']
True
max_pool
(x_input, pool_size)
max_pool downsamples a feature map by 2X.
max_pool downsamples a feature map by 2X.
def max_pool(x_input, pool_size): """max_pool downsamples a feature map by 2X.""" return tf.nn.max_pool(x_input, ksize=[1, pool_size, pool_size, 1], strides=[1, pool_size, pool_size, 1], padding='SAME')
[ "def", "max_pool", "(", "x_input", ",", "pool_size", ")", ":", "return", "tf", ".", "nn", ".", "max_pool", "(", "x_input", ",", "ksize", "=", "[", "1", ",", "pool_size", ",", "pool_size", ",", "1", "]", ",", "strides", "=", "[", "1", ",", "pool_size", ",", "pool_size", ",", "1", "]", ",", "padding", "=", "'SAME'", ")" ]
[ 110, 0 ]
[ 113, 61 ]
python
en
['en', 'en', 'en']
True
weight_variable
(shape)
weight_variable generates a weight variable of a given shape.
weight_variable generates a weight variable of a given shape.
def weight_variable(shape): """weight_variable generates a weight variable of a given shape.""" initial = tf.truncated_normal(shape, stddev=0.1) return tf.Variable(initial)
[ "def", "weight_variable", "(", "shape", ")", ":", "initial", "=", "tf", ".", "truncated_normal", "(", "shape", ",", "stddev", "=", "0.1", ")", "return", "tf", ".", "Variable", "(", "initial", ")" ]
[ 121, 0 ]
[ 124, 31 ]
python
en
['en', 'en', 'en']
True
bias_variable
(shape)
bias_variable generates a bias variable of a given shape.
bias_variable generates a bias variable of a given shape.
def bias_variable(shape): """bias_variable generates a bias variable of a given shape.""" initial = tf.constant(0.1, shape=shape) return tf.Variable(initial)
[ "def", "bias_variable", "(", "shape", ")", ":", "initial", "=", "tf", ".", "constant", "(", "0.1", ",", "shape", "=", "shape", ")", "return", "tf", ".", "Variable", "(", "initial", ")" ]
[ 127, 0 ]
[ 130, 31 ]
python
en
['en', 'en', 'en']
True
download_mnist_retry
(data_dir, max_num_retries=20)
Try to download mnist dataset and avoid errors
Try to download mnist dataset and avoid errors
def download_mnist_retry(data_dir, max_num_retries=20): """Try to download mnist dataset and avoid errors""" for _ in range(max_num_retries): try: return input_data.read_data_sets(data_dir, one_hot=True) except tf.errors.AlreadyExistsError: time.sleep(1) raise Exception("Failed to download MNIST.")
[ "def", "download_mnist_retry", "(", "data_dir", ",", "max_num_retries", "=", "20", ")", ":", "for", "_", "in", "range", "(", "max_num_retries", ")", ":", "try", ":", "return", "input_data", ".", "read_data_sets", "(", "data_dir", ",", "one_hot", "=", "True", ")", "except", "tf", ".", "errors", ".", "AlreadyExistsError", ":", "time", ".", "sleep", "(", "1", ")", "raise", "Exception", "(", "\"Failed to download MNIST.\"", ")" ]
[ 132, 0 ]
[ 139, 48 ]
python
en
['en', 'en', 'en']
True
main
(params)
Main function, build mnist network, run and send result to NNI.
Main function, build mnist network, run and send result to NNI.
def main(params): """ Main function, build mnist network, run and send result to NNI. """
[ "def", "main", "(", "params", ")", ":" ]
[ 141, 0 ]
[ 144, 7 ]
python
en
['en', 'error', 'th']
False
generate_defualt_params
()
Generate default parameters for mnist network.
Generate default parameters for mnist network.
def generate_defualt_params(): """ Generate default parameters for mnist network. """ params = {'data_dir': '/tmp/tensorflow/mnist/input_data', 'dropout_rate': 0.5, 'channel_1_num': 32, 'channel_2_num': 64, 'conv_size': 5, 'pool_size': 2, 'hidden_size': 1024, 'learning_rate': 0.0001, 'batch_num': 200} return params
[ "def", "generate_defualt_params", "(", ")", ":", "params", "=", "{", "'data_dir'", ":", "'/tmp/tensorflow/mnist/input_data'", ",", "'dropout_rate'", ":", "0.5", ",", "'channel_1_num'", ":", "32", ",", "'channel_2_num'", ":", "64", ",", "'conv_size'", ":", "5", ",", "'pool_size'", ":", "2", ",", "'hidden_size'", ":", "1024", ",", "'learning_rate'", ":", "0.0001", ",", "'batch_num'", ":", "200", "}", "return", "params" ]
[ 186, 0 ]
[ 194, 17 ]
python
en
['en', 'error', 'th']
False
MnistNetwork.build_network
(self)
Building network for mnist
Building network for mnist
def build_network(self): """ Building network for mnist """ with tf.name_scope('reshape'): try: input_dim = int(math.sqrt(self.x_dim)) except: print('input dim cannot be sqrt and reshape. input dim: ' + str(self.x_dim)) logger.debug( 'input dim cannot be sqrt and reshape. input dim: %s', str(self.x_dim)) raise x_image = tf.reshape(self.images, [-1, input_dim, input_dim, 1]) with tf.name_scope('conv1'): w_conv1 = weight_variable([self.conv_size, self.conv_size, 1, self.channel_1_num]) b_conv1 = bias_variable([self.channel_1_num]) h_conv1 = nni.function_choice(lambda : tf.nn.relu(conv2d( x_image, w_conv1) + b_conv1), lambda : tf.nn.sigmoid(conv2d (x_image, w_conv1) + b_conv1), lambda : tf.nn.tanh(conv2d( x_image, w_conv1) + b_conv1), name='tf.nn.relu') with tf.name_scope('pool1'): h_pool1 = nni.function_choice(lambda : max_pool(h_conv1, self. pool_size), lambda : avg_pool(h_conv1, self.pool_size), name='max_pool') with tf.name_scope('conv2'): w_conv2 = weight_variable([self.conv_size, self.conv_size, self .channel_1_num, self.channel_2_num]) b_conv2 = bias_variable([self.channel_2_num]) h_conv2 = tf.nn.relu(conv2d(h_pool1, w_conv2) + b_conv2) with tf.name_scope('pool2'): h_pool2 = max_pool(h_conv2, self.pool_size) last_dim = int(input_dim / (self.pool_size * self.pool_size)) with tf.name_scope('fc1'): w_fc1 = weight_variable([last_dim * last_dim * self. channel_2_num, self.hidden_size]) b_fc1 = bias_variable([self.hidden_size]) h_pool2_flat = tf.reshape(h_pool2, [-1, last_dim * last_dim * self. channel_2_num]) h_fc1 = tf.nn.relu(tf.matmul(h_pool2_flat, w_fc1) + b_fc1) with tf.name_scope('dropout'): h_fc1_drop = tf.nn.dropout(h_fc1, self.keep_prob) with tf.name_scope('fc2'): w_fc2 = weight_variable([self.hidden_size, self.y_dim]) b_fc2 = bias_variable([self.y_dim]) y_conv = tf.matmul(h_fc1_drop, w_fc2) + b_fc2 with tf.name_scope('loss'): cross_entropy = tf.reduce_mean(tf.nn. softmax_cross_entropy_with_logits(labels=self.labels, logits=y_conv)) with tf.name_scope('adam_optimizer'): self.train_step = tf.train.AdamOptimizer(self.learning_rate ).minimize(cross_entropy) with tf.name_scope('accuracy'): correct_prediction = tf.equal(tf.argmax(y_conv, 1), tf.argmax( self.labels, 1)) self.accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf. float32))
[ "def", "build_network", "(", "self", ")", ":", "with", "tf", ".", "name_scope", "(", "'reshape'", ")", ":", "try", ":", "input_dim", "=", "int", "(", "math", ".", "sqrt", "(", "self", ".", "x_dim", ")", ")", "except", ":", "print", "(", "'input dim cannot be sqrt and reshape. input dim: '", "+", "str", "(", "self", ".", "x_dim", ")", ")", "logger", ".", "debug", "(", "'input dim cannot be sqrt and reshape. input dim: %s'", ",", "str", "(", "self", ".", "x_dim", ")", ")", "raise", "x_image", "=", "tf", ".", "reshape", "(", "self", ".", "images", ",", "[", "-", "1", ",", "input_dim", ",", "input_dim", ",", "1", "]", ")", "with", "tf", ".", "name_scope", "(", "'conv1'", ")", ":", "w_conv1", "=", "weight_variable", "(", "[", "self", ".", "conv_size", ",", "self", ".", "conv_size", ",", "1", ",", "self", ".", "channel_1_num", "]", ")", "b_conv1", "=", "bias_variable", "(", "[", "self", ".", "channel_1_num", "]", ")", "h_conv1", "=", "nni", ".", "function_choice", "(", "lambda", ":", "tf", ".", "nn", ".", "relu", "(", "conv2d", "(", "x_image", ",", "w_conv1", ")", "+", "b_conv1", ")", ",", "lambda", ":", "tf", ".", "nn", ".", "sigmoid", "(", "conv2d", "(", "x_image", ",", "w_conv1", ")", "+", "b_conv1", ")", ",", "lambda", ":", "tf", ".", "nn", ".", "tanh", "(", "conv2d", "(", "x_image", ",", "w_conv1", ")", "+", "b_conv1", ")", ",", "name", "=", "'tf.nn.relu'", ")", "with", "tf", ".", "name_scope", "(", "'pool1'", ")", ":", "h_pool1", "=", "nni", ".", "function_choice", "(", "lambda", ":", "max_pool", "(", "h_conv1", ",", "self", ".", "pool_size", ")", ",", "lambda", ":", "avg_pool", "(", "h_conv1", ",", "self", ".", "pool_size", ")", ",", "name", "=", "'max_pool'", ")", "with", "tf", ".", "name_scope", "(", "'conv2'", ")", ":", "w_conv2", "=", "weight_variable", "(", "[", "self", ".", "conv_size", ",", "self", ".", "conv_size", ",", "self", ".", "channel_1_num", ",", "self", ".", "channel_2_num", "]", ")", "b_conv2", "=", "bias_variable", "(", "[", "self", ".", "channel_2_num", "]", ")", "h_conv2", "=", "tf", ".", "nn", ".", "relu", "(", "conv2d", "(", "h_pool1", ",", "w_conv2", ")", "+", "b_conv2", ")", "with", "tf", ".", "name_scope", "(", "'pool2'", ")", ":", "h_pool2", "=", "max_pool", "(", "h_conv2", ",", "self", ".", "pool_size", ")", "last_dim", "=", "int", "(", "input_dim", "/", "(", "self", ".", "pool_size", "*", "self", ".", "pool_size", ")", ")", "with", "tf", ".", "name_scope", "(", "'fc1'", ")", ":", "w_fc1", "=", "weight_variable", "(", "[", "last_dim", "*", "last_dim", "*", "self", ".", "channel_2_num", ",", "self", ".", "hidden_size", "]", ")", "b_fc1", "=", "bias_variable", "(", "[", "self", ".", "hidden_size", "]", ")", "h_pool2_flat", "=", "tf", ".", "reshape", "(", "h_pool2", ",", "[", "-", "1", ",", "last_dim", "*", "last_dim", "*", "self", ".", "channel_2_num", "]", ")", "h_fc1", "=", "tf", ".", "nn", ".", "relu", "(", "tf", ".", "matmul", "(", "h_pool2_flat", ",", "w_fc1", ")", "+", "b_fc1", ")", "with", "tf", ".", "name_scope", "(", "'dropout'", ")", ":", "h_fc1_drop", "=", "tf", ".", "nn", ".", "dropout", "(", "h_fc1", ",", "self", ".", "keep_prob", ")", "with", "tf", ".", "name_scope", "(", "'fc2'", ")", ":", "w_fc2", "=", "weight_variable", "(", "[", "self", ".", "hidden_size", ",", "self", ".", "y_dim", "]", ")", "b_fc2", "=", "bias_variable", "(", "[", "self", ".", "y_dim", "]", ")", "y_conv", "=", "tf", ".", "matmul", "(", "h_fc1_drop", ",", "w_fc2", ")", "+", "b_fc2", "with", "tf", ".", "name_scope", "(", "'loss'", ")", ":", "cross_entropy", "=", "tf", ".", "reduce_mean", "(", "tf", ".", "nn", ".", "softmax_cross_entropy_with_logits", "(", "labels", "=", "self", ".", "labels", ",", "logits", "=", "y_conv", ")", ")", "with", "tf", ".", "name_scope", "(", "'adam_optimizer'", ")", ":", "self", ".", "train_step", "=", "tf", ".", "train", ".", "AdamOptimizer", "(", "self", ".", "learning_rate", ")", ".", "minimize", "(", "cross_entropy", ")", "with", "tf", ".", "name_scope", "(", "'accuracy'", ")", ":", "correct_prediction", "=", "tf", ".", "equal", "(", "tf", ".", "argmax", "(", "y_conv", ",", "1", ")", ",", "tf", ".", "argmax", "(", "self", ".", "labels", ",", "1", ")", ")", "self", ".", "accuracy", "=", "tf", ".", "reduce_mean", "(", "tf", ".", "cast", "(", "correct_prediction", ",", "tf", ".", "float32", ")", ")" ]
[ 42, 4 ]
[ 101, 25 ]
python
en
['en', 'error', 'th']
False
async_setup_platform
(hass, config, async_add_entities, discovery_info=None)
Set up an InComfort/InTouch climate device.
Set up an InComfort/InTouch climate device.
async def async_setup_platform(hass, config, async_add_entities, discovery_info=None): """Set up an InComfort/InTouch climate device.""" if discovery_info is None: return client = hass.data[DOMAIN]["client"] heaters = hass.data[DOMAIN]["heaters"] async_add_entities( [InComfortClimate(client, h, r) for h in heaters for r in h.rooms] )
[ "async", "def", "async_setup_platform", "(", "hass", ",", "config", ",", "async_add_entities", ",", "discovery_info", "=", "None", ")", ":", "if", "discovery_info", "is", "None", ":", "return", "client", "=", "hass", ".", "data", "[", "DOMAIN", "]", "[", "\"client\"", "]", "heaters", "=", "hass", ".", "data", "[", "DOMAIN", "]", "[", "\"heaters\"", "]", "async_add_entities", "(", "[", "InComfortClimate", "(", "client", ",", "h", ",", "r", ")", "for", "h", "in", "heaters", "for", "r", "in", "h", ".", "rooms", "]", ")" ]
[ 13, 0 ]
[ 23, 5 ]
python
en
['en', 'en', 'en']
True
InComfortClimate.__init__
(self, client, heater, room)
Initialize the climate device.
Initialize the climate device.
def __init__(self, client, heater, room) -> None: """Initialize the climate device.""" super().__init__() self._unique_id = f"{heater.serial_no}_{room.room_no}" self.entity_id = f"{CLIMATE_DOMAIN}.{DOMAIN}_{room.room_no}" self._name = f"Thermostat {room.room_no}" self._client = client self._room = room
[ "def", "__init__", "(", "self", ",", "client", ",", "heater", ",", "room", ")", "->", "None", ":", "super", "(", ")", ".", "__init__", "(", ")", "self", ".", "_unique_id", "=", "f\"{heater.serial_no}_{room.room_no}\"", "self", ".", "entity_id", "=", "f\"{CLIMATE_DOMAIN}.{DOMAIN}_{room.room_no}\"", "self", ".", "_name", "=", "f\"Thermostat {room.room_no}\"", "self", ".", "_client", "=", "client", "self", ".", "_room", "=", "room" ]
[ 29, 4 ]
[ 38, 25 ]
python
en
['en', 'en', 'en']
True
InComfortClimate.device_state_attributes
(self)
Return the device state attributes.
Return the device state attributes.
def device_state_attributes(self) -> Dict[str, Any]: """Return the device state attributes.""" return {"status": self._room.status}
[ "def", "device_state_attributes", "(", "self", ")", "->", "Dict", "[", "str", ",", "Any", "]", ":", "return", "{", "\"status\"", ":", "self", ".", "_room", ".", "status", "}" ]
[ 41, 4 ]
[ 43, 44 ]
python
en
['en', 'en', 'en']
True
InComfortClimate.temperature_unit
(self)
Return the unit of measurement.
Return the unit of measurement.
def temperature_unit(self) -> str: """Return the unit of measurement.""" return TEMP_CELSIUS
[ "def", "temperature_unit", "(", "self", ")", "->", "str", ":", "return", "TEMP_CELSIUS" ]
[ 46, 4 ]
[ 48, 27 ]
python
en
['en', 'la', 'en']
True
InComfortClimate.hvac_mode
(self)
Return hvac operation ie. heat, cool mode.
Return hvac operation ie. heat, cool mode.
def hvac_mode(self) -> str: """Return hvac operation ie. heat, cool mode.""" return HVAC_MODE_HEAT
[ "def", "hvac_mode", "(", "self", ")", "->", "str", ":", "return", "HVAC_MODE_HEAT" ]
[ 51, 4 ]
[ 53, 29 ]
python
bg
['en', 'bg', 'bg']
True
InComfortClimate.hvac_modes
(self)
Return the list of available hvac operation modes.
Return the list of available hvac operation modes.
def hvac_modes(self) -> List[str]: """Return the list of available hvac operation modes.""" return [HVAC_MODE_HEAT]
[ "def", "hvac_modes", "(", "self", ")", "->", "List", "[", "str", "]", ":", "return", "[", "HVAC_MODE_HEAT", "]" ]
[ 56, 4 ]
[ 58, 31 ]
python
en
['en', 'en', 'en']
True
InComfortClimate.current_temperature
(self)
Return the current temperature.
Return the current temperature.
def current_temperature(self) -> Optional[float]: """Return the current temperature.""" return self._room.room_temp
[ "def", "current_temperature", "(", "self", ")", "->", "Optional", "[", "float", "]", ":", "return", "self", ".", "_room", ".", "room_temp" ]
[ 61, 4 ]
[ 63, 35 ]
python
en
['en', 'la', 'en']
True
InComfortClimate.target_temperature
(self)
Return the temperature we try to reach.
Return the temperature we try to reach.
def target_temperature(self) -> Optional[float]: """Return the temperature we try to reach.""" return self._room.setpoint
[ "def", "target_temperature", "(", "self", ")", "->", "Optional", "[", "float", "]", ":", "return", "self", ".", "_room", ".", "setpoint" ]
[ 66, 4 ]
[ 68, 34 ]
python
en
['en', 'en', 'en']
True
InComfortClimate.supported_features
(self)
Return the list of supported features.
Return the list of supported features.
def supported_features(self) -> int: """Return the list of supported features.""" return SUPPORT_TARGET_TEMPERATURE
[ "def", "supported_features", "(", "self", ")", "->", "int", ":", "return", "SUPPORT_TARGET_TEMPERATURE" ]
[ 71, 4 ]
[ 73, 41 ]
python
en
['en', 'en', 'en']
True
InComfortClimate.min_temp
(self)
Return max valid temperature that can be set.
Return max valid temperature that can be set.
def min_temp(self) -> float: """Return max valid temperature that can be set.""" return 5.0
[ "def", "min_temp", "(", "self", ")", "->", "float", ":", "return", "5.0" ]
[ 76, 4 ]
[ 78, 18 ]
python
en
['en', 'en', 'en']
True
InComfortClimate.max_temp
(self)
Return max valid temperature that can be set.
Return max valid temperature that can be set.
def max_temp(self) -> float: """Return max valid temperature that can be set.""" return 30.0
[ "def", "max_temp", "(", "self", ")", "->", "float", ":", "return", "30.0" ]
[ 81, 4 ]
[ 83, 19 ]
python
en
['en', 'en', 'en']
True
InComfortClimate.async_set_temperature
(self, **kwargs)
Set a new target temperature for this zone.
Set a new target temperature for this zone.
async def async_set_temperature(self, **kwargs) -> None: """Set a new target temperature for this zone.""" temperature = kwargs.get(ATTR_TEMPERATURE) await self._room.set_override(temperature)
[ "async", "def", "async_set_temperature", "(", "self", ",", "*", "*", "kwargs", ")", "->", "None", ":", "temperature", "=", "kwargs", ".", "get", "(", "ATTR_TEMPERATURE", ")", "await", "self", ".", "_room", ".", "set_override", "(", "temperature", ")" ]
[ 85, 4 ]
[ 88, 50 ]
python
en
['en', 'en', 'en']
True
InComfortClimate.async_set_hvac_mode
(self, hvac_mode: str)
Set new target hvac mode.
Set new target hvac mode.
async def async_set_hvac_mode(self, hvac_mode: str) -> None: """Set new target hvac mode."""
[ "async", "def", "async_set_hvac_mode", "(", "self", ",", "hvac_mode", ":", "str", ")", "->", "None", ":" ]
[ 90, 4 ]
[ 91, 39 ]
python
da
['da', 'su', 'en']
False
test_matching_url
()
Test we can match urls.
Test we can match urls.
async def test_matching_url(): """Test we can match urls.""" mocker = AiohttpClientMocker() mocker.get("http://example.com") await mocker.match_request("get", "http://example.com/") mocker.clear_requests() with pytest.raises(AssertionError): await mocker.match_request("get", "http://example.com/") mocker.clear_requests() mocker.get("http://example.com?a=1") await mocker.match_request("get", "http://example.com/", params={"a": 1, "b": 2})
[ "async", "def", "test_matching_url", "(", ")", ":", "mocker", "=", "AiohttpClientMocker", "(", ")", "mocker", ".", "get", "(", "\"http://example.com\"", ")", "await", "mocker", ".", "match_request", "(", "\"get\"", ",", "\"http://example.com/\"", ")", "mocker", ".", "clear_requests", "(", ")", "with", "pytest", ".", "raises", "(", "AssertionError", ")", ":", "await", "mocker", ".", "match_request", "(", "\"get\"", ",", "\"http://example.com/\"", ")", "mocker", ".", "clear_requests", "(", ")", "mocker", ".", "get", "(", "\"http://example.com?a=1\"", ")", "await", "mocker", ".", "match_request", "(", "\"get\"", ",", "\"http://example.com/\"", ",", "params", "=", "{", "\"a\"", ":", "1", ",", "\"b\"", ":", "2", "}", ")" ]
[ 6, 0 ]
[ 20, 85 ]
python
en
['en', 'lb', 'en']
True
validate_sql_select
(value)
Validate that value is a SQL SELECT query.
Validate that value is a SQL SELECT query.
def validate_sql_select(value): """Validate that value is a SQL SELECT query.""" if not value.lstrip().lower().startswith("select"): raise vol.Invalid("Only SELECT queries allowed") return value
[ "def", "validate_sql_select", "(", "value", ")", ":", "if", "not", "value", ".", "lstrip", "(", ")", ".", "lower", "(", ")", ".", "startswith", "(", "\"select\"", ")", ":", "raise", "vol", ".", "Invalid", "(", "\"Only SELECT queries allowed\"", ")", "return", "value" ]
[ 22, 0 ]
[ 26, 16 ]
python
en
['en', 'en', 'en']
True
setup_platform
(hass, config, add_entities, discovery_info=None)
Set up the SQL sensor platform.
Set up the SQL sensor platform.
def setup_platform(hass, config, add_entities, discovery_info=None): """Set up the SQL sensor platform.""" db_url = config.get(CONF_DB_URL) if not db_url: db_url = DEFAULT_URL.format(hass_config_path=hass.config.path(DEFAULT_DB_FILE)) try: engine = sqlalchemy.create_engine(db_url) sessmaker = scoped_session(sessionmaker(bind=engine)) # Run a dummy query just to test the db_url sess = sessmaker() sess.execute("SELECT 1;") except sqlalchemy.exc.SQLAlchemyError as err: _LOGGER.error("Couldn't connect using %s DB_URL: %s", db_url, err) return finally: sess.close() queries = [] for query in config.get(CONF_QUERIES): name = query.get(CONF_NAME) query_str = query.get(CONF_QUERY) unit = query.get(CONF_UNIT_OF_MEASUREMENT) value_template = query.get(CONF_VALUE_TEMPLATE) column_name = query.get(CONF_COLUMN_NAME) if value_template is not None: value_template.hass = hass sensor = SQLSensor( name, sessmaker, query_str, column_name, unit, value_template ) queries.append(sensor) add_entities(queries, True)
[ "def", "setup_platform", "(", "hass", ",", "config", ",", "add_entities", ",", "discovery_info", "=", "None", ")", ":", "db_url", "=", "config", ".", "get", "(", "CONF_DB_URL", ")", "if", "not", "db_url", ":", "db_url", "=", "DEFAULT_URL", ".", "format", "(", "hass_config_path", "=", "hass", ".", "config", ".", "path", "(", "DEFAULT_DB_FILE", ")", ")", "try", ":", "engine", "=", "sqlalchemy", ".", "create_engine", "(", "db_url", ")", "sessmaker", "=", "scoped_session", "(", "sessionmaker", "(", "bind", "=", "engine", ")", ")", "# Run a dummy query just to test the db_url", "sess", "=", "sessmaker", "(", ")", "sess", ".", "execute", "(", "\"SELECT 1;\"", ")", "except", "sqlalchemy", ".", "exc", ".", "SQLAlchemyError", "as", "err", ":", "_LOGGER", ".", "error", "(", "\"Couldn't connect using %s DB_URL: %s\"", ",", "db_url", ",", "err", ")", "return", "finally", ":", "sess", ".", "close", "(", ")", "queries", "=", "[", "]", "for", "query", "in", "config", ".", "get", "(", "CONF_QUERIES", ")", ":", "name", "=", "query", ".", "get", "(", "CONF_NAME", ")", "query_str", "=", "query", ".", "get", "(", "CONF_QUERY", ")", "unit", "=", "query", ".", "get", "(", "CONF_UNIT_OF_MEASUREMENT", ")", "value_template", "=", "query", ".", "get", "(", "CONF_VALUE_TEMPLATE", ")", "column_name", "=", "query", ".", "get", "(", "CONF_COLUMN_NAME", ")", "if", "value_template", "is", "not", "None", ":", "value_template", ".", "hass", "=", "hass", "sensor", "=", "SQLSensor", "(", "name", ",", "sessmaker", ",", "query_str", ",", "column_name", ",", "unit", ",", "value_template", ")", "queries", ".", "append", "(", "sensor", ")", "add_entities", "(", "queries", ",", "True", ")" ]
[ 44, 0 ]
[ 81, 31 ]
python
en
['en', 'da', 'en']
True
SQLSensor.__init__
(self, name, sessmaker, query, column, unit, value_template)
Initialize the SQL sensor.
Initialize the SQL sensor.
def __init__(self, name, sessmaker, query, column, unit, value_template): """Initialize the SQL sensor.""" self._name = name if "LIMIT" in query: self._query = query else: self._query = query.replace(";", " LIMIT 1;") self._unit_of_measurement = unit self._template = value_template self._column_name = column self.sessionmaker = sessmaker self._state = None self._attributes = None
[ "def", "__init__", "(", "self", ",", "name", ",", "sessmaker", ",", "query", ",", "column", ",", "unit", ",", "value_template", ")", ":", "self", ".", "_name", "=", "name", "if", "\"LIMIT\"", "in", "query", ":", "self", ".", "_query", "=", "query", "else", ":", "self", ".", "_query", "=", "query", ".", "replace", "(", "\";\"", ",", "\" LIMIT 1;\"", ")", "self", ".", "_unit_of_measurement", "=", "unit", "self", ".", "_template", "=", "value_template", "self", ".", "_column_name", "=", "column", "self", ".", "sessionmaker", "=", "sessmaker", "self", ".", "_state", "=", "None", "self", ".", "_attributes", "=", "None" ]
[ 87, 4 ]
[ 99, 31 ]
python
en
['en', 'pt', 'en']
True
SQLSensor.name
(self)
Return the name of the query.
Return the name of the query.
def name(self): """Return the name of the query.""" return self._name
[ "def", "name", "(", "self", ")", ":", "return", "self", ".", "_name" ]
[ 102, 4 ]
[ 104, 25 ]
python
en
['en', 'en', 'en']
True
SQLSensor.state
(self)
Return the query's current state.
Return the query's current state.
def state(self): """Return the query's current state.""" return self._state
[ "def", "state", "(", "self", ")", ":", "return", "self", ".", "_state" ]
[ 107, 4 ]
[ 109, 26 ]
python
en
['en', 'en', 'en']
True
SQLSensor.unit_of_measurement
(self)
Return the unit of measurement.
Return the unit of measurement.
def unit_of_measurement(self): """Return the unit of measurement.""" return self._unit_of_measurement
[ "def", "unit_of_measurement", "(", "self", ")", ":", "return", "self", ".", "_unit_of_measurement" ]
[ 112, 4 ]
[ 114, 40 ]
python
en
['en', 'la', 'en']
True
SQLSensor.device_state_attributes
(self)
Return the state attributes.
Return the state attributes.
def device_state_attributes(self): """Return the state attributes.""" return self._attributes
[ "def", "device_state_attributes", "(", "self", ")", ":", "return", "self", ".", "_attributes" ]
[ 117, 4 ]
[ 119, 31 ]
python
en
['en', 'en', 'en']
True
SQLSensor.update
(self)
Retrieve sensor data from the query.
Retrieve sensor data from the query.
def update(self): """Retrieve sensor data from the query.""" data = None try: sess = self.sessionmaker() result = sess.execute(self._query) self._attributes = {} if not result.returns_rows or result.rowcount == 0: _LOGGER.warning("%s returned no results", self._query) self._state = None return for res in result: _LOGGER.debug("result = %s", res.items()) data = res[self._column_name] for key, value in res.items(): if isinstance(value, decimal.Decimal): value = float(value) if isinstance(value, datetime.date): value = str(value) self._attributes[key] = value except sqlalchemy.exc.SQLAlchemyError as err: _LOGGER.error("Error executing query %s: %s", self._query, err) return finally: sess.close() if data is not None and self._template is not None: self._state = self._template.async_render_with_possible_json_value( data, None ) else: self._state = data
[ "def", "update", "(", "self", ")", ":", "data", "=", "None", "try", ":", "sess", "=", "self", ".", "sessionmaker", "(", ")", "result", "=", "sess", ".", "execute", "(", "self", ".", "_query", ")", "self", ".", "_attributes", "=", "{", "}", "if", "not", "result", ".", "returns_rows", "or", "result", ".", "rowcount", "==", "0", ":", "_LOGGER", ".", "warning", "(", "\"%s returned no results\"", ",", "self", ".", "_query", ")", "self", ".", "_state", "=", "None", "return", "for", "res", "in", "result", ":", "_LOGGER", ".", "debug", "(", "\"result = %s\"", ",", "res", ".", "items", "(", ")", ")", "data", "=", "res", "[", "self", ".", "_column_name", "]", "for", "key", ",", "value", "in", "res", ".", "items", "(", ")", ":", "if", "isinstance", "(", "value", ",", "decimal", ".", "Decimal", ")", ":", "value", "=", "float", "(", "value", ")", "if", "isinstance", "(", "value", ",", "datetime", ".", "date", ")", ":", "value", "=", "str", "(", "value", ")", "self", ".", "_attributes", "[", "key", "]", "=", "value", "except", "sqlalchemy", ".", "exc", ".", "SQLAlchemyError", "as", "err", ":", "_LOGGER", ".", "error", "(", "\"Error executing query %s: %s\"", ",", "self", ".", "_query", ",", "err", ")", "return", "finally", ":", "sess", ".", "close", "(", ")", "if", "data", "is", "not", "None", "and", "self", ".", "_template", "is", "not", "None", ":", "self", ".", "_state", "=", "self", ".", "_template", ".", "async_render_with_possible_json_value", "(", "data", ",", "None", ")", "else", ":", "self", ".", "_state", "=", "data" ]
[ 121, 4 ]
[ 155, 30 ]
python
en
['en', 'pt', 'en']
True
setup_platform
(hass, config, add_entities, discovery_info=None)
Set up the sensor platform.
Set up the sensor platform.
def setup_platform(hass, config, add_entities, discovery_info=None): """Set up the sensor platform.""" i2c_address = config.get(CONF_I2C_ADDRESS) sensor = SHT31(address=i2c_address) try: if sensor.read_status() is None: raise ValueError("CRC error while reading SHT31 status") except (OSError, ValueError): _LOGGER.error("SHT31 sensor not detected at address %s", hex(i2c_address)) return sensor_client = SHTClient(sensor) sensor_classes = { SENSOR_TEMPERATURE: SHTSensorTemperature, SENSOR_HUMIDITY: SHTSensorHumidity, } devs = [] for sensor_type, sensor_class in sensor_classes.items(): name = "{} {}".format(config.get(CONF_NAME), sensor_type.capitalize()) devs.append(sensor_class(sensor_client, name)) add_entities(devs)
[ "def", "setup_platform", "(", "hass", ",", "config", ",", "add_entities", ",", "discovery_info", "=", "None", ")", ":", "i2c_address", "=", "config", ".", "get", "(", "CONF_I2C_ADDRESS", ")", "sensor", "=", "SHT31", "(", "address", "=", "i2c_address", ")", "try", ":", "if", "sensor", ".", "read_status", "(", ")", "is", "None", ":", "raise", "ValueError", "(", "\"CRC error while reading SHT31 status\"", ")", "except", "(", "OSError", ",", "ValueError", ")", ":", "_LOGGER", ".", "error", "(", "\"SHT31 sensor not detected at address %s\"", ",", "hex", "(", "i2c_address", ")", ")", "return", "sensor_client", "=", "SHTClient", "(", "sensor", ")", "sensor_classes", "=", "{", "SENSOR_TEMPERATURE", ":", "SHTSensorTemperature", ",", "SENSOR_HUMIDITY", ":", "SHTSensorHumidity", ",", "}", "devs", "=", "[", "]", "for", "sensor_type", ",", "sensor_class", "in", "sensor_classes", ".", "items", "(", ")", ":", "name", "=", "\"{} {}\"", ".", "format", "(", "config", ".", "get", "(", "CONF_NAME", ")", ",", "sensor_type", ".", "capitalize", "(", ")", ")", "devs", ".", "append", "(", "sensor_class", "(", "sensor_client", ",", "name", ")", ")", "add_entities", "(", "devs", ")" ]
[ 48, 0 ]
[ 72, 22 ]
python
en
['en', 'da', 'en']
True
SHTClient.__init__
(self, adafruit_sht)
Initialize the sensor.
Initialize the sensor.
def __init__(self, adafruit_sht): """Initialize the sensor.""" self.adafruit_sht = adafruit_sht self.temperature = None self.humidity = None
[ "def", "__init__", "(", "self", ",", "adafruit_sht", ")", ":", "self", ".", "adafruit_sht", "=", "adafruit_sht", "self", ".", "temperature", "=", "None", "self", ".", "humidity", "=", "None" ]
[ 78, 4 ]
[ 82, 28 ]
python
en
['en', 'en', 'en']
True
SHTClient.update
(self)
Get the latest data from the SHT sensor.
Get the latest data from the SHT sensor.
def update(self): """Get the latest data from the SHT sensor.""" temperature, humidity = self.adafruit_sht.read_temperature_humidity() if math.isnan(temperature) or math.isnan(humidity): _LOGGER.warning("Bad sample from sensor SHT31") return self.temperature = temperature self.humidity = humidity
[ "def", "update", "(", "self", ")", ":", "temperature", ",", "humidity", "=", "self", ".", "adafruit_sht", ".", "read_temperature_humidity", "(", ")", "if", "math", ".", "isnan", "(", "temperature", ")", "or", "math", ".", "isnan", "(", "humidity", ")", ":", "_LOGGER", ".", "warning", "(", "\"Bad sample from sensor SHT31\"", ")", "return", "self", ".", "temperature", "=", "temperature", "self", ".", "humidity", "=", "humidity" ]
[ 85, 4 ]
[ 92, 32 ]
python
en
['en', 'en', 'en']
True
SHTSensor.__init__
(self, sensor, name)
Initialize the sensor.
Initialize the sensor.
def __init__(self, sensor, name): """Initialize the sensor.""" self._sensor = sensor self._name = name self._state = None
[ "def", "__init__", "(", "self", ",", "sensor", ",", "name", ")", ":", "self", ".", "_sensor", "=", "sensor", "self", ".", "_name", "=", "name", "self", ".", "_state", "=", "None" ]
[ 98, 4 ]
[ 102, 26 ]
python
en
['en', 'en', 'en']
True
SHTSensor.name
(self)
Return the name of the sensor.
Return the name of the sensor.
def name(self): """Return the name of the sensor.""" return self._name
[ "def", "name", "(", "self", ")", ":", "return", "self", ".", "_name" ]
[ 105, 4 ]
[ 107, 25 ]
python
en
['en', 'mi', 'en']
True
SHTSensor.state
(self)
Return the state of the sensor.
Return the state of the sensor.
def state(self): """Return the state of the sensor.""" return self._state
[ "def", "state", "(", "self", ")", ":", "return", "self", ".", "_state" ]
[ 110, 4 ]
[ 112, 26 ]
python
en
['en', 'en', 'en']
True
SHTSensor.update
(self)
Fetch temperature and humidity from the sensor.
Fetch temperature and humidity from the sensor.
def update(self): """Fetch temperature and humidity from the sensor.""" self._sensor.update()
[ "def", "update", "(", "self", ")", ":", "self", ".", "_sensor", ".", "update", "(", ")" ]
[ 114, 4 ]
[ 116, 29 ]
python
en
['en', 'en', 'en']
True
SHTSensorTemperature.unit_of_measurement
(self)
Return the unit of measurement.
Return the unit of measurement.
def unit_of_measurement(self): """Return the unit of measurement.""" return self.hass.config.units.temperature_unit
[ "def", "unit_of_measurement", "(", "self", ")", ":", "return", "self", ".", "hass", ".", "config", ".", "units", ".", "temperature_unit" ]
[ 123, 4 ]
[ 125, 54 ]
python
en
['en', 'la', 'en']
True
SHTSensorTemperature.update
(self)
Fetch temperature from the sensor.
Fetch temperature from the sensor.
def update(self): """Fetch temperature from the sensor.""" super().update() temp_celsius = self._sensor.temperature if temp_celsius is not None: self._state = display_temp( self.hass, temp_celsius, TEMP_CELSIUS, PRECISION_TENTHS )
[ "def", "update", "(", "self", ")", ":", "super", "(", ")", ".", "update", "(", ")", "temp_celsius", "=", "self", ".", "_sensor", ".", "temperature", "if", "temp_celsius", "is", "not", "None", ":", "self", ".", "_state", "=", "display_temp", "(", "self", ".", "hass", ",", "temp_celsius", ",", "TEMP_CELSIUS", ",", "PRECISION_TENTHS", ")" ]
[ 127, 4 ]
[ 134, 13 ]
python
en
['en', 'en', 'en']
True
SHTSensorHumidity.unit_of_measurement
(self)
Return the unit of measurement.
Return the unit of measurement.
def unit_of_measurement(self): """Return the unit of measurement.""" return PERCENTAGE
[ "def", "unit_of_measurement", "(", "self", ")", ":", "return", "PERCENTAGE" ]
[ 141, 4 ]
[ 143, 25 ]
python
en
['en', 'la', 'en']
True
SHTSensorHumidity.update
(self)
Fetch humidity from the sensor.
Fetch humidity from the sensor.
def update(self): """Fetch humidity from the sensor.""" super().update() humidity = self._sensor.humidity if humidity is not None: self._state = round(humidity)
[ "def", "update", "(", "self", ")", ":", "super", "(", ")", ".", "update", "(", ")", "humidity", "=", "self", ".", "_sensor", ".", "humidity", "if", "humidity", "is", "not", "None", ":", "self", ".", "_state", "=", "round", "(", "humidity", ")" ]
[ 145, 4 ]
[ 150, 41 ]
python
en
['en', 'en', 'en']
True
test_upload_image
(hass, hass_client, hass_ws_client)
Test we can upload an image.
Test we can upload an image.
async def test_upload_image(hass, hass_client, hass_ws_client): """Test we can upload an image.""" now = util_dt.utcnow() test_image = pathlib.Path(__file__).parent / "logo.png" with tempfile.TemporaryDirectory() as tempdir, patch.object( hass.config, "path", return_value=tempdir ), patch("homeassistant.util.dt.utcnow", return_value=now): assert await async_setup_component(hass, "image", {}) ws_client: ClientWebSocketResponse = await hass_ws_client() client: ClientSession = await hass_client() with test_image.open("rb") as fp: res = await client.post("/api/image/upload", data={"file": fp}) assert res.status == 200 item = await res.json() assert item["content_type"] == "image/png" assert item["filesize"] == 38847 assert item["name"] == "logo.png" assert item["uploaded_at"] == now.isoformat() tempdir = pathlib.Path(tempdir) item_folder: pathlib.Path = tempdir / item["id"] assert (item_folder / "original").read_bytes() == test_image.read_bytes() # fetch non-existing image res = await client.get("/api/image/serve/non-existing/256x256") assert res.status == 404 # fetch invalid sizes for inv_size in ("256", "256x25A", "100x100", "25Ax256"): res = await client.get(f"/api/image/serve/{item['id']}/{inv_size}") assert res.status == 400 # fetch resized version res = await client.get(f"/api/image/serve/{item['id']}/256x256") assert res.status == 200 assert (item_folder / "256x256").is_file() # List item await ws_client.send_json({"id": 6, "type": "image/list"}) msg = await ws_client.receive_json() assert msg["id"] == 6 assert msg["type"] == ws_const.TYPE_RESULT assert msg["success"] assert msg["result"] == [item] # Delete item await ws_client.send_json( {"id": 7, "type": "image/delete", "image_id": item["id"]} ) msg = await ws_client.receive_json() assert msg["id"] == 7 assert msg["type"] == ws_const.TYPE_RESULT assert msg["success"] # Ensure removed from disk assert not item_folder.is_dir()
[ "async", "def", "test_upload_image", "(", "hass", ",", "hass_client", ",", "hass_ws_client", ")", ":", "now", "=", "util_dt", ".", "utcnow", "(", ")", "test_image", "=", "pathlib", ".", "Path", "(", "__file__", ")", ".", "parent", "/", "\"logo.png\"", "with", "tempfile", ".", "TemporaryDirectory", "(", ")", "as", "tempdir", ",", "patch", ".", "object", "(", "hass", ".", "config", ",", "\"path\"", ",", "return_value", "=", "tempdir", ")", ",", "patch", "(", "\"homeassistant.util.dt.utcnow\"", ",", "return_value", "=", "now", ")", ":", "assert", "await", "async_setup_component", "(", "hass", ",", "\"image\"", ",", "{", "}", ")", "ws_client", ":", "ClientWebSocketResponse", "=", "await", "hass_ws_client", "(", ")", "client", ":", "ClientSession", "=", "await", "hass_client", "(", ")", "with", "test_image", ".", "open", "(", "\"rb\"", ")", "as", "fp", ":", "res", "=", "await", "client", ".", "post", "(", "\"/api/image/upload\"", ",", "data", "=", "{", "\"file\"", ":", "fp", "}", ")", "assert", "res", ".", "status", "==", "200", "item", "=", "await", "res", ".", "json", "(", ")", "assert", "item", "[", "\"content_type\"", "]", "==", "\"image/png\"", "assert", "item", "[", "\"filesize\"", "]", "==", "38847", "assert", "item", "[", "\"name\"", "]", "==", "\"logo.png\"", "assert", "item", "[", "\"uploaded_at\"", "]", "==", "now", ".", "isoformat", "(", ")", "tempdir", "=", "pathlib", ".", "Path", "(", "tempdir", ")", "item_folder", ":", "pathlib", ".", "Path", "=", "tempdir", "/", "item", "[", "\"id\"", "]", "assert", "(", "item_folder", "/", "\"original\"", ")", ".", "read_bytes", "(", ")", "==", "test_image", ".", "read_bytes", "(", ")", "# fetch non-existing image", "res", "=", "await", "client", ".", "get", "(", "\"/api/image/serve/non-existing/256x256\"", ")", "assert", "res", ".", "status", "==", "404", "# fetch invalid sizes", "for", "inv_size", "in", "(", "\"256\"", ",", "\"256x25A\"", ",", "\"100x100\"", ",", "\"25Ax256\"", ")", ":", "res", "=", "await", "client", ".", "get", "(", "f\"/api/image/serve/{item['id']}/{inv_size}\"", ")", "assert", "res", ".", "status", "==", "400", "# fetch resized version", "res", "=", "await", "client", ".", "get", "(", "f\"/api/image/serve/{item['id']}/256x256\"", ")", "assert", "res", ".", "status", "==", "200", "assert", "(", "item_folder", "/", "\"256x256\"", ")", ".", "is_file", "(", ")", "# List item", "await", "ws_client", ".", "send_json", "(", "{", "\"id\"", ":", "6", ",", "\"type\"", ":", "\"image/list\"", "}", ")", "msg", "=", "await", "ws_client", ".", "receive_json", "(", ")", "assert", "msg", "[", "\"id\"", "]", "==", "6", "assert", "msg", "[", "\"type\"", "]", "==", "ws_const", ".", "TYPE_RESULT", "assert", "msg", "[", "\"success\"", "]", "assert", "msg", "[", "\"result\"", "]", "==", "[", "item", "]", "# Delete item", "await", "ws_client", ".", "send_json", "(", "{", "\"id\"", ":", "7", ",", "\"type\"", ":", "\"image/delete\"", ",", "\"image_id\"", ":", "item", "[", "\"id\"", "]", "}", ")", "msg", "=", "await", "ws_client", ".", "receive_json", "(", ")", "assert", "msg", "[", "\"id\"", "]", "==", "7", "assert", "msg", "[", "\"type\"", "]", "==", "ws_const", ".", "TYPE_RESULT", "assert", "msg", "[", "\"success\"", "]", "# Ensure removed from disk", "assert", "not", "item_folder", ".", "is_dir", "(", ")" ]
[ 13, 0 ]
[ 75, 39 ]
python
en
['en', 'en', 'en']
True
do_tta_predict
(args, model, ckp_path, tta_num=4)
return 18000x128x128 np array
return 18000x128x128 np array
def do_tta_predict(args, model, ckp_path, tta_num=4): ''' return 18000x128x128 np array ''' model.eval() preds = [] meta = None # i is tta index, 0: no change, 1: horizon flip, 2: vertical flip, 3: do both for flip_index in range(tta_num): print('flip_index:', flip_index) test_loader = get_test_loader(args.batch_size, index=flip_index, dev_mode=False, pad_mode=args.pad_mode) meta = test_loader.meta outputs = None with torch.no_grad(): for i, img in enumerate(test_loader): add_depth_channel(img, args.pad_mode) img = img.cuda() output, _ = model(img) output = torch.sigmoid(output) if outputs is None: outputs = output.squeeze() else: outputs = torch.cat([outputs, output.squeeze()], 0) print('{} / {}'.format(args.batch_size*(i+1), test_loader.num), end='\r') outputs = outputs.cpu().numpy() # flip back masks if flip_index == 1: outputs = np.flip(outputs, 2) elif flip_index == 2: outputs = np.flip(outputs, 1) elif flip_index == 3: outputs = np.flip(outputs, 2) outputs = np.flip(outputs, 1) #print(outputs.shape) preds.append(outputs) parent_dir = ckp_path+'_out' if not os.path.exists(parent_dir): os.makedirs(parent_dir) np_file = os.path.join(parent_dir, 'pred.npy') model_pred_result = np.mean(preds, 0) np.save(np_file, model_pred_result) return model_pred_result, meta
[ "def", "do_tta_predict", "(", "args", ",", "model", ",", "ckp_path", ",", "tta_num", "=", "4", ")", ":", "model", ".", "eval", "(", ")", "preds", "=", "[", "]", "meta", "=", "None", "# i is tta index, 0: no change, 1: horizon flip, 2: vertical flip, 3: do both", "for", "flip_index", "in", "range", "(", "tta_num", ")", ":", "print", "(", "'flip_index:'", ",", "flip_index", ")", "test_loader", "=", "get_test_loader", "(", "args", ".", "batch_size", ",", "index", "=", "flip_index", ",", "dev_mode", "=", "False", ",", "pad_mode", "=", "args", ".", "pad_mode", ")", "meta", "=", "test_loader", ".", "meta", "outputs", "=", "None", "with", "torch", ".", "no_grad", "(", ")", ":", "for", "i", ",", "img", "in", "enumerate", "(", "test_loader", ")", ":", "add_depth_channel", "(", "img", ",", "args", ".", "pad_mode", ")", "img", "=", "img", ".", "cuda", "(", ")", "output", ",", "_", "=", "model", "(", "img", ")", "output", "=", "torch", ".", "sigmoid", "(", "output", ")", "if", "outputs", "is", "None", ":", "outputs", "=", "output", ".", "squeeze", "(", ")", "else", ":", "outputs", "=", "torch", ".", "cat", "(", "[", "outputs", ",", "output", ".", "squeeze", "(", ")", "]", ",", "0", ")", "print", "(", "'{} / {}'", ".", "format", "(", "args", ".", "batch_size", "*", "(", "i", "+", "1", ")", ",", "test_loader", ".", "num", ")", ",", "end", "=", "'\\r'", ")", "outputs", "=", "outputs", ".", "cpu", "(", ")", ".", "numpy", "(", ")", "# flip back masks", "if", "flip_index", "==", "1", ":", "outputs", "=", "np", ".", "flip", "(", "outputs", ",", "2", ")", "elif", "flip_index", "==", "2", ":", "outputs", "=", "np", ".", "flip", "(", "outputs", ",", "1", ")", "elif", "flip_index", "==", "3", ":", "outputs", "=", "np", ".", "flip", "(", "outputs", ",", "2", ")", "outputs", "=", "np", ".", "flip", "(", "outputs", ",", "1", ")", "#print(outputs.shape)", "preds", ".", "append", "(", "outputs", ")", "parent_dir", "=", "ckp_path", "+", "'_out'", "if", "not", "os", ".", "path", ".", "exists", "(", "parent_dir", ")", ":", "os", ".", "makedirs", "(", "parent_dir", ")", "np_file", "=", "os", ".", "path", ".", "join", "(", "parent_dir", ",", "'pred.npy'", ")", "model_pred_result", "=", "np", ".", "mean", "(", "preds", ",", "0", ")", "np", ".", "save", "(", "np_file", ",", "model_pred_result", ")", "return", "model_pred_result", ",", "meta" ]
[ 36, 0 ]
[ 82, 34 ]
python
en
['en', 'error', 'th']
False
UploadCommand.status
(s)
Prints things in bold.
Prints things in bold.
def status(s): """Prints things in bold.""" print("\033[1m{0}\033[0m".format(s))
[ "def", "status", "(", "s", ")", ":", "print", "(", "\"\\033[1m{0}\\033[0m\"", ".", "format", "(", "s", ")", ")" ]
[ 61, 4 ]
[ 63, 44 ]
python
en
['en', 'en', 'en']
True
register_flow_implementation
( hass, domain, client_id, client_secret, api_key, redirect_uri, sensors )
Register a flow implementation. domain: Domain of the component responsible for the implementation. client_id: Client ID. client_secret: Client secret. api_key: API key issued by Logitech. redirect_uri: Auth callback redirect URI. sensors: Sensor config.
Register a flow implementation.
def register_flow_implementation( hass, domain, client_id, client_secret, api_key, redirect_uri, sensors ): """Register a flow implementation. domain: Domain of the component responsible for the implementation. client_id: Client ID. client_secret: Client secret. api_key: API key issued by Logitech. redirect_uri: Auth callback redirect URI. sensors: Sensor config. """ if DATA_FLOW_IMPL not in hass.data: hass.data[DATA_FLOW_IMPL] = OrderedDict() hass.data[DATA_FLOW_IMPL][domain] = { CONF_CLIENT_ID: client_id, CONF_CLIENT_SECRET: client_secret, CONF_API_KEY: api_key, CONF_REDIRECT_URI: redirect_uri, CONF_SENSORS: sensors, EXTERNAL_ERRORS: None, }
[ "def", "register_flow_implementation", "(", "hass", ",", "domain", ",", "client_id", ",", "client_secret", ",", "api_key", ",", "redirect_uri", ",", "sensors", ")", ":", "if", "DATA_FLOW_IMPL", "not", "in", "hass", ".", "data", ":", "hass", ".", "data", "[", "DATA_FLOW_IMPL", "]", "=", "OrderedDict", "(", ")", "hass", ".", "data", "[", "DATA_FLOW_IMPL", "]", "[", "domain", "]", "=", "{", "CONF_CLIENT_ID", ":", "client_id", ",", "CONF_CLIENT_SECRET", ":", "client_secret", ",", "CONF_API_KEY", ":", "api_key", ",", "CONF_REDIRECT_URI", ":", "redirect_uri", ",", "CONF_SENSORS", ":", "sensors", ",", "EXTERNAL_ERRORS", ":", "None", ",", "}" ]
[ 30, 0 ]
[ 52, 5 ]
python
en
['en', 'da', 'en']
True
LogiCircleAuthCallbackView.get
(self, request)
Receive authorization code.
Receive authorization code.
async def get(self, request): """Receive authorization code.""" hass = request.app["hass"] if "code" in request.query: hass.async_create_task( hass.config_entries.flow.async_init( DOMAIN, context={"source": "code"}, data=request.query["code"] ) ) return self.json_message("Authorisation code saved") return self.json_message( "Authorisation code missing from query string", status_code=HTTP_BAD_REQUEST )
[ "async", "def", "get", "(", "self", ",", "request", ")", ":", "hass", "=", "request", ".", "app", "[", "\"hass\"", "]", "if", "\"code\"", "in", "request", ".", "query", ":", "hass", ".", "async_create_task", "(", "hass", ".", "config_entries", ".", "flow", ".", "async_init", "(", "DOMAIN", ",", "context", "=", "{", "\"source\"", ":", "\"code\"", "}", ",", "data", "=", "request", ".", "query", "[", "\"code\"", "]", ")", ")", "return", "self", ".", "json_message", "(", "\"Authorisation code saved\"", ")", "return", "self", ".", "json_message", "(", "\"Authorisation code missing from query string\"", ",", "status_code", "=", "HTTP_BAD_REQUEST", ")" ]
[ 198, 4 ]
[ 210, 9 ]
python
de
['de', 'sr', 'en']
False
main
()
delete=True removes snapshots after posting
delete=True removes snapshots after posting
def main(): get_os_type() f = Figlet(font='slant') print(f.renderText('asleep')) print('https://t.me/asleep_cg\n') options = get_options() if options.debug or options.ports: config.logging.getLogger().setLevel(config.logging.DEBUG) else: config.logging.getLogger().propagate = False utils.setup_credentials(options.logins_passes) utils.prepare_folders_and_files() if not options.brute_only: masscan(options.scan_file, options.threads, options.masscan_resume) process_cameras() if not options.no_xml and len(config.working_hosts) > 0: export.save_xml(config.working_hosts) export.save_csv() if options.dead_cams: hosts = utils.masscan_parse(config.tmp_masscan_file) export.dead_cams(hosts) # Configs for Telegram Bot: ROOM_ID = '' # Channel ID TOKEN = '' # Bot Token SNAPSHOT_DIR = Path.cwd() / config.snapshots_folder """ delete=True removes snapshots after posting """ #poster = Poster(SNAPSHOT_DIR, TOKEN, ROOM_ID, delete=False) #poster.start() ### Start posting function if Path(config.snapshots_folder).exists(): c_error = False if config.global_country: try: Path(config.snapshots_folder).rename(f'{config.global_country}_{config.start_datetime}') except: c_error = True elif not config.global_country or c_error: Path(config.snapshots_folder).rename(f'Snapshots_{config.start_datetime}')
[ "def", "main", "(", ")", ":", "get_os_type", "(", ")", "f", "=", "Figlet", "(", "font", "=", "'slant'", ")", "print", "(", "f", ".", "renderText", "(", "'asleep'", ")", ")", "print", "(", "'https://t.me/asleep_cg\\n'", ")", "options", "=", "get_options", "(", ")", "if", "options", ".", "debug", "or", "options", ".", "ports", ":", "config", ".", "logging", ".", "getLogger", "(", ")", ".", "setLevel", "(", "config", ".", "logging", ".", "DEBUG", ")", "else", ":", "config", ".", "logging", ".", "getLogger", "(", ")", ".", "propagate", "=", "False", "utils", ".", "setup_credentials", "(", "options", ".", "logins_passes", ")", "utils", ".", "prepare_folders_and_files", "(", ")", "if", "not", "options", ".", "brute_only", ":", "masscan", "(", "options", ".", "scan_file", ",", "options", ".", "threads", ",", "options", ".", "masscan_resume", ")", "process_cameras", "(", ")", "if", "not", "options", ".", "no_xml", "and", "len", "(", "config", ".", "working_hosts", ")", ">", "0", ":", "export", ".", "save_xml", "(", "config", ".", "working_hosts", ")", "export", ".", "save_csv", "(", ")", "if", "options", ".", "dead_cams", ":", "hosts", "=", "utils", ".", "masscan_parse", "(", "config", ".", "tmp_masscan_file", ")", "export", ".", "dead_cams", "(", "hosts", ")", "# Configs for Telegram Bot:", "ROOM_ID", "=", "''", "# Channel ID", "TOKEN", "=", "''", "# Bot Token", "SNAPSHOT_DIR", "=", "Path", ".", "cwd", "(", ")", "/", "config", ".", "snapshots_folder", "#poster = Poster(SNAPSHOT_DIR, TOKEN, ROOM_ID, delete=False) ", "#poster.start() ### Start posting function", "if", "Path", "(", "config", ".", "snapshots_folder", ")", ".", "exists", "(", ")", ":", "c_error", "=", "False", "if", "config", ".", "global_country", ":", "try", ":", "Path", "(", "config", ".", "snapshots_folder", ")", ".", "rename", "(", "f'{config.global_country}_{config.start_datetime}'", ")", "except", ":", "c_error", "=", "True", "elif", "not", "config", ".", "global_country", "or", "c_error", ":", "Path", "(", "config", ".", "snapshots_folder", ")", ".", "rename", "(", "f'Snapshots_{config.start_datetime}'", ")" ]
[ 251, 0 ]
[ 289, 86 ]
python
en
['da', 'en', 'en']
True
get_engine
(hass, config, discovery_info=None)
Set up IBM Watson TTS component.
Set up IBM Watson TTS component.
def get_engine(hass, config, discovery_info=None): """Set up IBM Watson TTS component.""" authenticator = IAMAuthenticator(config[CONF_APIKEY]) service = TextToSpeechV1(authenticator) service.set_service_url(config[CONF_URL]) supported_languages = list({s[:5] for s in SUPPORTED_VOICES}) default_voice = config[CONF_VOICE] output_format = config[CONF_OUTPUT_FORMAT] service.set_default_headers({"x-watson-learning-opt-out": "true"}) return WatsonTTSProvider(service, supported_languages, default_voice, output_format)
[ "def", "get_engine", "(", "hass", ",", "config", ",", "discovery_info", "=", "None", ")", ":", "authenticator", "=", "IAMAuthenticator", "(", "config", "[", "CONF_APIKEY", "]", ")", "service", "=", "TextToSpeechV1", "(", "authenticator", ")", "service", ".", "set_service_url", "(", "config", "[", "CONF_URL", "]", ")", "supported_languages", "=", "list", "(", "{", "s", "[", ":", "5", "]", "for", "s", "in", "SUPPORTED_VOICES", "}", ")", "default_voice", "=", "config", "[", "CONF_VOICE", "]", "output_format", "=", "config", "[", "CONF_OUTPUT_FORMAT", "]", "service", ".", "set_default_headers", "(", "{", "\"x-watson-learning-opt-out\"", ":", "\"true\"", "}", ")", "return", "WatsonTTSProvider", "(", "service", ",", "supported_languages", ",", "default_voice", ",", "output_format", ")" ]
[ 98, 0 ]
[ 110, 88 ]
python
en
['en', 'bg', 'en']
True
WatsonTTSProvider.__init__
(self, service, supported_languages, default_voice, output_format)
Initialize Watson TTS provider.
Initialize Watson TTS provider.
def __init__(self, service, supported_languages, default_voice, output_format): """Initialize Watson TTS provider.""" self.service = service self.supported_langs = supported_languages self.default_lang = default_voice[:5] self.default_voice = default_voice self.output_format = output_format self.name = "Watson TTS"
[ "def", "__init__", "(", "self", ",", "service", ",", "supported_languages", ",", "default_voice", ",", "output_format", ")", ":", "self", ".", "service", "=", "service", "self", ".", "supported_langs", "=", "supported_languages", "self", ".", "default_lang", "=", "default_voice", "[", ":", "5", "]", "self", ".", "default_voice", "=", "default_voice", "self", ".", "output_format", "=", "output_format", "self", ".", "name", "=", "\"Watson TTS\"" ]
[ 116, 4 ]
[ 123, 32 ]
python
en
['en', 'ny', 'en']
True
WatsonTTSProvider.supported_languages
(self)
Return a list of supported languages.
Return a list of supported languages.
def supported_languages(self): """Return a list of supported languages.""" return self.supported_langs
[ "def", "supported_languages", "(", "self", ")", ":", "return", "self", ".", "supported_langs" ]
[ 126, 4 ]
[ 128, 35 ]
python
en
['en', 'en', 'en']
True
WatsonTTSProvider.default_language
(self)
Return the default language.
Return the default language.
def default_language(self): """Return the default language.""" return self.default_lang
[ "def", "default_language", "(", "self", ")", ":", "return", "self", ".", "default_lang" ]
[ 131, 4 ]
[ 133, 32 ]
python
en
['en', 'et', 'en']
True
WatsonTTSProvider.default_options
(self)
Return dict include default options.
Return dict include default options.
def default_options(self): """Return dict include default options.""" return {CONF_VOICE: self.default_voice}
[ "def", "default_options", "(", "self", ")", ":", "return", "{", "CONF_VOICE", ":", "self", ".", "default_voice", "}" ]
[ 136, 4 ]
[ 138, 47 ]
python
en
['nl', 'en', 'en']
True
WatsonTTSProvider.supported_options
(self)
Return a list of supported options.
Return a list of supported options.
def supported_options(self): """Return a list of supported options.""" return [CONF_VOICE]
[ "def", "supported_options", "(", "self", ")", ":", "return", "[", "CONF_VOICE", "]" ]
[ 141, 4 ]
[ 143, 27 ]
python
en
['en', 'en', 'en']
True
WatsonTTSProvider.get_tts_audio
(self, message, language=None, options=None)
Request TTS file from Watson TTS.
Request TTS file from Watson TTS.
def get_tts_audio(self, message, language=None, options=None): """Request TTS file from Watson TTS.""" response = self.service.synthesize( message, accept=self.output_format, voice=self.default_voice ).get_result() return (CONTENT_TYPE_EXTENSIONS[self.output_format], response.content)
[ "def", "get_tts_audio", "(", "self", ",", "message", ",", "language", "=", "None", ",", "options", "=", "None", ")", ":", "response", "=", "self", ".", "service", ".", "synthesize", "(", "message", ",", "accept", "=", "self", ".", "output_format", ",", "voice", "=", "self", ".", "default_voice", ")", ".", "get_result", "(", ")", "return", "(", "CONTENT_TYPE_EXTENSIONS", "[", "self", ".", "output_format", "]", ",", "response", ".", "content", ")" ]
[ 145, 4 ]
[ 151, 78 ]
python
en
['en', 'en', 'en']
True
accuracy
(output, target, topk=(1, 5))
Computes the precision@k for the specified values of k
Computes the precision
def accuracy(output, target, topk=(1, 5)): """ Computes the precision@k for the specified values of k """ maxk = max(topk) batch_size = target.size(0) _, pred = output.topk(maxk, 1, True, True) pred = pred.t() # one-hot case if target.ndimension() > 1: target = target.max(1)[1] correct = pred.eq(target.view(1, -1).expand_as(pred)) res = dict() for k in topk: correct_k = correct[:k].reshape(-1).float().sum(0) res["acc{}".format(k)] = correct_k.mul_(1.0 / batch_size).item() return res
[ "def", "accuracy", "(", "output", ",", "target", ",", "topk", "=", "(", "1", ",", "5", ")", ")", ":", "maxk", "=", "max", "(", "topk", ")", "batch_size", "=", "target", ".", "size", "(", "0", ")", "_", ",", "pred", "=", "output", ".", "topk", "(", "maxk", ",", "1", ",", "True", ",", "True", ")", "pred", "=", "pred", ".", "t", "(", ")", "# one-hot case", "if", "target", ".", "ndimension", "(", ")", ">", "1", ":", "target", "=", "target", ".", "max", "(", "1", ")", "[", "1", "]", "correct", "=", "pred", ".", "eq", "(", "target", ".", "view", "(", "1", ",", "-", "1", ")", ".", "expand_as", "(", "pred", ")", ")", "res", "=", "dict", "(", ")", "for", "k", "in", "topk", ":", "correct_k", "=", "correct", "[", ":", "k", "]", ".", "reshape", "(", "-", "1", ")", ".", "float", "(", ")", ".", "sum", "(", "0", ")", "res", "[", "\"acc{}\"", ".", "format", "(", "k", ")", "]", "=", "correct_k", ".", "mul_", "(", "1.0", "/", "batch_size", ")", ".", "item", "(", ")", "return", "res" ]
[ 23, 0 ]
[ 40, 14 ]
python
en
['en', 'en', 'en']
True
init_integration
( hass, *, data: dict = ENTRY_CONFIG, options: dict = ENTRY_OPTIONS, )
Set up the NZBGet integration in Home Assistant.
Set up the NZBGet integration in Home Assistant.
async def init_integration( hass, *, data: dict = ENTRY_CONFIG, options: dict = ENTRY_OPTIONS, ) -> MockConfigEntry: """Set up the NZBGet integration in Home Assistant.""" entry = MockConfigEntry(domain=DOMAIN, data=data, options=options) entry.add_to_hass(hass) await hass.config_entries.async_setup(entry.entry_id) await hass.async_block_till_done() return entry
[ "async", "def", "init_integration", "(", "hass", ",", "*", ",", "data", ":", "dict", "=", "ENTRY_CONFIG", ",", "options", ":", "dict", "=", "ENTRY_OPTIONS", ",", ")", "->", "MockConfigEntry", ":", "entry", "=", "MockConfigEntry", "(", "domain", "=", "DOMAIN", ",", "data", "=", "data", ",", "options", "=", "options", ")", "entry", ".", "add_to_hass", "(", "hass", ")", "await", "hass", ".", "config_entries", ".", "async_setup", "(", "entry", ".", "entry_id", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "return", "entry" ]
[ 70, 0 ]
[ 83, 16 ]
python
en
['en', 'en', 'en']
True
test_form
(hass)
Test we get the form.
Test we get the form.
async def test_form(hass): """Test we get the form.""" result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": config_entries.SOURCE_USER} ) assert result["type"] == "form" assert result["errors"] is None with patch( "homeassistant.components.coolmaster.config_flow.CoolMasterNet.status", return_value={"test_id": "test_unit"}, ), patch( "homeassistant.components.coolmaster.async_setup", return_value=True ) as mock_setup, patch( "homeassistant.components.coolmaster.async_setup_entry", return_value=True, ) as mock_setup_entry: result2 = await hass.config_entries.flow.async_configure( result["flow_id"], _flow_data() ) await hass.async_block_till_done() assert result2["type"] == "create_entry" assert result2["title"] == "1.1.1.1" assert result2["data"] == { "host": "1.1.1.1", "port": 10102, "supported_modes": AVAILABLE_MODES, } assert len(mock_setup.mock_calls) == 1 assert len(mock_setup_entry.mock_calls) == 1
[ "async", "def", "test_form", "(", "hass", ")", ":", "result", "=", "await", "hass", ".", "config_entries", ".", "flow", ".", "async_init", "(", "DOMAIN", ",", "context", "=", "{", "\"source\"", ":", "config_entries", ".", "SOURCE_USER", "}", ")", "assert", "result", "[", "\"type\"", "]", "==", "\"form\"", "assert", "result", "[", "\"errors\"", "]", "is", "None", "with", "patch", "(", "\"homeassistant.components.coolmaster.config_flow.CoolMasterNet.status\"", ",", "return_value", "=", "{", "\"test_id\"", ":", "\"test_unit\"", "}", ",", ")", ",", "patch", "(", "\"homeassistant.components.coolmaster.async_setup\"", ",", "return_value", "=", "True", ")", "as", "mock_setup", ",", "patch", "(", "\"homeassistant.components.coolmaster.async_setup_entry\"", ",", "return_value", "=", "True", ",", ")", "as", "mock_setup_entry", ":", "result2", "=", "await", "hass", ".", "config_entries", ".", "flow", ".", "async_configure", "(", "result", "[", "\"flow_id\"", "]", ",", "_flow_data", "(", ")", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "assert", "result2", "[", "\"type\"", "]", "==", "\"create_entry\"", "assert", "result2", "[", "\"title\"", "]", "==", "\"1.1.1.1\"", "assert", "result2", "[", "\"data\"", "]", "==", "{", "\"host\"", ":", "\"1.1.1.1\"", ",", "\"port\"", ":", "10102", ",", "\"supported_modes\"", ":", "AVAILABLE_MODES", ",", "}", "assert", "len", "(", "mock_setup", ".", "mock_calls", ")", "==", "1", "assert", "len", "(", "mock_setup_entry", ".", "mock_calls", ")", "==", "1" ]
[ 14, 0 ]
[ 44, 48 ]
python
en
['en', 'en', 'en']
True
test_form_timeout
(hass)
Test we handle a connection timeout.
Test we handle a connection timeout.
async def test_form_timeout(hass): """Test we handle a connection timeout.""" result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": config_entries.SOURCE_USER} ) with patch( "homeassistant.components.coolmaster.config_flow.CoolMasterNet.status", side_effect=TimeoutError(), ): result2 = await hass.config_entries.flow.async_configure( result["flow_id"], _flow_data() ) assert result2["type"] == "form" assert result2["errors"] == {"base": "cannot_connect"}
[ "async", "def", "test_form_timeout", "(", "hass", ")", ":", "result", "=", "await", "hass", ".", "config_entries", ".", "flow", ".", "async_init", "(", "DOMAIN", ",", "context", "=", "{", "\"source\"", ":", "config_entries", ".", "SOURCE_USER", "}", ")", "with", "patch", "(", "\"homeassistant.components.coolmaster.config_flow.CoolMasterNet.status\"", ",", "side_effect", "=", "TimeoutError", "(", ")", ",", ")", ":", "result2", "=", "await", "hass", ".", "config_entries", ".", "flow", ".", "async_configure", "(", "result", "[", "\"flow_id\"", "]", ",", "_flow_data", "(", ")", ")", "assert", "result2", "[", "\"type\"", "]", "==", "\"form\"", "assert", "result2", "[", "\"errors\"", "]", "==", "{", "\"base\"", ":", "\"cannot_connect\"", "}" ]
[ 47, 0 ]
[ 62, 58 ]
python
en
['en', 'en', 'en']
True
test_form_connection_refused
(hass)
Test we handle a connection error.
Test we handle a connection error.
async def test_form_connection_refused(hass): """Test we handle a connection error.""" result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": config_entries.SOURCE_USER} ) with patch( "homeassistant.components.coolmaster.config_flow.CoolMasterNet.status", side_effect=ConnectionRefusedError(), ): result2 = await hass.config_entries.flow.async_configure( result["flow_id"], _flow_data() ) assert result2["type"] == "form" assert result2["errors"] == {"base": "cannot_connect"}
[ "async", "def", "test_form_connection_refused", "(", "hass", ")", ":", "result", "=", "await", "hass", ".", "config_entries", ".", "flow", ".", "async_init", "(", "DOMAIN", ",", "context", "=", "{", "\"source\"", ":", "config_entries", ".", "SOURCE_USER", "}", ")", "with", "patch", "(", "\"homeassistant.components.coolmaster.config_flow.CoolMasterNet.status\"", ",", "side_effect", "=", "ConnectionRefusedError", "(", ")", ",", ")", ":", "result2", "=", "await", "hass", ".", "config_entries", ".", "flow", ".", "async_configure", "(", "result", "[", "\"flow_id\"", "]", ",", "_flow_data", "(", ")", ")", "assert", "result2", "[", "\"type\"", "]", "==", "\"form\"", "assert", "result2", "[", "\"errors\"", "]", "==", "{", "\"base\"", ":", "\"cannot_connect\"", "}" ]
[ 65, 0 ]
[ 80, 58 ]
python
en
['en', 'en', 'en']
True
test_form_no_units
(hass)
Test we handle no units found.
Test we handle no units found.
async def test_form_no_units(hass): """Test we handle no units found.""" result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": config_entries.SOURCE_USER} ) with patch( "homeassistant.components.coolmaster.config_flow.CoolMasterNet.status", return_value={}, ): result2 = await hass.config_entries.flow.async_configure( result["flow_id"], _flow_data() ) assert result2["type"] == "form" assert result2["errors"] == {"base": "no_units"}
[ "async", "def", "test_form_no_units", "(", "hass", ")", ":", "result", "=", "await", "hass", ".", "config_entries", ".", "flow", ".", "async_init", "(", "DOMAIN", ",", "context", "=", "{", "\"source\"", ":", "config_entries", ".", "SOURCE_USER", "}", ")", "with", "patch", "(", "\"homeassistant.components.coolmaster.config_flow.CoolMasterNet.status\"", ",", "return_value", "=", "{", "}", ",", ")", ":", "result2", "=", "await", "hass", ".", "config_entries", ".", "flow", ".", "async_configure", "(", "result", "[", "\"flow_id\"", "]", ",", "_flow_data", "(", ")", ")", "assert", "result2", "[", "\"type\"", "]", "==", "\"form\"", "assert", "result2", "[", "\"errors\"", "]", "==", "{", "\"base\"", ":", "\"no_units\"", "}" ]
[ 83, 0 ]
[ 98, 52 ]
python
en
['en', 'de', 'en']
True
normalize_answer
(str_input)
Lower text and remove punctuation, articles and extra whitespace.
Lower text and remove punctuation, articles and extra whitespace.
def normalize_answer(str_input): """Lower text and remove punctuation, articles and extra whitespace.""" def remove_articles(text): ''' Remove "a|an|the" ''' return re.sub(r'\b(a|an|the)\b', ' ', text) def white_space_fix(text): ''' Remove unnessary whitespace ''' return ' '.join(text.split()) def remove_punc(text): ''' Remove punc ''' exclude = set(string.punctuation) return ''.join(ch for ch in text if ch not in exclude) def lower(text): ''' Change string to lower form. ''' return text.lower() return white_space_fix(remove_articles(remove_punc(lower(str_input))))
[ "def", "normalize_answer", "(", "str_input", ")", ":", "def", "remove_articles", "(", "text", ")", ":", "'''\n Remove \"a|an|the\"\n '''", "return", "re", ".", "sub", "(", "r'\\b(a|an|the)\\b'", ",", "' '", ",", "text", ")", "def", "white_space_fix", "(", "text", ")", ":", "'''\n Remove unnessary whitespace\n '''", "return", "' '", ".", "join", "(", "text", ".", "split", "(", ")", ")", "def", "remove_punc", "(", "text", ")", ":", "'''\n Remove punc\n '''", "exclude", "=", "set", "(", "string", ".", "punctuation", ")", "return", "''", ".", "join", "(", "ch", "for", "ch", "in", "text", "if", "ch", "not", "in", "exclude", ")", "def", "lower", "(", "text", ")", ":", "'''\n Change string to lower form.\n '''", "return", "text", ".", "lower", "(", ")", "return", "white_space_fix", "(", "remove_articles", "(", "remove_punc", "(", "lower", "(", "str_input", ")", ")", ")", ")" ]
[ 33, 0 ]
[ 60, 74 ]
python
en
['en', 'en', 'en']
True
f1_score
(prediction, ground_truth)
Calculate the f1 score.
Calculate the f1 score.
def f1_score(prediction, ground_truth): ''' Calculate the f1 score. ''' prediction_tokens = normalize_answer(prediction).split() ground_truth_tokens = normalize_answer(ground_truth).split() common = Counter(prediction_tokens) & Counter(ground_truth_tokens) num_same = sum(common.values()) if num_same == 0: return 0 precision = 1.0 * num_same / len(prediction_tokens) recall = 1.0 * num_same / len(ground_truth_tokens) f1_result = (2 * precision * recall) / (precision + recall) return f1_result
[ "def", "f1_score", "(", "prediction", ",", "ground_truth", ")", ":", "prediction_tokens", "=", "normalize_answer", "(", "prediction", ")", ".", "split", "(", ")", "ground_truth_tokens", "=", "normalize_answer", "(", "ground_truth", ")", ".", "split", "(", ")", "common", "=", "Counter", "(", "prediction_tokens", ")", "&", "Counter", "(", "ground_truth_tokens", ")", "num_same", "=", "sum", "(", "common", ".", "values", "(", ")", ")", "if", "num_same", "==", "0", ":", "return", "0", "precision", "=", "1.0", "*", "num_same", "/", "len", "(", "prediction_tokens", ")", "recall", "=", "1.0", "*", "num_same", "/", "len", "(", "ground_truth_tokens", ")", "f1_result", "=", "(", "2", "*", "precision", "*", "recall", ")", "/", "(", "precision", "+", "recall", ")", "return", "f1_result" ]
[ 62, 0 ]
[ 75, 20 ]
python
en
['en', 'error', 'th']
False
exact_match_score
(prediction, ground_truth)
Calculate the match score with prediction and ground truth.
Calculate the match score with prediction and ground truth.
def exact_match_score(prediction, ground_truth): ''' Calculate the match score with prediction and ground truth. ''' return normalize_answer(prediction) == normalize_answer(ground_truth)
[ "def", "exact_match_score", "(", "prediction", ",", "ground_truth", ")", ":", "return", "normalize_answer", "(", "prediction", ")", "==", "normalize_answer", "(", "ground_truth", ")" ]
[ 77, 0 ]
[ 81, 73 ]
python
en
['en', 'error', 'th']
False
metric_max_over_ground_truths
(metric_fn, prediction, ground_truths)
Metric max over the ground truths.
Metric max over the ground truths.
def metric_max_over_ground_truths(metric_fn, prediction, ground_truths): ''' Metric max over the ground truths. ''' scores_for_ground_truths = [] for ground_truth in ground_truths: score = metric_fn(prediction, ground_truth) scores_for_ground_truths.append(score) return max(scores_for_ground_truths)
[ "def", "metric_max_over_ground_truths", "(", "metric_fn", ",", "prediction", ",", "ground_truths", ")", ":", "scores_for_ground_truths", "=", "[", "]", "for", "ground_truth", "in", "ground_truths", ":", "score", "=", "metric_fn", "(", "prediction", ",", "ground_truth", ")", "scores_for_ground_truths", ".", "append", "(", "score", ")", "return", "max", "(", "scores_for_ground_truths", ")" ]
[ 83, 0 ]
[ 91, 40 ]
python
en
['en', 'error', 'th']
False
_evaluate
(dataset, predictions)
Evaluate function.
Evaluate function.
def _evaluate(dataset, predictions): ''' Evaluate function. ''' f1_result = exact_match = total = 0 count = 0 for article in dataset: for paragraph in article['paragraphs']: for qa_pair in paragraph['qas']: total += 1 if qa_pair['id'] not in predictions: count += 1 continue ground_truths = list(map(lambda x: x['text'], qa_pair['answers'])) prediction = predictions[qa_pair['id']] exact_match += metric_max_over_ground_truths( exact_match_score, prediction, ground_truths) f1_result += metric_max_over_ground_truths( f1_score, prediction, ground_truths) print('total', total, 'exact_match', exact_match, 'unanswer_question ', count) exact_match = 100.0 * exact_match / total f1_result = 100.0 * f1_result / total return {'exact_match': exact_match, 'f1': f1_result}
[ "def", "_evaluate", "(", "dataset", ",", "predictions", ")", ":", "f1_result", "=", "exact_match", "=", "total", "=", "0", "count", "=", "0", "for", "article", "in", "dataset", ":", "for", "paragraph", "in", "article", "[", "'paragraphs'", "]", ":", "for", "qa_pair", "in", "paragraph", "[", "'qas'", "]", ":", "total", "+=", "1", "if", "qa_pair", "[", "'id'", "]", "not", "in", "predictions", ":", "count", "+=", "1", "continue", "ground_truths", "=", "list", "(", "map", "(", "lambda", "x", ":", "x", "[", "'text'", "]", ",", "qa_pair", "[", "'answers'", "]", ")", ")", "prediction", "=", "predictions", "[", "qa_pair", "[", "'id'", "]", "]", "exact_match", "+=", "metric_max_over_ground_truths", "(", "exact_match_score", ",", "prediction", ",", "ground_truths", ")", "f1_result", "+=", "metric_max_over_ground_truths", "(", "f1_score", ",", "prediction", ",", "ground_truths", ")", "print", "(", "'total'", ",", "total", ",", "'exact_match'", ",", "exact_match", ",", "'unanswer_question '", ",", "count", ")", "exact_match", "=", "100.0", "*", "exact_match", "/", "total", "f1_result", "=", "100.0", "*", "f1_result", "/", "total", "return", "{", "'exact_match'", ":", "exact_match", ",", "'f1'", ":", "f1_result", "}" ]
[ 93, 0 ]
[ 115, 56 ]
python
en
['en', 'error', 'th']
False