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 |
---|---|---|---|---|---|---|---|---|---|---|---|
SunflowerBulb.name | (self) | Return the display name of this light. | Return the display name of this light. | def name(self):
"""Return the display name of this light."""
return f"sunflower_{self._light.zid}" | [
"def",
"name",
"(",
"self",
")",
":",
"return",
"f\"sunflower_{self._light.zid}\""
] | [
50,
4
] | [
52,
45
] | python | en | ['en', 'en', 'en'] | True |
SunflowerBulb.unique_id | (self) | Return the unique ID of this light. | Return the unique ID of this light. | def unique_id(self):
"""Return the unique ID of this light."""
return self._unique_id | [
"def",
"unique_id",
"(",
"self",
")",
":",
"return",
"self",
".",
"_unique_id"
] | [
55,
4
] | [
57,
30
] | python | en | ['en', 'la', 'en'] | True |
SunflowerBulb.available | (self) | Return True if entity is available. | Return True if entity is available. | def available(self):
"""Return True if entity is available."""
return self._available | [
"def",
"available",
"(",
"self",
")",
":",
"return",
"self",
".",
"_available"
] | [
60,
4
] | [
62,
30
] | python | en | ['en', 'en', 'en'] | True |
SunflowerBulb.is_on | (self) | Return true if light is on. | Return true if light is on. | def is_on(self):
"""Return true if light is on."""
return self._is_on | [
"def",
"is_on",
"(",
"self",
")",
":",
"return",
"self",
".",
"_is_on"
] | [
65,
4
] | [
67,
26
] | python | en | ['en', 'et', 'en'] | True |
SunflowerBulb.brightness | (self) | Return the brightness is 0-255; Yeelight's brightness is 0-100. | Return the brightness is 0-255; Yeelight's brightness is 0-100. | def brightness(self):
"""Return the brightness is 0-255; Yeelight's brightness is 0-100."""
return int(self._brightness / 100 * 255) | [
"def",
"brightness",
"(",
"self",
")",
":",
"return",
"int",
"(",
"self",
".",
"_brightness",
"/",
"100",
"*",
"255",
")"
] | [
70,
4
] | [
72,
48
] | python | en | ['en', 'sn', 'en'] | True |
SunflowerBulb.hs_color | (self) | Return the color property. | Return the color property. | def hs_color(self):
"""Return the color property."""
return color_util.color_RGB_to_hs(*self._rgb_color) | [
"def",
"hs_color",
"(",
"self",
")",
":",
"return",
"color_util",
".",
"color_RGB_to_hs",
"(",
"*",
"self",
".",
"_rgb_color",
")"
] | [
75,
4
] | [
77,
59
] | python | en | ['en', 'en', 'en'] | True |
SunflowerBulb.supported_features | (self) | Flag supported features. | Flag supported features. | def supported_features(self):
"""Flag supported features."""
return SUPPORT_YEELIGHT_SUNFLOWER | [
"def",
"supported_features",
"(",
"self",
")",
":",
"return",
"SUPPORT_YEELIGHT_SUNFLOWER"
] | [
80,
4
] | [
82,
41
] | python | en | ['da', 'en', 'en'] | True |
SunflowerBulb.turn_on | (self, **kwargs) | Instruct the light to turn on, optionally set colour/brightness. | Instruct the light to turn on, optionally set colour/brightness. | def turn_on(self, **kwargs):
"""Instruct the light to turn on, optionally set colour/brightness."""
# when no arguments, just turn light on (full brightness)
if not kwargs:
self._light.turn_on()
else:
if ATTR_HS_COLOR in kwargs and ATTR_BRIGHTNESS in kwargs:
rgb = color_util.color_hs_to_RGB(*kwargs[ATTR_HS_COLOR])
bright = int(kwargs[ATTR_BRIGHTNESS] / 255 * 100)
self._light.set_all(rgb[0], rgb[1], rgb[2], bright)
elif ATTR_HS_COLOR in kwargs:
rgb = color_util.color_hs_to_RGB(*kwargs[ATTR_HS_COLOR])
self._light.set_rgb_color(rgb[0], rgb[1], rgb[2])
elif ATTR_BRIGHTNESS in kwargs:
bright = int(kwargs[ATTR_BRIGHTNESS] / 255 * 100)
self._light.set_brightness(bright) | [
"def",
"turn_on",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"# when no arguments, just turn light on (full brightness)",
"if",
"not",
"kwargs",
":",
"self",
".",
"_light",
".",
"turn_on",
"(",
")",
"else",
":",
"if",
"ATTR_HS_COLOR",
"in",
"kwargs",
"and",
"ATTR_BRIGHTNESS",
"in",
"kwargs",
":",
"rgb",
"=",
"color_util",
".",
"color_hs_to_RGB",
"(",
"*",
"kwargs",
"[",
"ATTR_HS_COLOR",
"]",
")",
"bright",
"=",
"int",
"(",
"kwargs",
"[",
"ATTR_BRIGHTNESS",
"]",
"/",
"255",
"*",
"100",
")",
"self",
".",
"_light",
".",
"set_all",
"(",
"rgb",
"[",
"0",
"]",
",",
"rgb",
"[",
"1",
"]",
",",
"rgb",
"[",
"2",
"]",
",",
"bright",
")",
"elif",
"ATTR_HS_COLOR",
"in",
"kwargs",
":",
"rgb",
"=",
"color_util",
".",
"color_hs_to_RGB",
"(",
"*",
"kwargs",
"[",
"ATTR_HS_COLOR",
"]",
")",
"self",
".",
"_light",
".",
"set_rgb_color",
"(",
"rgb",
"[",
"0",
"]",
",",
"rgb",
"[",
"1",
"]",
",",
"rgb",
"[",
"2",
"]",
")",
"elif",
"ATTR_BRIGHTNESS",
"in",
"kwargs",
":",
"bright",
"=",
"int",
"(",
"kwargs",
"[",
"ATTR_BRIGHTNESS",
"]",
"/",
"255",
"*",
"100",
")",
"self",
".",
"_light",
".",
"set_brightness",
"(",
"bright",
")"
] | [
84,
4
] | [
99,
50
] | python | en | ['en', 'zu', 'en'] | True |
SunflowerBulb.turn_off | (self, **kwargs) | Instruct the light to turn off. | Instruct the light to turn off. | def turn_off(self, **kwargs):
"""Instruct the light to turn off."""
self._light.turn_off() | [
"def",
"turn_off",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"_light",
".",
"turn_off",
"(",
")"
] | [
101,
4
] | [
103,
30
] | python | en | ['en', 'en', 'en'] | True |
SunflowerBulb.update | (self) | Fetch new state data for this light and update local values. | Fetch new state data for this light and update local values. | def update(self):
"""Fetch new state data for this light and update local values."""
self._light.update()
self._available = self._light.available
self._brightness = self._light.brightness
self._is_on = self._light.is_on
self._rgb_color = self._light.rgb_color | [
"def",
"update",
"(",
"self",
")",
":",
"self",
".",
"_light",
".",
"update",
"(",
")",
"self",
".",
"_available",
"=",
"self",
".",
"_light",
".",
"available",
"self",
".",
"_brightness",
"=",
"self",
".",
"_light",
".",
"brightness",
"self",
".",
"_is_on",
"=",
"self",
".",
"_light",
".",
"is_on",
"self",
".",
"_rgb_color",
"=",
"self",
".",
"_light",
".",
"rgb_color"
] | [
105,
4
] | [
111,
47
] | python | en | ['en', 'en', 'en'] | True |
async_setup_entry | (
hass: HomeAssistantType, entry: ConfigEntry, async_add_entities
) | Set up the switch. | Set up the switch. | async def async_setup_entry(
hass: HomeAssistantType, entry: ConfigEntry, async_add_entities
) -> None:
"""Set up the switch."""
router = hass.data[DOMAIN][entry.unique_id]
async_add_entities([FreeboxWifiSwitch(router)], True) | [
"async",
"def",
"async_setup_entry",
"(",
"hass",
":",
"HomeAssistantType",
",",
"entry",
":",
"ConfigEntry",
",",
"async_add_entities",
")",
"->",
"None",
":",
"router",
"=",
"hass",
".",
"data",
"[",
"DOMAIN",
"]",
"[",
"entry",
".",
"unique_id",
"]",
"async_add_entities",
"(",
"[",
"FreeboxWifiSwitch",
"(",
"router",
")",
"]",
",",
"True",
")"
] | [
16,
0
] | [
21,
57
] | python | en | ['en', 'en', 'en'] | True |
FreeboxWifiSwitch.__init__ | (self, router: FreeboxRouter) | Initialize the Wifi switch. | Initialize the Wifi switch. | def __init__(self, router: FreeboxRouter) -> None:
"""Initialize the Wifi switch."""
self._name = "Freebox WiFi"
self._state = None
self._router = router
self._unique_id = f"{self._router.mac} {self._name}" | [
"def",
"__init__",
"(",
"self",
",",
"router",
":",
"FreeboxRouter",
")",
"->",
"None",
":",
"self",
".",
"_name",
"=",
"\"Freebox WiFi\"",
"self",
".",
"_state",
"=",
"None",
"self",
".",
"_router",
"=",
"router",
"self",
".",
"_unique_id",
"=",
"f\"{self._router.mac} {self._name}\""
] | [
27,
4
] | [
32,
60
] | python | en | ['en', 'pl', 'en'] | True |
FreeboxWifiSwitch.unique_id | (self) | Return a unique ID. | Return a unique ID. | def unique_id(self) -> str:
"""Return a unique ID."""
return self._unique_id | [
"def",
"unique_id",
"(",
"self",
")",
"->",
"str",
":",
"return",
"self",
".",
"_unique_id"
] | [
35,
4
] | [
37,
30
] | python | ca | ['fr', 'ca', 'en'] | False |
FreeboxWifiSwitch.name | (self) | Return the name of the switch. | Return the name of the switch. | def name(self) -> str:
"""Return the name of the switch."""
return self._name | [
"def",
"name",
"(",
"self",
")",
"->",
"str",
":",
"return",
"self",
".",
"_name"
] | [
40,
4
] | [
42,
25
] | python | en | ['en', 'en', 'en'] | True |
FreeboxWifiSwitch.is_on | (self) | Return true if device is on. | Return true if device is on. | def is_on(self) -> bool:
"""Return true if device is on."""
return self._state | [
"def",
"is_on",
"(",
"self",
")",
"->",
"bool",
":",
"return",
"self",
".",
"_state"
] | [
45,
4
] | [
47,
26
] | python | en | ['en', 'fy', 'en'] | True |
FreeboxWifiSwitch.device_info | (self) | Return the device information. | Return the device information. | def device_info(self) -> Dict[str, any]:
"""Return the device information."""
return self._router.device_info | [
"def",
"device_info",
"(",
"self",
")",
"->",
"Dict",
"[",
"str",
",",
"any",
"]",
":",
"return",
"self",
".",
"_router",
".",
"device_info"
] | [
50,
4
] | [
52,
39
] | python | en | ['en', 'en', 'en'] | True |
FreeboxWifiSwitch._async_set_state | (self, enabled: bool) | Turn the switch on or off. | Turn the switch on or off. | async def _async_set_state(self, enabled: bool):
"""Turn the switch on or off."""
wifi_config = {"enabled": enabled}
try:
await self._router.wifi.set_global_config(wifi_config)
except InsufficientPermissionsError:
_LOGGER.warning(
"Home Assistant does not have permissions to modify the Freebox settings. Please refer to documentation"
) | [
"async",
"def",
"_async_set_state",
"(",
"self",
",",
"enabled",
":",
"bool",
")",
":",
"wifi_config",
"=",
"{",
"\"enabled\"",
":",
"enabled",
"}",
"try",
":",
"await",
"self",
".",
"_router",
".",
"wifi",
".",
"set_global_config",
"(",
"wifi_config",
")",
"except",
"InsufficientPermissionsError",
":",
"_LOGGER",
".",
"warning",
"(",
"\"Home Assistant does not have permissions to modify the Freebox settings. Please refer to documentation\"",
")"
] | [
54,
4
] | [
62,
13
] | python | en | ['en', 'en', 'en'] | True |
FreeboxWifiSwitch.async_turn_on | (self, **kwargs) | Turn the switch on. | Turn the switch on. | async def async_turn_on(self, **kwargs):
"""Turn the switch on."""
await self._async_set_state(True) | [
"async",
"def",
"async_turn_on",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"await",
"self",
".",
"_async_set_state",
"(",
"True",
")"
] | [
64,
4
] | [
66,
41
] | python | en | ['en', 'en', 'en'] | True |
FreeboxWifiSwitch.async_turn_off | (self, **kwargs) | Turn the switch off. | Turn the switch off. | async def async_turn_off(self, **kwargs):
"""Turn the switch off."""
await self._async_set_state(False) | [
"async",
"def",
"async_turn_off",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"await",
"self",
".",
"_async_set_state",
"(",
"False",
")"
] | [
68,
4
] | [
70,
42
] | python | en | ['en', 'en', 'en'] | True |
FreeboxWifiSwitch.async_update | (self) | Get the state and update it. | Get the state and update it. | async def async_update(self):
"""Get the state and update it."""
datas = await self._router.wifi.get_global_config()
active = datas["enabled"]
self._state = bool(active) | [
"async",
"def",
"async_update",
"(",
"self",
")",
":",
"datas",
"=",
"await",
"self",
".",
"_router",
".",
"wifi",
".",
"get_global_config",
"(",
")",
"active",
"=",
"datas",
"[",
"\"enabled\"",
"]",
"self",
".",
"_state",
"=",
"bool",
"(",
"active",
")"
] | [
72,
4
] | [
76,
34
] | python | en | ['en', 'en', 'en'] | True |
async_setup | (hass, config) | Import the Transmission Component from config. | Import the Transmission Component from config. | async def async_setup(hass, config):
"""Import the Transmission Component from config."""
if DOMAIN in config:
for entry in config[DOMAIN]:
hass.async_create_task(
hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_IMPORT}, data=entry
)
)
return True | [
"async",
"def",
"async_setup",
"(",
"hass",
",",
"config",
")",
":",
"if",
"DOMAIN",
"in",
"config",
":",
"for",
"entry",
"in",
"config",
"[",
"DOMAIN",
"]",
":",
"hass",
".",
"async_create_task",
"(",
"hass",
".",
"config_entries",
".",
"flow",
".",
"async_init",
"(",
"DOMAIN",
",",
"context",
"=",
"{",
"\"source\"",
":",
"SOURCE_IMPORT",
"}",
",",
"data",
"=",
"entry",
")",
")",
"return",
"True"
] | [
81,
0
] | [
91,
15
] | python | en | ['en', 'en', 'en'] | True |
async_setup_entry | (hass, config_entry) | Set up the Transmission Component. | Set up the Transmission Component. | async def async_setup_entry(hass, config_entry):
"""Set up the Transmission Component."""
client = TransmissionClient(hass, config_entry)
hass.data.setdefault(DOMAIN, {})[config_entry.entry_id] = client
if not await client.async_setup():
return False
return True | [
"async",
"def",
"async_setup_entry",
"(",
"hass",
",",
"config_entry",
")",
":",
"client",
"=",
"TransmissionClient",
"(",
"hass",
",",
"config_entry",
")",
"hass",
".",
"data",
".",
"setdefault",
"(",
"DOMAIN",
",",
"{",
"}",
")",
"[",
"config_entry",
".",
"entry_id",
"]",
"=",
"client",
"if",
"not",
"await",
"client",
".",
"async_setup",
"(",
")",
":",
"return",
"False",
"return",
"True"
] | [
94,
0
] | [
102,
15
] | python | en | ['en', 'da', 'en'] | True |
async_unload_entry | (hass, config_entry) | Unload Transmission Entry from config_entry. | Unload Transmission Entry from config_entry. | async def async_unload_entry(hass, config_entry):
"""Unload Transmission Entry from config_entry."""
client = hass.data[DOMAIN].pop(config_entry.entry_id)
if client.unsub_timer:
client.unsub_timer()
for platform in PLATFORMS:
await hass.config_entries.async_forward_entry_unload(config_entry, platform)
if not hass.data[DOMAIN]:
hass.services.async_remove(DOMAIN, SERVICE_ADD_TORRENT)
hass.services.async_remove(DOMAIN, SERVICE_REMOVE_TORRENT)
return True | [
"async",
"def",
"async_unload_entry",
"(",
"hass",
",",
"config_entry",
")",
":",
"client",
"=",
"hass",
".",
"data",
"[",
"DOMAIN",
"]",
".",
"pop",
"(",
"config_entry",
".",
"entry_id",
")",
"if",
"client",
".",
"unsub_timer",
":",
"client",
".",
"unsub_timer",
"(",
")",
"for",
"platform",
"in",
"PLATFORMS",
":",
"await",
"hass",
".",
"config_entries",
".",
"async_forward_entry_unload",
"(",
"config_entry",
",",
"platform",
")",
"if",
"not",
"hass",
".",
"data",
"[",
"DOMAIN",
"]",
":",
"hass",
".",
"services",
".",
"async_remove",
"(",
"DOMAIN",
",",
"SERVICE_ADD_TORRENT",
")",
"hass",
".",
"services",
".",
"async_remove",
"(",
"DOMAIN",
",",
"SERVICE_REMOVE_TORRENT",
")",
"return",
"True"
] | [
105,
0
] | [
118,
15
] | python | en | ['en', 'en', 'en'] | True |
get_api | (hass, entry) | Get Transmission client. | Get Transmission client. | async def get_api(hass, entry):
"""Get Transmission client."""
host = entry[CONF_HOST]
port = entry[CONF_PORT]
username = entry.get(CONF_USERNAME)
password = entry.get(CONF_PASSWORD)
try:
api = await hass.async_add_executor_job(
transmissionrpc.Client, host, port, username, password
)
_LOGGER.debug("Successfully connected to %s", host)
return api
except TransmissionError as error:
if "401: Unauthorized" in str(error):
_LOGGER.error("Credentials for Transmission client are not valid")
raise AuthenticationError from error
if "111: Connection refused" in str(error):
_LOGGER.error("Connecting to the Transmission client %s failed", host)
raise CannotConnect from error
_LOGGER.error(error)
raise UnknownError from error | [
"async",
"def",
"get_api",
"(",
"hass",
",",
"entry",
")",
":",
"host",
"=",
"entry",
"[",
"CONF_HOST",
"]",
"port",
"=",
"entry",
"[",
"CONF_PORT",
"]",
"username",
"=",
"entry",
".",
"get",
"(",
"CONF_USERNAME",
")",
"password",
"=",
"entry",
".",
"get",
"(",
"CONF_PASSWORD",
")",
"try",
":",
"api",
"=",
"await",
"hass",
".",
"async_add_executor_job",
"(",
"transmissionrpc",
".",
"Client",
",",
"host",
",",
"port",
",",
"username",
",",
"password",
")",
"_LOGGER",
".",
"debug",
"(",
"\"Successfully connected to %s\"",
",",
"host",
")",
"return",
"api",
"except",
"TransmissionError",
"as",
"error",
":",
"if",
"\"401: Unauthorized\"",
"in",
"str",
"(",
"error",
")",
":",
"_LOGGER",
".",
"error",
"(",
"\"Credentials for Transmission client are not valid\"",
")",
"raise",
"AuthenticationError",
"from",
"error",
"if",
"\"111: Connection refused\"",
"in",
"str",
"(",
"error",
")",
":",
"_LOGGER",
".",
"error",
"(",
"\"Connecting to the Transmission client %s failed\"",
",",
"host",
")",
"raise",
"CannotConnect",
"from",
"error",
"_LOGGER",
".",
"error",
"(",
"error",
")",
"raise",
"UnknownError",
"from",
"error"
] | [
121,
0
] | [
144,
37
] | python | en | ['en', 'da', 'en'] | True |
TransmissionClient.__init__ | (self, hass, config_entry) | Initialize the Transmission RPC API. | Initialize the Transmission RPC API. | def __init__(self, hass, config_entry):
"""Initialize the Transmission RPC API."""
self.hass = hass
self.config_entry = config_entry
self.tm_api = None
self._tm_data = None
self.unsub_timer = None | [
"def",
"__init__",
"(",
"self",
",",
"hass",
",",
"config_entry",
")",
":",
"self",
".",
"hass",
"=",
"hass",
"self",
".",
"config_entry",
"=",
"config_entry",
"self",
".",
"tm_api",
"=",
"None",
"self",
".",
"_tm_data",
"=",
"None",
"self",
".",
"unsub_timer",
"=",
"None"
] | [
150,
4
] | [
156,
31
] | python | en | ['en', 'en', 'en'] | True |
TransmissionClient.api | (self) | Return the tm_data object. | Return the tm_data object. | def api(self):
"""Return the tm_data object."""
return self._tm_data | [
"def",
"api",
"(",
"self",
")",
":",
"return",
"self",
".",
"_tm_data"
] | [
159,
4
] | [
161,
28
] | python | en | ['en', 'no', 'en'] | True |
TransmissionClient.async_setup | (self) | Set up the Transmission client. | Set up the Transmission client. | async def async_setup(self):
"""Set up the Transmission client."""
try:
self.tm_api = await get_api(self.hass, self.config_entry.data)
except CannotConnect as error:
raise ConfigEntryNotReady from error
except (AuthenticationError, UnknownError):
return False
self._tm_data = TransmissionData(self.hass, self.config_entry, self.tm_api)
await self.hass.async_add_executor_job(self._tm_data.init_torrent_list)
await self.hass.async_add_executor_job(self._tm_data.update)
self.add_options()
self.set_scan_interval(self.config_entry.options[CONF_SCAN_INTERVAL])
for platform in PLATFORMS:
self.hass.async_create_task(
self.hass.config_entries.async_forward_entry_setup(
self.config_entry, platform
)
)
def add_torrent(service):
"""Add new torrent to download."""
tm_client = None
for entry in self.hass.config_entries.async_entries(DOMAIN):
if entry.data[CONF_NAME] == service.data[CONF_NAME]:
tm_client = self.hass.data[DOMAIN][entry.entry_id]
break
if tm_client is None:
_LOGGER.error("Transmission instance is not found")
return
torrent = service.data[ATTR_TORRENT]
if torrent.startswith(
("http", "ftp:", "magnet:")
) or self.hass.config.is_allowed_path(torrent):
tm_client.tm_api.add_torrent(torrent)
tm_client.api.update()
else:
_LOGGER.warning(
"Could not add torrent: unsupported type or no permission"
)
def remove_torrent(service):
"""Remove torrent."""
tm_client = None
for entry in self.hass.config_entries.async_entries(DOMAIN):
if entry.data[CONF_NAME] == service.data[CONF_NAME]:
tm_client = self.hass.data[DOMAIN][entry.entry_id]
break
if tm_client is None:
_LOGGER.error("Transmission instance is not found")
return
torrent_id = service.data[CONF_ID]
delete_data = service.data[ATTR_DELETE_DATA]
tm_client.tm_api.remove_torrent(torrent_id, delete_data=delete_data)
tm_client.api.update()
self.hass.services.async_register(
DOMAIN, SERVICE_ADD_TORRENT, add_torrent, schema=SERVICE_ADD_TORRENT_SCHEMA
)
self.hass.services.async_register(
DOMAIN,
SERVICE_REMOVE_TORRENT,
remove_torrent,
schema=SERVICE_REMOVE_TORRENT_SCHEMA,
)
self.config_entry.add_update_listener(self.async_options_updated)
return True | [
"async",
"def",
"async_setup",
"(",
"self",
")",
":",
"try",
":",
"self",
".",
"tm_api",
"=",
"await",
"get_api",
"(",
"self",
".",
"hass",
",",
"self",
".",
"config_entry",
".",
"data",
")",
"except",
"CannotConnect",
"as",
"error",
":",
"raise",
"ConfigEntryNotReady",
"from",
"error",
"except",
"(",
"AuthenticationError",
",",
"UnknownError",
")",
":",
"return",
"False",
"self",
".",
"_tm_data",
"=",
"TransmissionData",
"(",
"self",
".",
"hass",
",",
"self",
".",
"config_entry",
",",
"self",
".",
"tm_api",
")",
"await",
"self",
".",
"hass",
".",
"async_add_executor_job",
"(",
"self",
".",
"_tm_data",
".",
"init_torrent_list",
")",
"await",
"self",
".",
"hass",
".",
"async_add_executor_job",
"(",
"self",
".",
"_tm_data",
".",
"update",
")",
"self",
".",
"add_options",
"(",
")",
"self",
".",
"set_scan_interval",
"(",
"self",
".",
"config_entry",
".",
"options",
"[",
"CONF_SCAN_INTERVAL",
"]",
")",
"for",
"platform",
"in",
"PLATFORMS",
":",
"self",
".",
"hass",
".",
"async_create_task",
"(",
"self",
".",
"hass",
".",
"config_entries",
".",
"async_forward_entry_setup",
"(",
"self",
".",
"config_entry",
",",
"platform",
")",
")",
"def",
"add_torrent",
"(",
"service",
")",
":",
"\"\"\"Add new torrent to download.\"\"\"",
"tm_client",
"=",
"None",
"for",
"entry",
"in",
"self",
".",
"hass",
".",
"config_entries",
".",
"async_entries",
"(",
"DOMAIN",
")",
":",
"if",
"entry",
".",
"data",
"[",
"CONF_NAME",
"]",
"==",
"service",
".",
"data",
"[",
"CONF_NAME",
"]",
":",
"tm_client",
"=",
"self",
".",
"hass",
".",
"data",
"[",
"DOMAIN",
"]",
"[",
"entry",
".",
"entry_id",
"]",
"break",
"if",
"tm_client",
"is",
"None",
":",
"_LOGGER",
".",
"error",
"(",
"\"Transmission instance is not found\"",
")",
"return",
"torrent",
"=",
"service",
".",
"data",
"[",
"ATTR_TORRENT",
"]",
"if",
"torrent",
".",
"startswith",
"(",
"(",
"\"http\"",
",",
"\"ftp:\"",
",",
"\"magnet:\"",
")",
")",
"or",
"self",
".",
"hass",
".",
"config",
".",
"is_allowed_path",
"(",
"torrent",
")",
":",
"tm_client",
".",
"tm_api",
".",
"add_torrent",
"(",
"torrent",
")",
"tm_client",
".",
"api",
".",
"update",
"(",
")",
"else",
":",
"_LOGGER",
".",
"warning",
"(",
"\"Could not add torrent: unsupported type or no permission\"",
")",
"def",
"remove_torrent",
"(",
"service",
")",
":",
"\"\"\"Remove torrent.\"\"\"",
"tm_client",
"=",
"None",
"for",
"entry",
"in",
"self",
".",
"hass",
".",
"config_entries",
".",
"async_entries",
"(",
"DOMAIN",
")",
":",
"if",
"entry",
".",
"data",
"[",
"CONF_NAME",
"]",
"==",
"service",
".",
"data",
"[",
"CONF_NAME",
"]",
":",
"tm_client",
"=",
"self",
".",
"hass",
".",
"data",
"[",
"DOMAIN",
"]",
"[",
"entry",
".",
"entry_id",
"]",
"break",
"if",
"tm_client",
"is",
"None",
":",
"_LOGGER",
".",
"error",
"(",
"\"Transmission instance is not found\"",
")",
"return",
"torrent_id",
"=",
"service",
".",
"data",
"[",
"CONF_ID",
"]",
"delete_data",
"=",
"service",
".",
"data",
"[",
"ATTR_DELETE_DATA",
"]",
"tm_client",
".",
"tm_api",
".",
"remove_torrent",
"(",
"torrent_id",
",",
"delete_data",
"=",
"delete_data",
")",
"tm_client",
".",
"api",
".",
"update",
"(",
")",
"self",
".",
"hass",
".",
"services",
".",
"async_register",
"(",
"DOMAIN",
",",
"SERVICE_ADD_TORRENT",
",",
"add_torrent",
",",
"schema",
"=",
"SERVICE_ADD_TORRENT_SCHEMA",
")",
"self",
".",
"hass",
".",
"services",
".",
"async_register",
"(",
"DOMAIN",
",",
"SERVICE_REMOVE_TORRENT",
",",
"remove_torrent",
",",
"schema",
"=",
"SERVICE_REMOVE_TORRENT_SCHEMA",
",",
")",
"self",
".",
"config_entry",
".",
"add_update_listener",
"(",
"self",
".",
"async_options_updated",
")",
"return",
"True"
] | [
163,
4
] | [
236,
19
] | python | en | ['en', 'da', 'en'] | True |
TransmissionClient.add_options | (self) | Add options for entry. | Add options for entry. | def add_options(self):
"""Add options for entry."""
if not self.config_entry.options:
scan_interval = self.config_entry.data.get(
CONF_SCAN_INTERVAL, DEFAULT_SCAN_INTERVAL
)
limit = self.config_entry.data.get(CONF_LIMIT, DEFAULT_LIMIT)
order = self.config_entry.data.get(CONF_ORDER, DEFAULT_ORDER)
options = {
CONF_SCAN_INTERVAL: scan_interval,
CONF_LIMIT: limit,
CONF_ORDER: order,
}
self.hass.config_entries.async_update_entry(
self.config_entry, options=options
) | [
"def",
"add_options",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"config_entry",
".",
"options",
":",
"scan_interval",
"=",
"self",
".",
"config_entry",
".",
"data",
".",
"get",
"(",
"CONF_SCAN_INTERVAL",
",",
"DEFAULT_SCAN_INTERVAL",
")",
"limit",
"=",
"self",
".",
"config_entry",
".",
"data",
".",
"get",
"(",
"CONF_LIMIT",
",",
"DEFAULT_LIMIT",
")",
"order",
"=",
"self",
".",
"config_entry",
".",
"data",
".",
"get",
"(",
"CONF_ORDER",
",",
"DEFAULT_ORDER",
")",
"options",
"=",
"{",
"CONF_SCAN_INTERVAL",
":",
"scan_interval",
",",
"CONF_LIMIT",
":",
"limit",
",",
"CONF_ORDER",
":",
"order",
",",
"}",
"self",
".",
"hass",
".",
"config_entries",
".",
"async_update_entry",
"(",
"self",
".",
"config_entry",
",",
"options",
"=",
"options",
")"
] | [
238,
4
] | [
254,
13
] | python | en | ['en', 'en', 'en'] | True |
TransmissionClient.set_scan_interval | (self, scan_interval) | Update scan interval. | Update scan interval. | def set_scan_interval(self, scan_interval):
"""Update scan interval."""
def refresh(event_time):
"""Get the latest data from Transmission."""
self._tm_data.update()
if self.unsub_timer is not None:
self.unsub_timer()
self.unsub_timer = async_track_time_interval(
self.hass, refresh, timedelta(seconds=scan_interval)
) | [
"def",
"set_scan_interval",
"(",
"self",
",",
"scan_interval",
")",
":",
"def",
"refresh",
"(",
"event_time",
")",
":",
"\"\"\"Get the latest data from Transmission.\"\"\"",
"self",
".",
"_tm_data",
".",
"update",
"(",
")",
"if",
"self",
".",
"unsub_timer",
"is",
"not",
"None",
":",
"self",
".",
"unsub_timer",
"(",
")",
"self",
".",
"unsub_timer",
"=",
"async_track_time_interval",
"(",
"self",
".",
"hass",
",",
"refresh",
",",
"timedelta",
"(",
"seconds",
"=",
"scan_interval",
")",
")"
] | [
256,
4
] | [
267,
9
] | python | en | ['en', 'de', 'en'] | True |
TransmissionClient.async_options_updated | (hass, entry) | Triggered by config entry options updates. | Triggered by config entry options updates. | async def async_options_updated(hass, entry):
"""Triggered by config entry options updates."""
tm_client = hass.data[DOMAIN][entry.entry_id]
tm_client.set_scan_interval(entry.options[CONF_SCAN_INTERVAL])
await hass.async_add_executor_job(tm_client.api.update) | [
"async",
"def",
"async_options_updated",
"(",
"hass",
",",
"entry",
")",
":",
"tm_client",
"=",
"hass",
".",
"data",
"[",
"DOMAIN",
"]",
"[",
"entry",
".",
"entry_id",
"]",
"tm_client",
".",
"set_scan_interval",
"(",
"entry",
".",
"options",
"[",
"CONF_SCAN_INTERVAL",
"]",
")",
"await",
"hass",
".",
"async_add_executor_job",
"(",
"tm_client",
".",
"api",
".",
"update",
")"
] | [
270,
4
] | [
274,
63
] | python | en | ['en', 'en', 'en'] | True |
TransmissionData.__init__ | (self, hass, config, api) | Initialize the Transmission RPC API. | Initialize the Transmission RPC API. | def __init__(self, hass, config, api):
"""Initialize the Transmission RPC API."""
self.hass = hass
self.config = config
self.data = None
self.torrents = []
self.session = None
self.available = True
self._api = api
self.completed_torrents = []
self.started_torrents = []
self.all_torrents = [] | [
"def",
"__init__",
"(",
"self",
",",
"hass",
",",
"config",
",",
"api",
")",
":",
"self",
".",
"hass",
"=",
"hass",
"self",
".",
"config",
"=",
"config",
"self",
".",
"data",
"=",
"None",
"self",
".",
"torrents",
"=",
"[",
"]",
"self",
".",
"session",
"=",
"None",
"self",
".",
"available",
"=",
"True",
"self",
".",
"_api",
"=",
"api",
"self",
".",
"completed_torrents",
"=",
"[",
"]",
"self",
".",
"started_torrents",
"=",
"[",
"]",
"self",
".",
"all_torrents",
"=",
"[",
"]"
] | [
280,
4
] | [
291,
30
] | python | en | ['en', 'en', 'en'] | True |
TransmissionData.host | (self) | Return the host name. | Return the host name. | def host(self):
"""Return the host name."""
return self.config.data[CONF_HOST] | [
"def",
"host",
"(",
"self",
")",
":",
"return",
"self",
".",
"config",
".",
"data",
"[",
"CONF_HOST",
"]"
] | [
294,
4
] | [
296,
42
] | python | en | ['en', 'no', 'en'] | True |
TransmissionData.signal_update | (self) | Update signal per transmission entry. | Update signal per transmission entry. | def signal_update(self):
"""Update signal per transmission entry."""
return f"{DATA_UPDATED}-{self.host}" | [
"def",
"signal_update",
"(",
"self",
")",
":",
"return",
"f\"{DATA_UPDATED}-{self.host}\""
] | [
299,
4
] | [
301,
44
] | python | en | ['en', 'en', 'it'] | True |
TransmissionData.update | (self) | Get the latest data from Transmission instance. | Get the latest data from Transmission instance. | def update(self):
"""Get the latest data from Transmission instance."""
try:
self.data = self._api.session_stats()
self.torrents = self._api.get_torrents()
self.session = self._api.get_session()
self.check_completed_torrent()
self.check_started_torrent()
self.check_removed_torrent()
_LOGGER.debug("Torrent Data for %s Updated", self.host)
self.available = True
except TransmissionError:
self.available = False
_LOGGER.error("Unable to connect to Transmission client %s", self.host)
dispatcher_send(self.hass, self.signal_update) | [
"def",
"update",
"(",
"self",
")",
":",
"try",
":",
"self",
".",
"data",
"=",
"self",
".",
"_api",
".",
"session_stats",
"(",
")",
"self",
".",
"torrents",
"=",
"self",
".",
"_api",
".",
"get_torrents",
"(",
")",
"self",
".",
"session",
"=",
"self",
".",
"_api",
".",
"get_session",
"(",
")",
"self",
".",
"check_completed_torrent",
"(",
")",
"self",
".",
"check_started_torrent",
"(",
")",
"self",
".",
"check_removed_torrent",
"(",
")",
"_LOGGER",
".",
"debug",
"(",
"\"Torrent Data for %s Updated\"",
",",
"self",
".",
"host",
")",
"self",
".",
"available",
"=",
"True",
"except",
"TransmissionError",
":",
"self",
".",
"available",
"=",
"False",
"_LOGGER",
".",
"error",
"(",
"\"Unable to connect to Transmission client %s\"",
",",
"self",
".",
"host",
")",
"dispatcher_send",
"(",
"self",
".",
"hass",
",",
"self",
".",
"signal_update",
")"
] | [
303,
4
] | [
319,
54
] | python | en | ['en', 'en', 'en'] | True |
TransmissionData.init_torrent_list | (self) | Initialize torrent lists. | Initialize torrent lists. | def init_torrent_list(self):
"""Initialize torrent lists."""
self.torrents = self._api.get_torrents()
self.completed_torrents = [
x.name for x in self.torrents if x.status == "seeding"
]
self.started_torrents = [
x.name for x in self.torrents if x.status == "downloading"
] | [
"def",
"init_torrent_list",
"(",
"self",
")",
":",
"self",
".",
"torrents",
"=",
"self",
".",
"_api",
".",
"get_torrents",
"(",
")",
"self",
".",
"completed_torrents",
"=",
"[",
"x",
".",
"name",
"for",
"x",
"in",
"self",
".",
"torrents",
"if",
"x",
".",
"status",
"==",
"\"seeding\"",
"]",
"self",
".",
"started_torrents",
"=",
"[",
"x",
".",
"name",
"for",
"x",
"in",
"self",
".",
"torrents",
"if",
"x",
".",
"status",
"==",
"\"downloading\"",
"]"
] | [
321,
4
] | [
329,
9
] | python | en | ['fr', 'en', 'it'] | False |
TransmissionData.check_completed_torrent | (self) | Get completed torrent functionality. | Get completed torrent functionality. | def check_completed_torrent(self):
"""Get completed torrent functionality."""
actual_torrents = self.torrents
actual_completed_torrents = [
var.name for var in actual_torrents if var.status == "seeding"
]
tmp_completed_torrents = list(
set(actual_completed_torrents).difference(self.completed_torrents)
)
for var in tmp_completed_torrents:
self.hass.bus.fire(EVENT_DOWNLOADED_TORRENT, {"name": var})
self.completed_torrents = actual_completed_torrents | [
"def",
"check_completed_torrent",
"(",
"self",
")",
":",
"actual_torrents",
"=",
"self",
".",
"torrents",
"actual_completed_torrents",
"=",
"[",
"var",
".",
"name",
"for",
"var",
"in",
"actual_torrents",
"if",
"var",
".",
"status",
"==",
"\"seeding\"",
"]",
"tmp_completed_torrents",
"=",
"list",
"(",
"set",
"(",
"actual_completed_torrents",
")",
".",
"difference",
"(",
"self",
".",
"completed_torrents",
")",
")",
"for",
"var",
"in",
"tmp_completed_torrents",
":",
"self",
".",
"hass",
".",
"bus",
".",
"fire",
"(",
"EVENT_DOWNLOADED_TORRENT",
",",
"{",
"\"name\"",
":",
"var",
"}",
")",
"self",
".",
"completed_torrents",
"=",
"actual_completed_torrents"
] | [
331,
4
] | [
345,
59
] | python | en | ['en', 'en', 'en'] | True |
TransmissionData.check_started_torrent | (self) | Get started torrent functionality. | Get started torrent functionality. | def check_started_torrent(self):
"""Get started torrent functionality."""
actual_torrents = self.torrents
actual_started_torrents = [
var.name for var in actual_torrents if var.status == "downloading"
]
tmp_started_torrents = list(
set(actual_started_torrents).difference(self.started_torrents)
)
for var in tmp_started_torrents:
self.hass.bus.fire(EVENT_STARTED_TORRENT, {"name": var})
self.started_torrents = actual_started_torrents | [
"def",
"check_started_torrent",
"(",
"self",
")",
":",
"actual_torrents",
"=",
"self",
".",
"torrents",
"actual_started_torrents",
"=",
"[",
"var",
".",
"name",
"for",
"var",
"in",
"actual_torrents",
"if",
"var",
".",
"status",
"==",
"\"downloading\"",
"]",
"tmp_started_torrents",
"=",
"list",
"(",
"set",
"(",
"actual_started_torrents",
")",
".",
"difference",
"(",
"self",
".",
"started_torrents",
")",
")",
"for",
"var",
"in",
"tmp_started_torrents",
":",
"self",
".",
"hass",
".",
"bus",
".",
"fire",
"(",
"EVENT_STARTED_TORRENT",
",",
"{",
"\"name\"",
":",
"var",
"}",
")",
"self",
".",
"started_torrents",
"=",
"actual_started_torrents"
] | [
347,
4
] | [
360,
55
] | python | en | ['en', 'en', 'en'] | True |
TransmissionData.check_removed_torrent | (self) | Get removed torrent functionality. | Get removed torrent functionality. | def check_removed_torrent(self):
"""Get removed torrent functionality."""
actual_torrents = self.torrents
actual_all_torrents = [var.name for var in actual_torrents]
removed_torrents = list(set(self.all_torrents).difference(actual_all_torrents))
for var in removed_torrents:
self.hass.bus.fire(EVENT_REMOVED_TORRENT, {"name": var})
self.all_torrents = actual_all_torrents | [
"def",
"check_removed_torrent",
"(",
"self",
")",
":",
"actual_torrents",
"=",
"self",
".",
"torrents",
"actual_all_torrents",
"=",
"[",
"var",
".",
"name",
"for",
"var",
"in",
"actual_torrents",
"]",
"removed_torrents",
"=",
"list",
"(",
"set",
"(",
"self",
".",
"all_torrents",
")",
".",
"difference",
"(",
"actual_all_torrents",
")",
")",
"for",
"var",
"in",
"removed_torrents",
":",
"self",
".",
"hass",
".",
"bus",
".",
"fire",
"(",
"EVENT_REMOVED_TORRENT",
",",
"{",
"\"name\"",
":",
"var",
"}",
")",
"self",
".",
"all_torrents",
"=",
"actual_all_torrents"
] | [
362,
4
] | [
370,
47
] | python | en | ['en', 'en', 'en'] | True |
TransmissionData.start_torrents | (self) | Start all torrents. | Start all torrents. | def start_torrents(self):
"""Start all torrents."""
if len(self.torrents) <= 0:
return
self._api.start_all() | [
"def",
"start_torrents",
"(",
"self",
")",
":",
"if",
"len",
"(",
"self",
".",
"torrents",
")",
"<=",
"0",
":",
"return",
"self",
".",
"_api",
".",
"start_all",
"(",
")"
] | [
372,
4
] | [
376,
29
] | python | en | ['en', 'no', 'en'] | True |
TransmissionData.stop_torrents | (self) | Stop all active torrents. | Stop all active torrents. | def stop_torrents(self):
"""Stop all active torrents."""
torrent_ids = [torrent.id for torrent in self.torrents]
self._api.stop_torrent(torrent_ids) | [
"def",
"stop_torrents",
"(",
"self",
")",
":",
"torrent_ids",
"=",
"[",
"torrent",
".",
"id",
"for",
"torrent",
"in",
"self",
".",
"torrents",
"]",
"self",
".",
"_api",
".",
"stop_torrent",
"(",
"torrent_ids",
")"
] | [
378,
4
] | [
381,
43
] | python | en | ['en', 'nl', 'en'] | True |
TransmissionData.set_alt_speed_enabled | (self, is_enabled) | Set the alternative speed flag. | Set the alternative speed flag. | def set_alt_speed_enabled(self, is_enabled):
"""Set the alternative speed flag."""
self._api.set_session(alt_speed_enabled=is_enabled) | [
"def",
"set_alt_speed_enabled",
"(",
"self",
",",
"is_enabled",
")",
":",
"self",
".",
"_api",
".",
"set_session",
"(",
"alt_speed_enabled",
"=",
"is_enabled",
")"
] | [
383,
4
] | [
385,
59
] | python | en | ['en', 'et', 'en'] | True |
TransmissionData.get_alt_speed_enabled | (self) | Get the alternative speed flag. | Get the alternative speed flag. | def get_alt_speed_enabled(self):
"""Get the alternative speed flag."""
if self.session is None:
return None
return self.session.alt_speed_enabled | [
"def",
"get_alt_speed_enabled",
"(",
"self",
")",
":",
"if",
"self",
".",
"session",
"is",
"None",
":",
"return",
"None",
"return",
"self",
".",
"session",
".",
"alt_speed_enabled"
] | [
387,
4
] | [
392,
45
] | python | en | ['en', 'de', 'en'] | True |
debug_mutated_model | (base_model, trainer, applied_mutators) |
Locally run only one trial without launching an experiment for debug purpose, then exit.
For example, it can be used to quickly check shape mismatch.
Specifically, it applies mutators (default to choose the first candidate for the choices)
to generate a new model, then run this model locally.
Parameters
----------
base_model : nni.retiarii.nn.pytorch.nn.Module
the base model
trainer : nni.retiarii.evaluator
the training class of the generated models
applied_mutators : list
a list of mutators that will be applied on the base model for generating a new model
|
Locally run only one trial without launching an experiment for debug purpose, then exit.
For example, it can be used to quickly check shape mismatch. | def debug_mutated_model(base_model, trainer, applied_mutators):
"""
Locally run only one trial without launching an experiment for debug purpose, then exit.
For example, it can be used to quickly check shape mismatch.
Specifically, it applies mutators (default to choose the first candidate for the choices)
to generate a new model, then run this model locally.
Parameters
----------
base_model : nni.retiarii.nn.pytorch.nn.Module
the base model
trainer : nni.retiarii.evaluator
the training class of the generated models
applied_mutators : list
a list of mutators that will be applied on the base model for generating a new model
"""
base_model_ir, applied_mutators = preprocess_model(base_model, trainer, applied_mutators)
from ..strategy import _LocalDebugStrategy
strategy = _LocalDebugStrategy()
strategy.run(base_model_ir, applied_mutators)
_logger.info('local debug completed!') | [
"def",
"debug_mutated_model",
"(",
"base_model",
",",
"trainer",
",",
"applied_mutators",
")",
":",
"base_model_ir",
",",
"applied_mutators",
"=",
"preprocess_model",
"(",
"base_model",
",",
"trainer",
",",
"applied_mutators",
")",
"from",
".",
".",
"strategy",
"import",
"_LocalDebugStrategy",
"strategy",
"=",
"_LocalDebugStrategy",
"(",
")",
"strategy",
".",
"run",
"(",
"base_model_ir",
",",
"applied_mutators",
")",
"_logger",
".",
"info",
"(",
"'local debug completed!'",
")"
] | [
130,
0
] | [
151,
42
] | python | en | ['en', 'error', 'th'] | False |
RetiariiExperiment.start | (self, port: int = 8080, debug: bool = False) |
Start the experiment in background.
This method will raise exception on failure.
If it returns, the experiment should have been successfully started.
Parameters
----------
port
The port of web UI.
debug
Whether to start in debug mode.
|
Start the experiment in background.
This method will raise exception on failure.
If it returns, the experiment should have been successfully started.
Parameters
----------
port
The port of web UI.
debug
Whether to start in debug mode.
| def start(self, port: int = 8080, debug: bool = False) -> None:
"""
Start the experiment in background.
This method will raise exception on failure.
If it returns, the experiment should have been successfully started.
Parameters
----------
port
The port of web UI.
debug
Whether to start in debug mode.
"""
atexit.register(self.stop)
# we will probably need a execution engine factory to make this clean and elegant
if self.config.execution_engine == 'base':
from ..execution.base import BaseExecutionEngine
engine = BaseExecutionEngine()
elif self.config.execution_engine == 'cgo':
from ..execution.cgo_engine import CGOExecutionEngine
engine = CGOExecutionEngine()
elif self.config.execution_engine == 'py':
from ..execution.python import PurePythonExecutionEngine
engine = PurePythonExecutionEngine()
set_execution_engine(engine)
self.id = management.generate_experiment_id()
if self.config.experiment_working_directory is not None:
log_dir = Path(self.config.experiment_working_directory, self.id, 'log')
else:
log_dir = Path.home() / f'nni-experiments/{self.id}/log'
nni.runtime.log.start_experiment_log(self.id, log_dir, debug)
self._proc, self._pipe = launcher.start_experiment_retiarii(self.id, self.config, port, debug)
assert self._proc is not None
assert self._pipe is not None
self.port = port # port will be None if start up failed
# dispatcher must be launched after pipe initialized
# the logic to launch dispatcher in background should be refactored into dispatcher api
self._dispatcher = self._create_dispatcher()
self._dispatcher_thread = Thread(target=self._dispatcher.run)
self._dispatcher_thread.start()
ips = [self.config.nni_manager_ip]
for interfaces in psutil.net_if_addrs().values():
for interface in interfaces:
if interface.family == socket.AF_INET:
ips.append(interface.address)
ips = [f'http://{ip}:{port}' for ip in ips if ip]
msg = 'Web UI URLs: ' + colorama.Fore.CYAN + ' '.join(ips) + colorama.Style.RESET_ALL
_logger.info(msg)
exp_status_checker = Thread(target=self._check_exp_status)
exp_status_checker.start()
self._start_strategy()
# TODO: the experiment should be completed, when strategy exits and there is no running job
_logger.info('Waiting for experiment to become DONE (you can ctrl+c if there is no running trial jobs)...')
exp_status_checker.join() | [
"def",
"start",
"(",
"self",
",",
"port",
":",
"int",
"=",
"8080",
",",
"debug",
":",
"bool",
"=",
"False",
")",
"->",
"None",
":",
"atexit",
".",
"register",
"(",
"self",
".",
"stop",
")",
"# we will probably need a execution engine factory to make this clean and elegant",
"if",
"self",
".",
"config",
".",
"execution_engine",
"==",
"'base'",
":",
"from",
".",
".",
"execution",
".",
"base",
"import",
"BaseExecutionEngine",
"engine",
"=",
"BaseExecutionEngine",
"(",
")",
"elif",
"self",
".",
"config",
".",
"execution_engine",
"==",
"'cgo'",
":",
"from",
".",
".",
"execution",
".",
"cgo_engine",
"import",
"CGOExecutionEngine",
"engine",
"=",
"CGOExecutionEngine",
"(",
")",
"elif",
"self",
".",
"config",
".",
"execution_engine",
"==",
"'py'",
":",
"from",
".",
".",
"execution",
".",
"python",
"import",
"PurePythonExecutionEngine",
"engine",
"=",
"PurePythonExecutionEngine",
"(",
")",
"set_execution_engine",
"(",
"engine",
")",
"self",
".",
"id",
"=",
"management",
".",
"generate_experiment_id",
"(",
")",
"if",
"self",
".",
"config",
".",
"experiment_working_directory",
"is",
"not",
"None",
":",
"log_dir",
"=",
"Path",
"(",
"self",
".",
"config",
".",
"experiment_working_directory",
",",
"self",
".",
"id",
",",
"'log'",
")",
"else",
":",
"log_dir",
"=",
"Path",
".",
"home",
"(",
")",
"/",
"f'nni-experiments/{self.id}/log'",
"nni",
".",
"runtime",
".",
"log",
".",
"start_experiment_log",
"(",
"self",
".",
"id",
",",
"log_dir",
",",
"debug",
")",
"self",
".",
"_proc",
",",
"self",
".",
"_pipe",
"=",
"launcher",
".",
"start_experiment_retiarii",
"(",
"self",
".",
"id",
",",
"self",
".",
"config",
",",
"port",
",",
"debug",
")",
"assert",
"self",
".",
"_proc",
"is",
"not",
"None",
"assert",
"self",
".",
"_pipe",
"is",
"not",
"None",
"self",
".",
"port",
"=",
"port",
"# port will be None if start up failed",
"# dispatcher must be launched after pipe initialized",
"# the logic to launch dispatcher in background should be refactored into dispatcher api",
"self",
".",
"_dispatcher",
"=",
"self",
".",
"_create_dispatcher",
"(",
")",
"self",
".",
"_dispatcher_thread",
"=",
"Thread",
"(",
"target",
"=",
"self",
".",
"_dispatcher",
".",
"run",
")",
"self",
".",
"_dispatcher_thread",
".",
"start",
"(",
")",
"ips",
"=",
"[",
"self",
".",
"config",
".",
"nni_manager_ip",
"]",
"for",
"interfaces",
"in",
"psutil",
".",
"net_if_addrs",
"(",
")",
".",
"values",
"(",
")",
":",
"for",
"interface",
"in",
"interfaces",
":",
"if",
"interface",
".",
"family",
"==",
"socket",
".",
"AF_INET",
":",
"ips",
".",
"append",
"(",
"interface",
".",
"address",
")",
"ips",
"=",
"[",
"f'http://{ip}:{port}'",
"for",
"ip",
"in",
"ips",
"if",
"ip",
"]",
"msg",
"=",
"'Web UI URLs: '",
"+",
"colorama",
".",
"Fore",
".",
"CYAN",
"+",
"' '",
".",
"join",
"(",
"ips",
")",
"+",
"colorama",
".",
"Style",
".",
"RESET_ALL",
"_logger",
".",
"info",
"(",
"msg",
")",
"exp_status_checker",
"=",
"Thread",
"(",
"target",
"=",
"self",
".",
"_check_exp_status",
")",
"exp_status_checker",
".",
"start",
"(",
")",
"self",
".",
"_start_strategy",
"(",
")",
"# TODO: the experiment should be completed, when strategy exits and there is no running job",
"_logger",
".",
"info",
"(",
"'Waiting for experiment to become DONE (you can ctrl+c if there is no running trial jobs)...'",
")",
"exp_status_checker",
".",
"join",
"(",
")"
] | [
181,
4
] | [
241,
33
] | python | en | ['en', 'error', 'th'] | False |
RetiariiExperiment.run | (self, config: RetiariiExeConfig = None, port: int = 8080, debug: bool = False) |
Run the experiment.
This function will block until experiment finish or error.
|
Run the experiment.
This function will block until experiment finish or error.
| def run(self, config: RetiariiExeConfig = None, port: int = 8080, debug: bool = False) -> str:
"""
Run the experiment.
This function will block until experiment finish or error.
"""
if isinstance(self.trainer, BaseOneShotTrainer):
self.trainer.fit()
else:
assert config is not None, 'You are using classic search mode, config cannot be None!'
self.config = config
self.start(port, debug) | [
"def",
"run",
"(",
"self",
",",
"config",
":",
"RetiariiExeConfig",
"=",
"None",
",",
"port",
":",
"int",
"=",
"8080",
",",
"debug",
":",
"bool",
"=",
"False",
")",
"->",
"str",
":",
"if",
"isinstance",
"(",
"self",
".",
"trainer",
",",
"BaseOneShotTrainer",
")",
":",
"self",
".",
"trainer",
".",
"fit",
"(",
")",
"else",
":",
"assert",
"config",
"is",
"not",
"None",
",",
"'You are using classic search mode, config cannot be None!'",
"self",
".",
"config",
"=",
"config",
"self",
".",
"start",
"(",
"port",
",",
"debug",
")"
] | [
246,
4
] | [
256,
35
] | python | en | ['en', 'error', 'th'] | False |
RetiariiExperiment._check_exp_status | (self) |
Run the experiment.
This function will block until experiment finish or error.
Return `True` when experiment done; or return `False` when experiment failed.
|
Run the experiment.
This function will block until experiment finish or error.
Return `True` when experiment done; or return `False` when experiment failed.
| def _check_exp_status(self) -> bool:
"""
Run the experiment.
This function will block until experiment finish or error.
Return `True` when experiment done; or return `False` when experiment failed.
"""
try:
while True:
time.sleep(10)
# this if is to deal with the situation that
# nnimanager is cleaned up by ctrl+c first
if self._proc.poll() is None:
status = self.get_status()
else:
return False
if status == 'DONE' or status == 'STOPPED':
return True
if status == 'ERROR':
return False
except KeyboardInterrupt:
_logger.warning('KeyboardInterrupt detected')
finally:
self.stop() | [
"def",
"_check_exp_status",
"(",
"self",
")",
"->",
"bool",
":",
"try",
":",
"while",
"True",
":",
"time",
".",
"sleep",
"(",
"10",
")",
"# this if is to deal with the situation that",
"# nnimanager is cleaned up by ctrl+c first",
"if",
"self",
".",
"_proc",
".",
"poll",
"(",
")",
"is",
"None",
":",
"status",
"=",
"self",
".",
"get_status",
"(",
")",
"else",
":",
"return",
"False",
"if",
"status",
"==",
"'DONE'",
"or",
"status",
"==",
"'STOPPED'",
":",
"return",
"True",
"if",
"status",
"==",
"'ERROR'",
":",
"return",
"False",
"except",
"KeyboardInterrupt",
":",
"_logger",
".",
"warning",
"(",
"'KeyboardInterrupt detected'",
")",
"finally",
":",
"self",
".",
"stop",
"(",
")"
] | [
258,
4
] | [
280,
23
] | python | en | ['en', 'error', 'th'] | False |
RetiariiExperiment.stop | (self) |
Stop background experiment.
|
Stop background experiment.
| def stop(self) -> None:
"""
Stop background experiment.
"""
_logger.info('Stopping experiment, please wait...')
atexit.unregister(self.stop)
if self.id is not None:
nni.runtime.log.stop_experiment_log(self.id)
if self._proc is not None:
try:
# this if is to deal with the situation that
# nnimanager is cleaned up by ctrl+c first
if self._proc.poll() is None:
rest.delete(self.port, '/experiment')
except Exception as e:
_logger.exception(e)
_logger.warning('Cannot gracefully stop experiment, killing NNI process...')
kill_command(self._proc.pid)
if self._pipe is not None:
self._pipe.close()
if self._dispatcher_thread is not None:
self._dispatcher.stopping = True
self._dispatcher_thread.join(timeout=1)
self.id = None
self.port = None
self._proc = None
self._pipe = None
self._dispatcher = None
self._dispatcher_thread = None
_logger.info('Experiment stopped') | [
"def",
"stop",
"(",
"self",
")",
"->",
"None",
":",
"_logger",
".",
"info",
"(",
"'Stopping experiment, please wait...'",
")",
"atexit",
".",
"unregister",
"(",
"self",
".",
"stop",
")",
"if",
"self",
".",
"id",
"is",
"not",
"None",
":",
"nni",
".",
"runtime",
".",
"log",
".",
"stop_experiment_log",
"(",
"self",
".",
"id",
")",
"if",
"self",
".",
"_proc",
"is",
"not",
"None",
":",
"try",
":",
"# this if is to deal with the situation that",
"# nnimanager is cleaned up by ctrl+c first",
"if",
"self",
".",
"_proc",
".",
"poll",
"(",
")",
"is",
"None",
":",
"rest",
".",
"delete",
"(",
"self",
".",
"port",
",",
"'/experiment'",
")",
"except",
"Exception",
"as",
"e",
":",
"_logger",
".",
"exception",
"(",
"e",
")",
"_logger",
".",
"warning",
"(",
"'Cannot gracefully stop experiment, killing NNI process...'",
")",
"kill_command",
"(",
"self",
".",
"_proc",
".",
"pid",
")",
"if",
"self",
".",
"_pipe",
"is",
"not",
"None",
":",
"self",
".",
"_pipe",
".",
"close",
"(",
")",
"if",
"self",
".",
"_dispatcher_thread",
"is",
"not",
"None",
":",
"self",
".",
"_dispatcher",
".",
"stopping",
"=",
"True",
"self",
".",
"_dispatcher_thread",
".",
"join",
"(",
"timeout",
"=",
"1",
")",
"self",
".",
"id",
"=",
"None",
"self",
".",
"port",
"=",
"None",
"self",
".",
"_proc",
"=",
"None",
"self",
".",
"_pipe",
"=",
"None",
"self",
".",
"_dispatcher",
"=",
"None",
"self",
".",
"_dispatcher_thread",
"=",
"None",
"_logger",
".",
"info",
"(",
"'Experiment stopped'",
")"
] | [
282,
4
] | [
314,
42
] | python | en | ['en', 'error', 'th'] | False |
RetiariiExperiment.export_top_models | (self, top_k: int = 1, optimize_mode: str = 'maximize', formatter: str = 'code') |
Export several top performing models.
For one-shot algorithms, only top-1 is supported. For others, ``optimize_mode`` and ``formatter`` are
available for customization.
top_k : int
How many models are intended to be exported.
optimize_mode : str
``maximize`` or ``minimize``. Not supported by one-shot algorithms.
``optimize_mode`` is likely to be removed and defined in strategy in future.
formatter : str
Support ``code`` and ``dict``. Not supported by one-shot algorithms.
If ``code``, the python code of model will be returned.
If ``dict``, the mutation history will be returned.
|
Export several top performing models. | def export_top_models(self, top_k: int = 1, optimize_mode: str = 'maximize', formatter: str = 'code') -> Any:
"""
Export several top performing models.
For one-shot algorithms, only top-1 is supported. For others, ``optimize_mode`` and ``formatter`` are
available for customization.
top_k : int
How many models are intended to be exported.
optimize_mode : str
``maximize`` or ``minimize``. Not supported by one-shot algorithms.
``optimize_mode`` is likely to be removed and defined in strategy in future.
formatter : str
Support ``code`` and ``dict``. Not supported by one-shot algorithms.
If ``code``, the python code of model will be returned.
If ``dict``, the mutation history will be returned.
"""
if formatter == 'code':
assert self.config.execution_engine != 'py', 'You should use `dict` formatter when using Python execution engine.'
if isinstance(self.trainer, BaseOneShotTrainer):
assert top_k == 1, 'Only support top_k is 1 for now.'
return self.trainer.export()
else:
all_models = filter(lambda m: m.metric is not None, list_models())
assert optimize_mode in ['maximize', 'minimize']
all_models = sorted(all_models, key=lambda m: m.metric, reverse=optimize_mode == 'maximize')
assert formatter in ['code', 'dict'], 'Export formatter other than "code" and "dict" is not supported yet.'
if formatter == 'code':
return [model_to_pytorch_script(model) for model in all_models[:top_k]]
elif formatter == 'dict':
return [get_mutation_dict(model) for model in all_models[:top_k]] | [
"def",
"export_top_models",
"(",
"self",
",",
"top_k",
":",
"int",
"=",
"1",
",",
"optimize_mode",
":",
"str",
"=",
"'maximize'",
",",
"formatter",
":",
"str",
"=",
"'code'",
")",
"->",
"Any",
":",
"if",
"formatter",
"==",
"'code'",
":",
"assert",
"self",
".",
"config",
".",
"execution_engine",
"!=",
"'py'",
",",
"'You should use `dict` formatter when using Python execution engine.'",
"if",
"isinstance",
"(",
"self",
".",
"trainer",
",",
"BaseOneShotTrainer",
")",
":",
"assert",
"top_k",
"==",
"1",
",",
"'Only support top_k is 1 for now.'",
"return",
"self",
".",
"trainer",
".",
"export",
"(",
")",
"else",
":",
"all_models",
"=",
"filter",
"(",
"lambda",
"m",
":",
"m",
".",
"metric",
"is",
"not",
"None",
",",
"list_models",
"(",
")",
")",
"assert",
"optimize_mode",
"in",
"[",
"'maximize'",
",",
"'minimize'",
"]",
"all_models",
"=",
"sorted",
"(",
"all_models",
",",
"key",
"=",
"lambda",
"m",
":",
"m",
".",
"metric",
",",
"reverse",
"=",
"optimize_mode",
"==",
"'maximize'",
")",
"assert",
"formatter",
"in",
"[",
"'code'",
",",
"'dict'",
"]",
",",
"'Export formatter other than \"code\" and \"dict\" is not supported yet.'",
"if",
"formatter",
"==",
"'code'",
":",
"return",
"[",
"model_to_pytorch_script",
"(",
"model",
")",
"for",
"model",
"in",
"all_models",
"[",
":",
"top_k",
"]",
"]",
"elif",
"formatter",
"==",
"'dict'",
":",
"return",
"[",
"get_mutation_dict",
"(",
"model",
")",
"for",
"model",
"in",
"all_models",
"[",
":",
"top_k",
"]",
"]"
] | [
316,
4
] | [
346,
81
] | python | en | ['en', 'error', 'th'] | False |
RetiariiExperiment.retrain_model | (self, model) |
this function retrains the exported model, and test it to output test accuracy
|
this function retrains the exported model, and test it to output test accuracy
| def retrain_model(self, model):
"""
this function retrains the exported model, and test it to output test accuracy
"""
raise NotImplementedError | [
"def",
"retrain_model",
"(",
"self",
",",
"model",
")",
":",
"raise",
"NotImplementedError"
] | [
348,
4
] | [
352,
33
] | python | en | ['en', 'error', 'th'] | False |
async_setup_entry | (hass, config_entry, async_add_entities) | Set up device tracker for Mikrotik component. | Set up device tracker for Mikrotik component. | async def async_setup_entry(hass, config_entry, async_add_entities):
"""Set up device tracker for Mikrotik component."""
hub = hass.data[DOMAIN][config_entry.entry_id]
tracked = {}
registry = await entity_registry.async_get_registry(hass)
# Restore clients that is not a part of active clients list.
for entity in registry.entities.values():
if (
entity.config_entry_id == config_entry.entry_id
and entity.domain == DEVICE_TRACKER
):
if (
entity.unique_id in hub.api.devices
or entity.unique_id not in hub.api.all_devices
):
continue
hub.api.restore_device(entity.unique_id)
@callback
def update_hub():
"""Update the status of the device."""
update_items(hub, async_add_entities, tracked)
async_dispatcher_connect(hass, hub.signal_update, update_hub)
update_hub() | [
"async",
"def",
"async_setup_entry",
"(",
"hass",
",",
"config_entry",
",",
"async_add_entities",
")",
":",
"hub",
"=",
"hass",
".",
"data",
"[",
"DOMAIN",
"]",
"[",
"config_entry",
".",
"entry_id",
"]",
"tracked",
"=",
"{",
"}",
"registry",
"=",
"await",
"entity_registry",
".",
"async_get_registry",
"(",
"hass",
")",
"# Restore clients that is not a part of active clients list.",
"for",
"entity",
"in",
"registry",
".",
"entities",
".",
"values",
"(",
")",
":",
"if",
"(",
"entity",
".",
"config_entry_id",
"==",
"config_entry",
".",
"entry_id",
"and",
"entity",
".",
"domain",
"==",
"DEVICE_TRACKER",
")",
":",
"if",
"(",
"entity",
".",
"unique_id",
"in",
"hub",
".",
"api",
".",
"devices",
"or",
"entity",
".",
"unique_id",
"not",
"in",
"hub",
".",
"api",
".",
"all_devices",
")",
":",
"continue",
"hub",
".",
"api",
".",
"restore_device",
"(",
"entity",
".",
"unique_id",
")",
"@",
"callback",
"def",
"update_hub",
"(",
")",
":",
"\"\"\"Update the status of the device.\"\"\"",
"update_items",
"(",
"hub",
",",
"async_add_entities",
",",
"tracked",
")",
"async_dispatcher_connect",
"(",
"hass",
",",
"hub",
".",
"signal_update",
",",
"update_hub",
")",
"update_hub",
"(",
")"
] | [
19,
0
] | [
49,
16
] | python | en | ['da', 'en', 'en'] | True |
update_items | (hub, async_add_entities, tracked) | Update tracked device state from the hub. | Update tracked device state from the hub. | def update_items(hub, async_add_entities, tracked):
"""Update tracked device state from the hub."""
new_tracked = []
for mac, device in hub.api.devices.items():
if mac not in tracked:
tracked[mac] = MikrotikHubTracker(device, hub)
new_tracked.append(tracked[mac])
if new_tracked:
async_add_entities(new_tracked) | [
"def",
"update_items",
"(",
"hub",
",",
"async_add_entities",
",",
"tracked",
")",
":",
"new_tracked",
"=",
"[",
"]",
"for",
"mac",
",",
"device",
"in",
"hub",
".",
"api",
".",
"devices",
".",
"items",
"(",
")",
":",
"if",
"mac",
"not",
"in",
"tracked",
":",
"tracked",
"[",
"mac",
"]",
"=",
"MikrotikHubTracker",
"(",
"device",
",",
"hub",
")",
"new_tracked",
".",
"append",
"(",
"tracked",
"[",
"mac",
"]",
")",
"if",
"new_tracked",
":",
"async_add_entities",
"(",
"new_tracked",
")"
] | [
53,
0
] | [
62,
39
] | python | en | ['en', 'en', 'en'] | True |
MikrotikHubTracker.__init__ | (self, device, hub) | Initialize the tracked device. | Initialize the tracked device. | def __init__(self, device, hub):
"""Initialize the tracked device."""
self.device = device
self.hub = hub
self.unsub_dispatcher = None | [
"def",
"__init__",
"(",
"self",
",",
"device",
",",
"hub",
")",
":",
"self",
".",
"device",
"=",
"device",
"self",
".",
"hub",
"=",
"hub",
"self",
".",
"unsub_dispatcher",
"=",
"None"
] | [
68,
4
] | [
72,
36
] | python | en | ['en', 'en', 'en'] | True |
MikrotikHubTracker.is_connected | (self) | Return true if the client is connected to the network. | Return true if the client is connected to the network. | def is_connected(self):
"""Return true if the client is connected to the network."""
if (
self.device.last_seen
and (dt_util.utcnow() - self.device.last_seen)
< self.hub.option_detection_time
):
return True
return False | [
"def",
"is_connected",
"(",
"self",
")",
":",
"if",
"(",
"self",
".",
"device",
".",
"last_seen",
"and",
"(",
"dt_util",
".",
"utcnow",
"(",
")",
"-",
"self",
".",
"device",
".",
"last_seen",
")",
"<",
"self",
".",
"hub",
".",
"option_detection_time",
")",
":",
"return",
"True",
"return",
"False"
] | [
75,
4
] | [
83,
20
] | python | en | ['en', 'en', 'en'] | True |
MikrotikHubTracker.source_type | (self) | Return the source type of the client. | Return the source type of the client. | def source_type(self):
"""Return the source type of the client."""
return SOURCE_TYPE_ROUTER | [
"def",
"source_type",
"(",
"self",
")",
":",
"return",
"SOURCE_TYPE_ROUTER"
] | [
86,
4
] | [
88,
33
] | python | en | ['en', 'en', 'en'] | True |
MikrotikHubTracker.name | (self) | Return the name of the client. | Return the name of the client. | def name(self) -> str:
"""Return the name of the client."""
return self.device.name | [
"def",
"name",
"(",
"self",
")",
"->",
"str",
":",
"return",
"self",
".",
"device",
".",
"name"
] | [
91,
4
] | [
93,
31
] | python | en | ['en', 'en', 'en'] | True |
MikrotikHubTracker.unique_id | (self) | Return a unique identifier for this device. | Return a unique identifier for this device. | def unique_id(self) -> str:
"""Return a unique identifier for this device."""
return self.device.mac | [
"def",
"unique_id",
"(",
"self",
")",
"->",
"str",
":",
"return",
"self",
".",
"device",
".",
"mac"
] | [
96,
4
] | [
98,
30
] | python | en | ['en', 'en', 'en'] | True |
MikrotikHubTracker.available | (self) | Return if controller is available. | Return if controller is available. | def available(self) -> bool:
"""Return if controller is available."""
return self.hub.available | [
"def",
"available",
"(",
"self",
")",
"->",
"bool",
":",
"return",
"self",
".",
"hub",
".",
"available"
] | [
101,
4
] | [
103,
33
] | python | en | ['en', 'en', 'en'] | True |
MikrotikHubTracker.device_state_attributes | (self) | Return the device state attributes. | Return the device state attributes. | def device_state_attributes(self):
"""Return the device state attributes."""
if self.is_connected:
return self.device.attrs
return None | [
"def",
"device_state_attributes",
"(",
"self",
")",
":",
"if",
"self",
".",
"is_connected",
":",
"return",
"self",
".",
"device",
".",
"attrs",
"return",
"None"
] | [
106,
4
] | [
110,
19
] | python | en | ['en', 'en', 'en'] | True |
MikrotikHubTracker.device_info | (self) | Return a client description for device registry. | Return a client description for device registry. | def device_info(self):
"""Return a client description for device registry."""
info = {
"connections": {(CONNECTION_NETWORK_MAC, self.device.mac)},
"identifiers": {(DOMAIN, self.device.mac)},
# We only get generic info from device discovery and so don't want
# to override API specific info that integrations can provide
"default_name": self.name,
}
return info | [
"def",
"device_info",
"(",
"self",
")",
":",
"info",
"=",
"{",
"\"connections\"",
":",
"{",
"(",
"CONNECTION_NETWORK_MAC",
",",
"self",
".",
"device",
".",
"mac",
")",
"}",
",",
"\"identifiers\"",
":",
"{",
"(",
"DOMAIN",
",",
"self",
".",
"device",
".",
"mac",
")",
"}",
",",
"# We only get generic info from device discovery and so don't want",
"# to override API specific info that integrations can provide",
"\"default_name\"",
":",
"self",
".",
"name",
",",
"}",
"return",
"info"
] | [
113,
4
] | [
122,
19
] | python | ca | ['ca', 'fr', 'en'] | False |
MikrotikHubTracker.async_added_to_hass | (self) | Client entity created. | Client entity created. | async def async_added_to_hass(self):
"""Client entity created."""
_LOGGER.debug("New network device tracker %s (%s)", self.name, self.unique_id)
self.unsub_dispatcher = async_dispatcher_connect(
self.hass, self.hub.signal_update, self.async_write_ha_state
) | [
"async",
"def",
"async_added_to_hass",
"(",
"self",
")",
":",
"_LOGGER",
".",
"debug",
"(",
"\"New network device tracker %s (%s)\"",
",",
"self",
".",
"name",
",",
"self",
".",
"unique_id",
")",
"self",
".",
"unsub_dispatcher",
"=",
"async_dispatcher_connect",
"(",
"self",
".",
"hass",
",",
"self",
".",
"hub",
".",
"signal_update",
",",
"self",
".",
"async_write_ha_state",
")"
] | [
124,
4
] | [
129,
9
] | python | en | ['en', 'en', 'en'] | True |
MikrotikHubTracker.async_update | (self) | Synchronize state with hub. | Synchronize state with hub. | async def async_update(self):
"""Synchronize state with hub."""
_LOGGER.debug(
"Updating Mikrotik tracked client %s (%s)", self.entity_id, self.unique_id
)
await self.hub.request_update() | [
"async",
"def",
"async_update",
"(",
"self",
")",
":",
"_LOGGER",
".",
"debug",
"(",
"\"Updating Mikrotik tracked client %s (%s)\"",
",",
"self",
".",
"entity_id",
",",
"self",
".",
"unique_id",
")",
"await",
"self",
".",
"hub",
".",
"request_update",
"(",
")"
] | [
131,
4
] | [
136,
39
] | python | en | ['en', 'en', 'en'] | True |
MikrotikHubTracker.will_remove_from_hass | (self) | Disconnect from dispatcher. | Disconnect from dispatcher. | async def will_remove_from_hass(self):
"""Disconnect from dispatcher."""
if self.unsub_dispatcher:
self.unsub_dispatcher() | [
"async",
"def",
"will_remove_from_hass",
"(",
"self",
")",
":",
"if",
"self",
".",
"unsub_dispatcher",
":",
"self",
".",
"unsub_dispatcher",
"(",
")"
] | [
138,
4
] | [
141,
35
] | python | en | ['en', 'en', 'en'] | True |
test_reproducing_states | (hass, caplog) | Test reproducing Input text states. | Test reproducing Input text states. | async def test_reproducing_states(hass, caplog):
"""Test reproducing Input text states."""
# Setup entity for testing
assert await async_setup_component(
hass,
"input_text",
{
"input_text": {
"test_text": {"min": "6", "max": "10", "initial": VALID_TEXT1}
}
},
)
# These calls should do nothing as entities already in desired state
await hass.helpers.state.async_reproduce_state(
[
State("input_text.test_text", VALID_TEXT1),
# Should not raise
State("input_text.non_existing", VALID_TEXT1),
],
)
# Test that entity is in desired state
assert hass.states.get("input_text.test_text").state == VALID_TEXT1
# Try reproducing with different state
await hass.helpers.state.async_reproduce_state(
[
State("input_text.test_text", VALID_TEXT2),
# Should not raise
State("input_text.non_existing", VALID_TEXT2),
],
)
# Test that the state was changed
assert hass.states.get("input_text.test_text").state == VALID_TEXT2
# Test setting state to invalid state (length too long)
await hass.helpers.state.async_reproduce_state(
[State("input_text.test_text", INVALID_TEXT1)]
)
# The entity state should be unchanged
assert hass.states.get("input_text.test_text").state == VALID_TEXT2
# Test setting state to invalid state (length too short)
await hass.helpers.state.async_reproduce_state(
[State("input_text.test_text", INVALID_TEXT2)]
)
# The entity state should be unchanged
assert hass.states.get("input_text.test_text").state == VALID_TEXT2 | [
"async",
"def",
"test_reproducing_states",
"(",
"hass",
",",
"caplog",
")",
":",
"# Setup entity for testing",
"assert",
"await",
"async_setup_component",
"(",
"hass",
",",
"\"input_text\"",
",",
"{",
"\"input_text\"",
":",
"{",
"\"test_text\"",
":",
"{",
"\"min\"",
":",
"\"6\"",
",",
"\"max\"",
":",
"\"10\"",
",",
"\"initial\"",
":",
"VALID_TEXT1",
"}",
"}",
"}",
",",
")",
"# These calls should do nothing as entities already in desired state",
"await",
"hass",
".",
"helpers",
".",
"state",
".",
"async_reproduce_state",
"(",
"[",
"State",
"(",
"\"input_text.test_text\"",
",",
"VALID_TEXT1",
")",
",",
"# Should not raise",
"State",
"(",
"\"input_text.non_existing\"",
",",
"VALID_TEXT1",
")",
",",
"]",
",",
")",
"# Test that entity is in desired state",
"assert",
"hass",
".",
"states",
".",
"get",
"(",
"\"input_text.test_text\"",
")",
".",
"state",
"==",
"VALID_TEXT1",
"# Try reproducing with different state",
"await",
"hass",
".",
"helpers",
".",
"state",
".",
"async_reproduce_state",
"(",
"[",
"State",
"(",
"\"input_text.test_text\"",
",",
"VALID_TEXT2",
")",
",",
"# Should not raise",
"State",
"(",
"\"input_text.non_existing\"",
",",
"VALID_TEXT2",
")",
",",
"]",
",",
")",
"# Test that the state was changed",
"assert",
"hass",
".",
"states",
".",
"get",
"(",
"\"input_text.test_text\"",
")",
".",
"state",
"==",
"VALID_TEXT2",
"# Test setting state to invalid state (length too long)",
"await",
"hass",
".",
"helpers",
".",
"state",
".",
"async_reproduce_state",
"(",
"[",
"State",
"(",
"\"input_text.test_text\"",
",",
"INVALID_TEXT1",
")",
"]",
")",
"# The entity state should be unchanged",
"assert",
"hass",
".",
"states",
".",
"get",
"(",
"\"input_text.test_text\"",
")",
".",
"state",
"==",
"VALID_TEXT2",
"# Test setting state to invalid state (length too short)",
"await",
"hass",
".",
"helpers",
".",
"state",
".",
"async_reproduce_state",
"(",
"[",
"State",
"(",
"\"input_text.test_text\"",
",",
"INVALID_TEXT2",
")",
"]",
")",
"# The entity state should be unchanged",
"assert",
"hass",
".",
"states",
".",
"get",
"(",
"\"input_text.test_text\"",
")",
".",
"state",
"==",
"VALID_TEXT2"
] | [
10,
0
] | [
62,
71
] | python | en | ['en', 'en', 'en'] | True |
setup_platform | (hass, config, add_entities, discovery_info=None) | Set up an EnOcean sensor device. | Set up an EnOcean sensor device. | def setup_platform(hass, config, add_entities, discovery_info=None):
"""Set up an EnOcean sensor device."""
dev_id = config.get(CONF_ID)
dev_name = config.get(CONF_NAME)
sensor_type = config.get(CONF_DEVICE_CLASS)
if sensor_type == SENSOR_TYPE_TEMPERATURE:
temp_min = config.get(CONF_MIN_TEMP)
temp_max = config.get(CONF_MAX_TEMP)
range_from = config.get(CONF_RANGE_FROM)
range_to = config.get(CONF_RANGE_TO)
add_entities(
[
EnOceanTemperatureSensor(
dev_id, dev_name, temp_min, temp_max, range_from, range_to
)
]
)
elif sensor_type == SENSOR_TYPE_HUMIDITY:
add_entities([EnOceanHumiditySensor(dev_id, dev_name)])
elif sensor_type == SENSOR_TYPE_POWER:
add_entities([EnOceanPowerSensor(dev_id, dev_name)])
elif sensor_type == SENSOR_TYPE_WINDOWHANDLE:
add_entities([EnOceanWindowHandle(dev_id, dev_name)]) | [
"def",
"setup_platform",
"(",
"hass",
",",
"config",
",",
"add_entities",
",",
"discovery_info",
"=",
"None",
")",
":",
"dev_id",
"=",
"config",
".",
"get",
"(",
"CONF_ID",
")",
"dev_name",
"=",
"config",
".",
"get",
"(",
"CONF_NAME",
")",
"sensor_type",
"=",
"config",
".",
"get",
"(",
"CONF_DEVICE_CLASS",
")",
"if",
"sensor_type",
"==",
"SENSOR_TYPE_TEMPERATURE",
":",
"temp_min",
"=",
"config",
".",
"get",
"(",
"CONF_MIN_TEMP",
")",
"temp_max",
"=",
"config",
".",
"get",
"(",
"CONF_MAX_TEMP",
")",
"range_from",
"=",
"config",
".",
"get",
"(",
"CONF_RANGE_FROM",
")",
"range_to",
"=",
"config",
".",
"get",
"(",
"CONF_RANGE_TO",
")",
"add_entities",
"(",
"[",
"EnOceanTemperatureSensor",
"(",
"dev_id",
",",
"dev_name",
",",
"temp_min",
",",
"temp_max",
",",
"range_from",
",",
"range_to",
")",
"]",
")",
"elif",
"sensor_type",
"==",
"SENSOR_TYPE_HUMIDITY",
":",
"add_entities",
"(",
"[",
"EnOceanHumiditySensor",
"(",
"dev_id",
",",
"dev_name",
")",
"]",
")",
"elif",
"sensor_type",
"==",
"SENSOR_TYPE_POWER",
":",
"add_entities",
"(",
"[",
"EnOceanPowerSensor",
"(",
"dev_id",
",",
"dev_name",
")",
"]",
")",
"elif",
"sensor_type",
"==",
"SENSOR_TYPE_WINDOWHANDLE",
":",
"add_entities",
"(",
"[",
"EnOceanWindowHandle",
"(",
"dev_id",
",",
"dev_name",
")",
"]",
")"
] | [
74,
0
] | [
100,
61
] | python | en | ['en', 'su', 'en'] | True |
EnOceanSensor.__init__ | (self, dev_id, dev_name, sensor_type) | Initialize the EnOcean sensor device. | Initialize the EnOcean sensor device. | def __init__(self, dev_id, dev_name, sensor_type):
"""Initialize the EnOcean sensor device."""
super().__init__(dev_id, dev_name)
self._sensor_type = sensor_type
self._device_class = SENSOR_TYPES[self._sensor_type]["class"]
self._dev_name = f"{SENSOR_TYPES[self._sensor_type]['name']} {dev_name}"
self._unit_of_measurement = SENSOR_TYPES[self._sensor_type]["unit"]
self._icon = SENSOR_TYPES[self._sensor_type]["icon"]
self._state = None | [
"def",
"__init__",
"(",
"self",
",",
"dev_id",
",",
"dev_name",
",",
"sensor_type",
")",
":",
"super",
"(",
")",
".",
"__init__",
"(",
"dev_id",
",",
"dev_name",
")",
"self",
".",
"_sensor_type",
"=",
"sensor_type",
"self",
".",
"_device_class",
"=",
"SENSOR_TYPES",
"[",
"self",
".",
"_sensor_type",
"]",
"[",
"\"class\"",
"]",
"self",
".",
"_dev_name",
"=",
"f\"{SENSOR_TYPES[self._sensor_type]['name']} {dev_name}\"",
"self",
".",
"_unit_of_measurement",
"=",
"SENSOR_TYPES",
"[",
"self",
".",
"_sensor_type",
"]",
"[",
"\"unit\"",
"]",
"self",
".",
"_icon",
"=",
"SENSOR_TYPES",
"[",
"self",
".",
"_sensor_type",
"]",
"[",
"\"icon\"",
"]",
"self",
".",
"_state",
"=",
"None"
] | [
106,
4
] | [
114,
26
] | python | en | ['en', 'fr', 'en'] | True |
EnOceanSensor.name | (self) | Return the name of the device. | Return the name of the device. | def name(self):
"""Return the name of the device."""
return self._dev_name | [
"def",
"name",
"(",
"self",
")",
":",
"return",
"self",
".",
"_dev_name"
] | [
117,
4
] | [
119,
29
] | python | en | ['en', 'en', 'en'] | True |
EnOceanSensor.icon | (self) | Icon to use in the frontend. | Icon to use in the frontend. | def icon(self):
"""Icon to use in the frontend."""
return self._icon | [
"def",
"icon",
"(",
"self",
")",
":",
"return",
"self",
".",
"_icon"
] | [
122,
4
] | [
124,
25
] | python | en | ['en', 'en', 'en'] | True |
EnOceanSensor.device_class | (self) | Return the device class of the sensor. | Return the device class of the sensor. | def device_class(self):
"""Return the device class of the sensor."""
return self._device_class | [
"def",
"device_class",
"(",
"self",
")",
":",
"return",
"self",
".",
"_device_class"
] | [
127,
4
] | [
129,
33
] | python | en | ['en', 'en', 'en'] | True |
EnOceanSensor.state | (self) | Return the state of the device. | Return the state of the device. | def state(self):
"""Return the state of the device."""
return self._state | [
"def",
"state",
"(",
"self",
")",
":",
"return",
"self",
".",
"_state"
] | [
132,
4
] | [
134,
26
] | python | en | ['en', 'en', 'en'] | True |
EnOceanSensor.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"
] | [
137,
4
] | [
139,
40
] | python | en | ['en', 'la', 'en'] | True |
EnOceanSensor.async_added_to_hass | (self) | Call when entity about to be added to hass. | Call when entity about to be added to hass. | async def async_added_to_hass(self):
"""Call when entity about to be added to hass."""
# If not None, we got an initial value.
await super().async_added_to_hass()
if self._state is not None:
return
state = await self.async_get_last_state()
if state is not None:
self._state = state.state | [
"async",
"def",
"async_added_to_hass",
"(",
"self",
")",
":",
"# If not None, we got an initial value.",
"await",
"super",
"(",
")",
".",
"async_added_to_hass",
"(",
")",
"if",
"self",
".",
"_state",
"is",
"not",
"None",
":",
"return",
"state",
"=",
"await",
"self",
".",
"async_get_last_state",
"(",
")",
"if",
"state",
"is",
"not",
"None",
":",
"self",
".",
"_state",
"=",
"state",
".",
"state"
] | [
141,
4
] | [
150,
37
] | python | en | ['en', 'en', 'en'] | True |
EnOceanSensor.value_changed | (self, packet) | Update the internal state of the sensor. | Update the internal state of the sensor. | def value_changed(self, packet):
"""Update the internal state of the sensor.""" | [
"def",
"value_changed",
"(",
"self",
",",
"packet",
")",
":"
] | [
152,
4
] | [
153,
54
] | python | en | ['en', 'en', 'en'] | True |
EnOceanPowerSensor.__init__ | (self, dev_id, dev_name) | Initialize the EnOcean power sensor device. | Initialize the EnOcean power sensor device. | def __init__(self, dev_id, dev_name):
"""Initialize the EnOcean power sensor device."""
super().__init__(dev_id, dev_name, SENSOR_TYPE_POWER) | [
"def",
"__init__",
"(",
"self",
",",
"dev_id",
",",
"dev_name",
")",
":",
"super",
"(",
")",
".",
"__init__",
"(",
"dev_id",
",",
"dev_name",
",",
"SENSOR_TYPE_POWER",
")"
] | [
163,
4
] | [
165,
61
] | python | en | ['en', 'fr', 'en'] | True |
EnOceanPowerSensor.value_changed | (self, packet) | Update the internal state of the sensor. | Update the internal state of the sensor. | def value_changed(self, packet):
"""Update the internal state of the sensor."""
if packet.rorg != 0xA5:
return
packet.parse_eep(0x12, 0x01)
if packet.parsed["DT"]["raw_value"] == 1:
# this packet reports the current value
raw_val = packet.parsed["MR"]["raw_value"]
divisor = packet.parsed["DIV"]["raw_value"]
self._state = raw_val / (10 ** divisor)
self.schedule_update_ha_state() | [
"def",
"value_changed",
"(",
"self",
",",
"packet",
")",
":",
"if",
"packet",
".",
"rorg",
"!=",
"0xA5",
":",
"return",
"packet",
".",
"parse_eep",
"(",
"0x12",
",",
"0x01",
")",
"if",
"packet",
".",
"parsed",
"[",
"\"DT\"",
"]",
"[",
"\"raw_value\"",
"]",
"==",
"1",
":",
"# this packet reports the current value",
"raw_val",
"=",
"packet",
".",
"parsed",
"[",
"\"MR\"",
"]",
"[",
"\"raw_value\"",
"]",
"divisor",
"=",
"packet",
".",
"parsed",
"[",
"\"DIV\"",
"]",
"[",
"\"raw_value\"",
"]",
"self",
".",
"_state",
"=",
"raw_val",
"/",
"(",
"10",
"**",
"divisor",
")",
"self",
".",
"schedule_update_ha_state",
"(",
")"
] | [
167,
4
] | [
177,
43
] | python | en | ['en', 'en', 'en'] | True |
EnOceanTemperatureSensor.__init__ | (self, dev_id, dev_name, scale_min, scale_max, range_from, range_to) | Initialize the EnOcean temperature sensor device. | Initialize the EnOcean temperature sensor device. | def __init__(self, dev_id, dev_name, scale_min, scale_max, range_from, range_to):
"""Initialize the EnOcean temperature sensor device."""
super().__init__(dev_id, dev_name, SENSOR_TYPE_TEMPERATURE)
self._scale_min = scale_min
self._scale_max = scale_max
self.range_from = range_from
self.range_to = range_to | [
"def",
"__init__",
"(",
"self",
",",
"dev_id",
",",
"dev_name",
",",
"scale_min",
",",
"scale_max",
",",
"range_from",
",",
"range_to",
")",
":",
"super",
"(",
")",
".",
"__init__",
"(",
"dev_id",
",",
"dev_name",
",",
"SENSOR_TYPE_TEMPERATURE",
")",
"self",
".",
"_scale_min",
"=",
"scale_min",
"self",
".",
"_scale_max",
"=",
"scale_max",
"self",
".",
"range_from",
"=",
"range_from",
"self",
".",
"range_to",
"=",
"range_to"
] | [
198,
4
] | [
204,
32
] | python | en | ['en', 'ro', 'en'] | True |
EnOceanTemperatureSensor.value_changed | (self, packet) | Update the internal state of the sensor. | Update the internal state of the sensor. | def value_changed(self, packet):
"""Update the internal state of the sensor."""
if packet.data[0] != 0xA5:
return
temp_scale = self._scale_max - self._scale_min
temp_range = self.range_to - self.range_from
raw_val = packet.data[3]
temperature = temp_scale / temp_range * (raw_val - self.range_from)
temperature += self._scale_min
self._state = round(temperature, 1)
self.schedule_update_ha_state() | [
"def",
"value_changed",
"(",
"self",
",",
"packet",
")",
":",
"if",
"packet",
".",
"data",
"[",
"0",
"]",
"!=",
"0xA5",
":",
"return",
"temp_scale",
"=",
"self",
".",
"_scale_max",
"-",
"self",
".",
"_scale_min",
"temp_range",
"=",
"self",
".",
"range_to",
"-",
"self",
".",
"range_from",
"raw_val",
"=",
"packet",
".",
"data",
"[",
"3",
"]",
"temperature",
"=",
"temp_scale",
"/",
"temp_range",
"*",
"(",
"raw_val",
"-",
"self",
".",
"range_from",
")",
"temperature",
"+=",
"self",
".",
"_scale_min",
"self",
".",
"_state",
"=",
"round",
"(",
"temperature",
",",
"1",
")",
"self",
".",
"schedule_update_ha_state",
"(",
")"
] | [
206,
4
] | [
216,
39
] | python | en | ['en', 'en', 'en'] | True |
EnOceanHumiditySensor.__init__ | (self, dev_id, dev_name) | Initialize the EnOcean humidity sensor device. | Initialize the EnOcean humidity sensor device. | def __init__(self, dev_id, dev_name):
"""Initialize the EnOcean humidity sensor device."""
super().__init__(dev_id, dev_name, SENSOR_TYPE_HUMIDITY) | [
"def",
"__init__",
"(",
"self",
",",
"dev_id",
",",
"dev_name",
")",
":",
"super",
"(",
")",
".",
"__init__",
"(",
"dev_id",
",",
"dev_name",
",",
"SENSOR_TYPE_HUMIDITY",
")"
] | [
228,
4
] | [
230,
64
] | python | en | ['en', 'en', 'en'] | True |
EnOceanHumiditySensor.value_changed | (self, packet) | Update the internal state of the sensor. | Update the internal state of the sensor. | def value_changed(self, packet):
"""Update the internal state of the sensor."""
if packet.rorg != 0xA5:
return
humidity = packet.data[2] * 100 / 250
self._state = round(humidity, 1)
self.schedule_update_ha_state() | [
"def",
"value_changed",
"(",
"self",
",",
"packet",
")",
":",
"if",
"packet",
".",
"rorg",
"!=",
"0xA5",
":",
"return",
"humidity",
"=",
"packet",
".",
"data",
"[",
"2",
"]",
"*",
"100",
"/",
"250",
"self",
".",
"_state",
"=",
"round",
"(",
"humidity",
",",
"1",
")",
"self",
".",
"schedule_update_ha_state",
"(",
")"
] | [
232,
4
] | [
238,
39
] | python | en | ['en', 'en', 'en'] | True |
EnOceanWindowHandle.__init__ | (self, dev_id, dev_name) | Initialize the EnOcean window handle sensor device. | Initialize the EnOcean window handle sensor device. | def __init__(self, dev_id, dev_name):
"""Initialize the EnOcean window handle sensor device."""
super().__init__(dev_id, dev_name, SENSOR_TYPE_WINDOWHANDLE) | [
"def",
"__init__",
"(",
"self",
",",
"dev_id",
",",
"dev_name",
")",
":",
"super",
"(",
")",
".",
"__init__",
"(",
"dev_id",
",",
"dev_name",
",",
"SENSOR_TYPE_WINDOWHANDLE",
")"
] | [
248,
4
] | [
250,
68
] | python | en | ['en', 'fy', 'en'] | True |
EnOceanWindowHandle.value_changed | (self, packet) | Update the internal state of the sensor. | Update the internal state of the sensor. | def value_changed(self, packet):
"""Update the internal state of the sensor."""
action = (packet.data[1] & 0x70) >> 4
if action == 0x07:
self._state = STATE_CLOSED
if action in (0x04, 0x06):
self._state = STATE_OPEN
if action == 0x05:
self._state = "tilt"
self.schedule_update_ha_state() | [
"def",
"value_changed",
"(",
"self",
",",
"packet",
")",
":",
"action",
"=",
"(",
"packet",
".",
"data",
"[",
"1",
"]",
"&",
"0x70",
")",
">>",
"4",
"if",
"action",
"==",
"0x07",
":",
"self",
".",
"_state",
"=",
"STATE_CLOSED",
"if",
"action",
"in",
"(",
"0x04",
",",
"0x06",
")",
":",
"self",
".",
"_state",
"=",
"STATE_OPEN",
"if",
"action",
"==",
"0x05",
":",
"self",
".",
"_state",
"=",
"\"tilt\"",
"self",
".",
"schedule_update_ha_state",
"(",
")"
] | [
252,
4
] | [
264,
39
] | python | en | ['en', 'en', 'en'] | True |
setup | (hass, config) | Set up the Nuimo component. | Set up the Nuimo component. | def setup(hass, config):
"""Set up the Nuimo component."""
conf = config[DOMAIN]
mac = conf.get(CONF_MAC)
name = conf.get(CONF_NAME)
NuimoThread(hass, mac, name).start()
return True | [
"def",
"setup",
"(",
"hass",
",",
"config",
")",
":",
"conf",
"=",
"config",
"[",
"DOMAIN",
"]",
"mac",
"=",
"conf",
".",
"get",
"(",
"CONF_MAC",
")",
"name",
"=",
"conf",
".",
"get",
"(",
"CONF_NAME",
")",
"NuimoThread",
"(",
"hass",
",",
"mac",
",",
"name",
")",
".",
"start",
"(",
")",
"return",
"True"
] | [
45,
0
] | [
51,
15
] | python | en | ['en', 'en', 'en'] | True |
NuimoLogger.__init__ | (self, hass, name) | Initialize Logger object. | Initialize Logger object. | def __init__(self, hass, name):
"""Initialize Logger object."""
self._hass = hass
self._name = name | [
"def",
"__init__",
"(",
"self",
",",
"hass",
",",
"name",
")",
":",
"self",
".",
"_hass",
"=",
"hass",
"self",
".",
"_name",
"=",
"name"
] | [
57,
4
] | [
60,
25
] | python | da | ['da', 'en', 'nl'] | False |
NuimoLogger.received_gesture_event | (self, event) | Input Event received. | Input Event received. | def received_gesture_event(self, event):
"""Input Event received."""
_LOGGER.debug(
"Received event: name=%s, gesture_id=%s,value=%s",
event.name,
event.gesture,
event.value,
)
self._hass.bus.fire(
EVENT_NUIMO, {"type": event.name, "value": event.value, "name": self._name}
) | [
"def",
"received_gesture_event",
"(",
"self",
",",
"event",
")",
":",
"_LOGGER",
".",
"debug",
"(",
"\"Received event: name=%s, gesture_id=%s,value=%s\"",
",",
"event",
".",
"name",
",",
"event",
".",
"gesture",
",",
"event",
".",
"value",
",",
")",
"self",
".",
"_hass",
".",
"bus",
".",
"fire",
"(",
"EVENT_NUIMO",
",",
"{",
"\"type\"",
":",
"event",
".",
"name",
",",
"\"value\"",
":",
"event",
".",
"value",
",",
"\"name\"",
":",
"self",
".",
"_name",
"}",
")"
] | [
62,
4
] | [
72,
9
] | python | en | ['en', 'en', 'en'] | True |
NuimoThread.__init__ | (self, hass, mac, name) | Initialize thread object. | Initialize thread object. | def __init__(self, hass, mac, name):
"""Initialize thread object."""
super().__init__()
self._hass = hass
self._mac = mac
self._name = name
self._hass_is_running = True
self._nuimo = None
hass.bus.listen_once(EVENT_HOMEASSISTANT_STOP, self.stop) | [
"def",
"__init__",
"(",
"self",
",",
"hass",
",",
"mac",
",",
"name",
")",
":",
"super",
"(",
")",
".",
"__init__",
"(",
")",
"self",
".",
"_hass",
"=",
"hass",
"self",
".",
"_mac",
"=",
"mac",
"self",
".",
"_name",
"=",
"name",
"self",
".",
"_hass_is_running",
"=",
"True",
"self",
".",
"_nuimo",
"=",
"None",
"hass",
".",
"bus",
".",
"listen_once",
"(",
"EVENT_HOMEASSISTANT_STOP",
",",
"self",
".",
"stop",
")"
] | [
78,
4
] | [
86,
65
] | python | en | ['en', 'en', 'en'] | True |
NuimoThread.run | (self) | Set up the connection or be idle. | Set up the connection or be idle. | def run(self):
"""Set up the connection or be idle."""
while self._hass_is_running:
if not self._nuimo or not self._nuimo.is_connected():
self._attach()
self._connect()
else:
time.sleep(1)
if self._nuimo:
self._nuimo.disconnect()
self._nuimo = None | [
"def",
"run",
"(",
"self",
")",
":",
"while",
"self",
".",
"_hass_is_running",
":",
"if",
"not",
"self",
".",
"_nuimo",
"or",
"not",
"self",
".",
"_nuimo",
".",
"is_connected",
"(",
")",
":",
"self",
".",
"_attach",
"(",
")",
"self",
".",
"_connect",
"(",
")",
"else",
":",
"time",
".",
"sleep",
"(",
"1",
")",
"if",
"self",
".",
"_nuimo",
":",
"self",
".",
"_nuimo",
".",
"disconnect",
"(",
")",
"self",
".",
"_nuimo",
"=",
"None"
] | [
88,
4
] | [
99,
30
] | python | en | ['en', 'en', 'en'] | True |
NuimoThread.stop | (self, event) | Terminate Thread by unsetting flag. | Terminate Thread by unsetting flag. | def stop(self, event):
"""Terminate Thread by unsetting flag."""
_LOGGER.debug("Stopping thread for Nuimo %s", self._mac)
self._hass_is_running = False | [
"def",
"stop",
"(",
"self",
",",
"event",
")",
":",
"_LOGGER",
".",
"debug",
"(",
"\"Stopping thread for Nuimo %s\"",
",",
"self",
".",
"_mac",
")",
"self",
".",
"_hass_is_running",
"=",
"False"
] | [
101,
4
] | [
104,
37
] | python | en | ['en', 'en', 'en'] | True |
NuimoThread._attach | (self) | Create a Nuimo object from MAC address or discovery. | Create a Nuimo object from MAC address or discovery. | def _attach(self):
"""Create a Nuimo object from MAC address or discovery."""
if self._nuimo:
self._nuimo.disconnect()
self._nuimo = None
if self._mac:
self._nuimo = NuimoController(self._mac)
else:
nuimo_manager = NuimoDiscoveryManager(
bluetooth_adapter=DEFAULT_ADAPTER, delegate=DiscoveryLogger()
)
nuimo_manager.start_discovery()
# Were any Nuimos found?
if not nuimo_manager.nuimos:
_LOGGER.debug("No Nuimo devices detected")
return
# Take the first Nuimo found.
self._nuimo = nuimo_manager.nuimos[0]
self._mac = self._nuimo.addr | [
"def",
"_attach",
"(",
"self",
")",
":",
"if",
"self",
".",
"_nuimo",
":",
"self",
".",
"_nuimo",
".",
"disconnect",
"(",
")",
"self",
".",
"_nuimo",
"=",
"None",
"if",
"self",
".",
"_mac",
":",
"self",
".",
"_nuimo",
"=",
"NuimoController",
"(",
"self",
".",
"_mac",
")",
"else",
":",
"nuimo_manager",
"=",
"NuimoDiscoveryManager",
"(",
"bluetooth_adapter",
"=",
"DEFAULT_ADAPTER",
",",
"delegate",
"=",
"DiscoveryLogger",
"(",
")",
")",
"nuimo_manager",
".",
"start_discovery",
"(",
")",
"# Were any Nuimos found?",
"if",
"not",
"nuimo_manager",
".",
"nuimos",
":",
"_LOGGER",
".",
"debug",
"(",
"\"No Nuimo devices detected\"",
")",
"return",
"# Take the first Nuimo found.",
"self",
".",
"_nuimo",
"=",
"nuimo_manager",
".",
"nuimos",
"[",
"0",
"]",
"self",
".",
"_mac",
"=",
"self",
".",
"_nuimo",
".",
"addr"
] | [
106,
4
] | [
126,
40
] | python | en | ['en', 'en', 'en'] | True |
NuimoThread._connect | (self) | Build up connection and set event delegator and service. | Build up connection and set event delegator and service. | def _connect(self):
"""Build up connection and set event delegator and service."""
if not self._nuimo:
return
try:
self._nuimo.connect()
_LOGGER.debug("Connected to %s", self._mac)
except RuntimeError as error:
_LOGGER.error("Could not connect to %s: %s", self._mac, error)
time.sleep(1)
return
nuimo_event_delegate = NuimoLogger(self._hass, self._name)
self._nuimo.set_delegate(nuimo_event_delegate)
def handle_write_matrix(call):
"""Handle led matrix service."""
matrix = call.data.get("matrix", None)
name = call.data.get(CONF_NAME, DEFAULT_NAME)
interval = call.data.get("interval", DEFAULT_INTERVAL)
if self._name == name and matrix:
self._nuimo.write_matrix(matrix, interval)
self._hass.services.register(
DOMAIN, SERVICE_NUIMO, handle_write_matrix, schema=SERVICE_NUIMO_SCHEMA
)
self._nuimo.write_matrix(HOMEASSIST_LOGO, 2.0) | [
"def",
"_connect",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_nuimo",
":",
"return",
"try",
":",
"self",
".",
"_nuimo",
".",
"connect",
"(",
")",
"_LOGGER",
".",
"debug",
"(",
"\"Connected to %s\"",
",",
"self",
".",
"_mac",
")",
"except",
"RuntimeError",
"as",
"error",
":",
"_LOGGER",
".",
"error",
"(",
"\"Could not connect to %s: %s\"",
",",
"self",
".",
"_mac",
",",
"error",
")",
"time",
".",
"sleep",
"(",
"1",
")",
"return",
"nuimo_event_delegate",
"=",
"NuimoLogger",
"(",
"self",
".",
"_hass",
",",
"self",
".",
"_name",
")",
"self",
".",
"_nuimo",
".",
"set_delegate",
"(",
"nuimo_event_delegate",
")",
"def",
"handle_write_matrix",
"(",
"call",
")",
":",
"\"\"\"Handle led matrix service.\"\"\"",
"matrix",
"=",
"call",
".",
"data",
".",
"get",
"(",
"\"matrix\"",
",",
"None",
")",
"name",
"=",
"call",
".",
"data",
".",
"get",
"(",
"CONF_NAME",
",",
"DEFAULT_NAME",
")",
"interval",
"=",
"call",
".",
"data",
".",
"get",
"(",
"\"interval\"",
",",
"DEFAULT_INTERVAL",
")",
"if",
"self",
".",
"_name",
"==",
"name",
"and",
"matrix",
":",
"self",
".",
"_nuimo",
".",
"write_matrix",
"(",
"matrix",
",",
"interval",
")",
"self",
".",
"_hass",
".",
"services",
".",
"register",
"(",
"DOMAIN",
",",
"SERVICE_NUIMO",
",",
"handle_write_matrix",
",",
"schema",
"=",
"SERVICE_NUIMO_SCHEMA",
")",
"self",
".",
"_nuimo",
".",
"write_matrix",
"(",
"HOMEASSIST_LOGO",
",",
"2.0",
")"
] | [
128,
4
] | [
156,
54
] | python | en | ['en', 'en', 'en'] | True |
DiscoveryLogger.discovery_started | (self) | Discovery started. | Discovery started. | def discovery_started(self):
"""Discovery started."""
_LOGGER.info("Started discovery") | [
"def",
"discovery_started",
"(",
"self",
")",
":",
"_LOGGER",
".",
"info",
"(",
"\"Started discovery\"",
")"
] | [
177,
4
] | [
179,
41
] | python | en | ['en', 'en', 'en'] | False |
DiscoveryLogger.discovery_finished | (self) | Discovery finished. | Discovery finished. | def discovery_finished(self):
"""Discovery finished."""
_LOGGER.info("Finished discovery") | [
"def",
"discovery_finished",
"(",
"self",
")",
":",
"_LOGGER",
".",
"info",
"(",
"\"Finished discovery\"",
")"
] | [
182,
4
] | [
184,
42
] | python | en | ['en', 'en', 'en'] | False |
DiscoveryLogger.controller_added | (self, nuimo) | Return that a controller was found. | Return that a controller was found. | def controller_added(self, nuimo):
"""Return that a controller was found."""
_LOGGER.info("Added Nuimo: %s", nuimo) | [
"def",
"controller_added",
"(",
"self",
",",
"nuimo",
")",
":",
"_LOGGER",
".",
"info",
"(",
"\"Added Nuimo: %s\"",
",",
"nuimo",
")"
] | [
187,
4
] | [
189,
46
] | python | en | ['en', 'en', 'en'] | True |
async_setup_entry | (hass, entry, async_add_entities) | Set up the Pi-hole switch. | Set up the Pi-hole switch. | async def async_setup_entry(hass, entry, async_add_entities):
"""Set up the Pi-hole switch."""
name = entry.data[CONF_NAME]
hole_data = hass.data[PIHOLE_DOMAIN][entry.entry_id]
switches = [
PiHoleSwitch(
hole_data[DATA_KEY_API],
hole_data[DATA_KEY_COORDINATOR],
name,
entry.entry_id,
)
]
async_add_entities(switches, True)
# register service
platform = entity_platform.current_platform.get()
platform.async_register_entity_service(
SERVICE_DISABLE,
{
vol.Required(SERVICE_DISABLE_ATTR_DURATION): vol.All(
cv.time_period_str, cv.positive_timedelta
),
},
"async_disable",
) | [
"async",
"def",
"async_setup_entry",
"(",
"hass",
",",
"entry",
",",
"async_add_entities",
")",
":",
"name",
"=",
"entry",
".",
"data",
"[",
"CONF_NAME",
"]",
"hole_data",
"=",
"hass",
".",
"data",
"[",
"PIHOLE_DOMAIN",
"]",
"[",
"entry",
".",
"entry_id",
"]",
"switches",
"=",
"[",
"PiHoleSwitch",
"(",
"hole_data",
"[",
"DATA_KEY_API",
"]",
",",
"hole_data",
"[",
"DATA_KEY_COORDINATOR",
"]",
",",
"name",
",",
"entry",
".",
"entry_id",
",",
")",
"]",
"async_add_entities",
"(",
"switches",
",",
"True",
")",
"# register service",
"platform",
"=",
"entity_platform",
".",
"current_platform",
".",
"get",
"(",
")",
"platform",
".",
"async_register_entity_service",
"(",
"SERVICE_DISABLE",
",",
"{",
"vol",
".",
"Required",
"(",
"SERVICE_DISABLE_ATTR_DURATION",
")",
":",
"vol",
".",
"All",
"(",
"cv",
".",
"time_period_str",
",",
"cv",
".",
"positive_timedelta",
")",
",",
"}",
",",
"\"async_disable\"",
",",
")"
] | [
22,
0
] | [
46,
5
] | python | en | ['en', 'zu', 'en'] | True |
PiHoleSwitch.name | (self) | Return the name of the switch. | Return the name of the switch. | def name(self):
"""Return the name of the switch."""
return self._name | [
"def",
"name",
"(",
"self",
")",
":",
"return",
"self",
".",
"_name"
] | [
53,
4
] | [
55,
25
] | python | en | ['en', 'en', 'en'] | True |
PiHoleSwitch.unique_id | (self) | Return the unique id of the switch. | Return the unique id of the switch. | def unique_id(self):
"""Return the unique id of the switch."""
return f"{self._server_unique_id}/Switch" | [
"def",
"unique_id",
"(",
"self",
")",
":",
"return",
"f\"{self._server_unique_id}/Switch\""
] | [
58,
4
] | [
60,
49
] | python | en | ['en', 'en', 'en'] | True |
PiHoleSwitch.icon | (self) | Icon to use in the frontend, if any. | Icon to use in the frontend, if any. | def icon(self):
"""Icon to use in the frontend, if any."""
return "mdi:pi-hole" | [
"def",
"icon",
"(",
"self",
")",
":",
"return",
"\"mdi:pi-hole\""
] | [
63,
4
] | [
65,
28
] | python | en | ['en', 'en', 'en'] | True |
PiHoleSwitch.is_on | (self) | Return if the service is on. | Return if the service is on. | def is_on(self):
"""Return if the service is on."""
return self.api.data.get("status") == "enabled" | [
"def",
"is_on",
"(",
"self",
")",
":",
"return",
"self",
".",
"api",
".",
"data",
".",
"get",
"(",
"\"status\"",
")",
"==",
"\"enabled\""
] | [
68,
4
] | [
70,
55
] | python | en | ['en', 'en', 'en'] | True |
PiHoleSwitch.async_turn_on | (self, **kwargs) | Turn on the service. | Turn on the service. | async def async_turn_on(self, **kwargs):
"""Turn on the service."""
try:
await self.api.enable()
await self.async_update()
except HoleError as err:
_LOGGER.error("Unable to enable Pi-hole: %s", err) | [
"async",
"def",
"async_turn_on",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"await",
"self",
".",
"api",
".",
"enable",
"(",
")",
"await",
"self",
".",
"async_update",
"(",
")",
"except",
"HoleError",
"as",
"err",
":",
"_LOGGER",
".",
"error",
"(",
"\"Unable to enable Pi-hole: %s\"",
",",
"err",
")"
] | [
72,
4
] | [
78,
62
] | python | en | ['en', 'en', 'en'] | True |
PiHoleSwitch.async_turn_off | (self, **kwargs) | Turn off the service. | Turn off the service. | async def async_turn_off(self, **kwargs):
"""Turn off the service."""
await self.async_disable() | [
"async",
"def",
"async_turn_off",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"await",
"self",
".",
"async_disable",
"(",
")"
] | [
80,
4
] | [
82,
34
] | python | en | ['en', 'en', 'en'] | True |
PiHoleSwitch.async_disable | (self, duration=None) | Disable the service for a given duration. | Disable the service for a given duration. | async def async_disable(self, duration=None):
"""Disable the service for a given duration."""
duration_seconds = True # Disable infinitely by default
if duration is not None:
duration_seconds = duration.total_seconds()
_LOGGER.debug(
"Disabling Pi-hole '%s' (%s) for %d seconds",
self.name,
self.api.host,
duration_seconds,
)
try:
await self.api.disable(duration_seconds)
await self.async_update()
except HoleError as err:
_LOGGER.error("Unable to disable Pi-hole: %s", err) | [
"async",
"def",
"async_disable",
"(",
"self",
",",
"duration",
"=",
"None",
")",
":",
"duration_seconds",
"=",
"True",
"# Disable infinitely by default",
"if",
"duration",
"is",
"not",
"None",
":",
"duration_seconds",
"=",
"duration",
".",
"total_seconds",
"(",
")",
"_LOGGER",
".",
"debug",
"(",
"\"Disabling Pi-hole '%s' (%s) for %d seconds\"",
",",
"self",
".",
"name",
",",
"self",
".",
"api",
".",
"host",
",",
"duration_seconds",
",",
")",
"try",
":",
"await",
"self",
".",
"api",
".",
"disable",
"(",
"duration_seconds",
")",
"await",
"self",
".",
"async_update",
"(",
")",
"except",
"HoleError",
"as",
"err",
":",
"_LOGGER",
".",
"error",
"(",
"\"Unable to disable Pi-hole: %s\"",
",",
"err",
")"
] | [
84,
4
] | [
99,
63
] | python | en | ['en', 'en', 'en'] | True |
TemplateError.__init__ | (self, exception: Exception) | Init the error. | Init the error. | def __init__(self, exception: Exception) -> None:
"""Init the error."""
super().__init__(f"{exception.__class__.__name__}: {exception}") | [
"def",
"__init__",
"(",
"self",
",",
"exception",
":",
"Exception",
")",
"->",
"None",
":",
"super",
"(",
")",
".",
"__init__",
"(",
"f\"{exception.__class__.__name__}: {exception}\"",
")"
] | [
22,
4
] | [
24,
72
] | python | en | ['en', 'la', 'en'] | True |
Subsets and Splits