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
list | start_point
list | end_point
list | language
stringclasses 1
value | docstring_language
stringlengths 2
7
| docstring_language_predictions
stringlengths 18
23
| is_langid_reliable
stringclasses 2
values |
---|---|---|---|---|---|---|---|---|---|---|---|
BatchTuner.import_data | (self, data) | Import additional data for tuning
Parameters
----------
data:
a list of dictionarys, each of which has at least two keys, 'parameter' and 'value'
| Import additional data for tuning | def import_data(self, data):
"""Import additional data for tuning
Parameters
----------
data:
a list of dictionarys, each of which has at least two keys, 'parameter' and 'value'
"""
if not self._values:
LOGGER.info("Search space has not been initialized, skip this data import")
return
self._values = self._values[(self._count+1):]
self._count = -1
_completed_num = 0
for trial_info in data:
LOGGER .info("Importing data, current processing \
progress %s / %s", _completed_num, len(data))
# simply validate data format
assert "parameter" in trial_info
_params = trial_info["parameter"]
assert "value" in trial_info
_value = trial_info['value']
if not _value:
LOGGER.info("Useless trial data, value is %s, skip this trial data.", _value)
continue
_completed_num += 1
if _params in self._values:
self._values.remove(_params)
LOGGER .info("Successfully import data to batch tuner, \
total data: %d, imported data: %d.", len(data), _completed_num) | [
"def",
"import_data",
"(",
"self",
",",
"data",
")",
":",
"if",
"not",
"self",
".",
"_values",
":",
"LOGGER",
".",
"info",
"(",
"\"Search space has not been initialized, skip this data import\"",
")",
"return",
"self",
".",
"_values",
"=",
"self",
".",
"_values",
"[",
"(",
"self",
".",
"_count",
"+",
"1",
")",
":",
"]",
"self",
".",
"_count",
"=",
"-",
"1",
"_completed_num",
"=",
"0",
"for",
"trial_info",
"in",
"data",
":",
"LOGGER",
".",
"info",
"(",
"\"Importing data, current processing \\\n progress %s / %s\"",
",",
"_completed_num",
",",
"len",
"(",
"data",
")",
")",
"# simply validate data format",
"assert",
"\"parameter\"",
"in",
"trial_info",
"_params",
"=",
"trial_info",
"[",
"\"parameter\"",
"]",
"assert",
"\"value\"",
"in",
"trial_info",
"_value",
"=",
"trial_info",
"[",
"'value'",
"]",
"if",
"not",
"_value",
":",
"LOGGER",
".",
"info",
"(",
"\"Useless trial data, value is %s, skip this trial data.\"",
",",
"_value",
")",
"continue",
"_completed_num",
"+=",
"1",
"if",
"_params",
"in",
"self",
".",
"_values",
":",
"self",
".",
"_values",
".",
"remove",
"(",
"_params",
")",
"LOGGER",
".",
"info",
"(",
"\"Successfully import data to batch tuner, \\\n total data: %d, imported data: %d.\"",
",",
"len",
"(",
"data",
")",
",",
"_completed_num",
")"
] | [
99,
4
] | [
130,
87
] | python | en | ['en', 'en', 'en'] | True |
async_setup_platform | (hass, config, async_add_entities, discovery_info=None) | Set up the Apple TV remote platform. | Set up the Apple TV remote platform. | async def async_setup_platform(hass, config, async_add_entities, discovery_info=None):
"""Set up the Apple TV remote platform."""
if not discovery_info:
return
name = discovery_info[CONF_NAME]
host = discovery_info[CONF_HOST]
atv = hass.data[DATA_APPLE_TV][host][ATTR_ATV]
power = hass.data[DATA_APPLE_TV][host][ATTR_POWER]
async_add_entities([AppleTVRemote(atv, power, name)]) | [
"async",
"def",
"async_setup_platform",
"(",
"hass",
",",
"config",
",",
"async_add_entities",
",",
"discovery_info",
"=",
"None",
")",
":",
"if",
"not",
"discovery_info",
":",
"return",
"name",
"=",
"discovery_info",
"[",
"CONF_NAME",
"]",
"host",
"=",
"discovery_info",
"[",
"CONF_HOST",
"]",
"atv",
"=",
"hass",
".",
"data",
"[",
"DATA_APPLE_TV",
"]",
"[",
"host",
"]",
"[",
"ATTR_ATV",
"]",
"power",
"=",
"hass",
".",
"data",
"[",
"DATA_APPLE_TV",
"]",
"[",
"host",
"]",
"[",
"ATTR_POWER",
"]",
"async_add_entities",
"(",
"[",
"AppleTVRemote",
"(",
"atv",
",",
"power",
",",
"name",
")",
"]",
")"
] | [
7,
0
] | [
16,
57
] | python | en | ['en', 'da', 'en'] | True |
AppleTVRemote.__init__ | (self, atv, power, name) | Initialize device. | Initialize device. | def __init__(self, atv, power, name):
"""Initialize device."""
self._atv = atv
self._name = name
self._power = power
self._power.listeners.append(self) | [
"def",
"__init__",
"(",
"self",
",",
"atv",
",",
"power",
",",
"name",
")",
":",
"self",
".",
"_atv",
"=",
"atv",
"self",
".",
"_name",
"=",
"name",
"self",
".",
"_power",
"=",
"power",
"self",
".",
"_power",
".",
"listeners",
".",
"append",
"(",
"self",
")"
] | [
22,
4
] | [
27,
42
] | python | en | ['fr', 'en', 'en'] | False |
AppleTVRemote.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._name | [
"def",
"name",
"(",
"self",
")",
":",
"return",
"self",
".",
"_name"
] | [
30,
4
] | [
32,
25
] | python | en | ['en', 'en', 'en'] | True |
AppleTVRemote.unique_id | (self) | Return a unique ID. | Return a unique ID. | def unique_id(self):
"""Return a unique ID."""
return self._atv.metadata.device_id | [
"def",
"unique_id",
"(",
"self",
")",
":",
"return",
"self",
".",
"_atv",
".",
"metadata",
".",
"device_id"
] | [
35,
4
] | [
37,
43
] | python | ca | ['fr', 'ca', 'en'] | False |
AppleTVRemote.is_on | (self) | Return true if device is on. | Return true if device is on. | def is_on(self):
"""Return true if device is on."""
return self._power.turned_on | [
"def",
"is_on",
"(",
"self",
")",
":",
"return",
"self",
".",
"_power",
".",
"turned_on"
] | [
40,
4
] | [
42,
36
] | python | en | ['en', 'fy', 'en'] | True |
AppleTVRemote.should_poll | (self) | No polling needed for Apple TV. | No polling needed for Apple TV. | def should_poll(self):
"""No polling needed for Apple TV."""
return False | [
"def",
"should_poll",
"(",
"self",
")",
":",
"return",
"False"
] | [
45,
4
] | [
47,
20
] | python | en | ['en', 'en', 'en'] | True |
AppleTVRemote.async_turn_on | (self, **kwargs) | Turn the device on.
This method is a coroutine.
| Turn the device on. | async def async_turn_on(self, **kwargs):
"""Turn the device on.
This method is a coroutine.
"""
self._power.set_power_on(True) | [
"async",
"def",
"async_turn_on",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"_power",
".",
"set_power_on",
"(",
"True",
")"
] | [
49,
4
] | [
54,
38
] | python | en | ['en', 'en', 'en'] | True |
AppleTVRemote.async_turn_off | (self, **kwargs) | Turn the device off.
This method is a coroutine.
| Turn the device off. | async def async_turn_off(self, **kwargs):
"""Turn the device off.
This method is a coroutine.
"""
self._power.set_power_on(False) | [
"async",
"def",
"async_turn_off",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"_power",
".",
"set_power_on",
"(",
"False",
")"
] | [
56,
4
] | [
61,
39
] | python | en | ['en', 'en', 'en'] | True |
AppleTVRemote.async_send_command | (self, command, **kwargs) | Send a command to one device. | Send a command to one device. | async def async_send_command(self, command, **kwargs):
"""Send a command to one device."""
for single_command in command:
if not hasattr(self._atv.remote_control, single_command):
continue
await getattr(self._atv.remote_control, single_command)() | [
"async",
"def",
"async_send_command",
"(",
"self",
",",
"command",
",",
"*",
"*",
"kwargs",
")",
":",
"for",
"single_command",
"in",
"command",
":",
"if",
"not",
"hasattr",
"(",
"self",
".",
"_atv",
".",
"remote_control",
",",
"single_command",
")",
":",
"continue",
"await",
"getattr",
"(",
"self",
".",
"_atv",
".",
"remote_control",
",",
"single_command",
")",
"(",
")"
] | [
63,
4
] | [
69,
69
] | python | en | ['en', 'en', 'en'] | True |
device_reg | (hass) | Return an empty, loaded, registry. | Return an empty, loaded, registry. | def device_reg(hass):
"""Return an empty, loaded, registry."""
return mock_device_registry(hass) | [
"def",
"device_reg",
"(",
"hass",
")",
":",
"return",
"mock_device_registry",
"(",
"hass",
")"
] | [
25,
0
] | [
27,
37
] | python | en | ['en', 'fy', 'en'] | True |
entity_reg | (hass) | Return an empty, loaded, registry. | Return an empty, loaded, registry. | def entity_reg(hass):
"""Return an empty, loaded, registry."""
return mock_registry(hass) | [
"def",
"entity_reg",
"(",
"hass",
")",
":",
"return",
"mock_registry",
"(",
"hass",
")"
] | [
31,
0
] | [
33,
30
] | python | en | ['en', 'fy', 'en'] | True |
calls | (hass) | Track calls to a mock service. | Track calls to a mock service. | def calls(hass):
"""Track calls to a mock service."""
return async_mock_service(hass, "test", "automation") | [
"def",
"calls",
"(",
"hass",
")",
":",
"return",
"async_mock_service",
"(",
"hass",
",",
"\"test\"",
",",
"\"automation\"",
")"
] | [
37,
0
] | [
39,
57
] | python | en | ['en', 'en', 'en'] | True |
test_get_triggers | (hass, device_reg, entity_reg) | Test we get the expected triggers from a humidifier device. | Test we get the expected triggers from a humidifier device. | async def test_get_triggers(hass, device_reg, entity_reg):
"""Test we get the expected triggers from a humidifier device."""
config_entry = MockConfigEntry(domain="test", data={})
config_entry.add_to_hass(hass)
device_entry = device_reg.async_get_or_create(
config_entry_id=config_entry.entry_id,
connections={(device_registry.CONNECTION_NETWORK_MAC, "12:34:56:AB:CD:EF")},
)
entity_reg.async_get_or_create(DOMAIN, "test", "5678", device_id=device_entry.id)
entity_id = f"{DOMAIN}.test_5678"
hass.states.async_set(
entity_id,
STATE_ON,
{
const.ATTR_HUMIDITY: 23,
const.ATTR_MODE: "home",
const.ATTR_AVAILABLE_MODES: ["home", "away"],
ATTR_SUPPORTED_FEATURES: 1,
},
)
expected_triggers = [
{
"platform": "device",
"domain": DOMAIN,
"type": "target_humidity_changed",
"device_id": device_entry.id,
"entity_id": entity_id,
},
{
"platform": "device",
"domain": DOMAIN,
"type": "turned_off",
"device_id": device_entry.id,
"entity_id": f"{DOMAIN}.test_5678",
},
{
"platform": "device",
"domain": DOMAIN,
"type": "turned_on",
"device_id": device_entry.id,
"entity_id": f"{DOMAIN}.test_5678",
},
]
triggers = await async_get_device_automations(hass, "trigger", device_entry.id)
assert_lists_same(triggers, expected_triggers) | [
"async",
"def",
"test_get_triggers",
"(",
"hass",
",",
"device_reg",
",",
"entity_reg",
")",
":",
"config_entry",
"=",
"MockConfigEntry",
"(",
"domain",
"=",
"\"test\"",
",",
"data",
"=",
"{",
"}",
")",
"config_entry",
".",
"add_to_hass",
"(",
"hass",
")",
"device_entry",
"=",
"device_reg",
".",
"async_get_or_create",
"(",
"config_entry_id",
"=",
"config_entry",
".",
"entry_id",
",",
"connections",
"=",
"{",
"(",
"device_registry",
".",
"CONNECTION_NETWORK_MAC",
",",
"\"12:34:56:AB:CD:EF\"",
")",
"}",
",",
")",
"entity_reg",
".",
"async_get_or_create",
"(",
"DOMAIN",
",",
"\"test\"",
",",
"\"5678\"",
",",
"device_id",
"=",
"device_entry",
".",
"id",
")",
"entity_id",
"=",
"f\"{DOMAIN}.test_5678\"",
"hass",
".",
"states",
".",
"async_set",
"(",
"entity_id",
",",
"STATE_ON",
",",
"{",
"const",
".",
"ATTR_HUMIDITY",
":",
"23",
",",
"const",
".",
"ATTR_MODE",
":",
"\"home\"",
",",
"const",
".",
"ATTR_AVAILABLE_MODES",
":",
"[",
"\"home\"",
",",
"\"away\"",
"]",
",",
"ATTR_SUPPORTED_FEATURES",
":",
"1",
",",
"}",
",",
")",
"expected_triggers",
"=",
"[",
"{",
"\"platform\"",
":",
"\"device\"",
",",
"\"domain\"",
":",
"DOMAIN",
",",
"\"type\"",
":",
"\"target_humidity_changed\"",
",",
"\"device_id\"",
":",
"device_entry",
".",
"id",
",",
"\"entity_id\"",
":",
"entity_id",
",",
"}",
",",
"{",
"\"platform\"",
":",
"\"device\"",
",",
"\"domain\"",
":",
"DOMAIN",
",",
"\"type\"",
":",
"\"turned_off\"",
",",
"\"device_id\"",
":",
"device_entry",
".",
"id",
",",
"\"entity_id\"",
":",
"f\"{DOMAIN}.test_5678\"",
",",
"}",
",",
"{",
"\"platform\"",
":",
"\"device\"",
",",
"\"domain\"",
":",
"DOMAIN",
",",
"\"type\"",
":",
"\"turned_on\"",
",",
"\"device_id\"",
":",
"device_entry",
".",
"id",
",",
"\"entity_id\"",
":",
"f\"{DOMAIN}.test_5678\"",
",",
"}",
",",
"]",
"triggers",
"=",
"await",
"async_get_device_automations",
"(",
"hass",
",",
"\"trigger\"",
",",
"device_entry",
".",
"id",
")",
"assert_lists_same",
"(",
"triggers",
",",
"expected_triggers",
")"
] | [
42,
0
] | [
86,
50
] | python | en | ['en', 'en', 'en'] | True |
test_if_fires_on_state_change | (hass, calls) | Test for turn_on and turn_off triggers firing. | Test for turn_on and turn_off triggers firing. | async def test_if_fires_on_state_change(hass, calls):
"""Test for turn_on and turn_off triggers firing."""
hass.states.async_set(
"humidifier.entity",
STATE_ON,
{
const.ATTR_HUMIDITY: 23,
const.ATTR_MODE: "home",
const.ATTR_AVAILABLE_MODES: ["home", "away"],
ATTR_SUPPORTED_FEATURES: 1,
},
)
assert await async_setup_component(
hass,
automation.DOMAIN,
{
automation.DOMAIN: [
{
"trigger": {
"platform": "device",
"domain": DOMAIN,
"device_id": "",
"entity_id": "humidifier.entity",
"type": "target_humidity_changed",
"below": 20,
},
"action": {
"service": "test.automation",
"data_template": {"some": "target_humidity_changed_below"},
},
},
{
"trigger": {
"platform": "device",
"domain": DOMAIN,
"device_id": "",
"entity_id": "humidifier.entity",
"type": "target_humidity_changed",
"above": 30,
},
"action": {
"service": "test.automation",
"data_template": {"some": "target_humidity_changed_above"},
},
},
{
"trigger": {
"platform": "device",
"domain": DOMAIN,
"device_id": "",
"entity_id": "humidifier.entity",
"type": "target_humidity_changed",
"above": 30,
"for": {"seconds": 5},
},
"action": {
"service": "test.automation",
"data_template": {"some": "target_humidity_changed_above_for"},
},
},
{
"trigger": {
"platform": "device",
"domain": DOMAIN,
"device_id": "",
"entity_id": "humidifier.entity",
"type": "turned_on",
},
"action": {
"service": "test.automation",
"data_template": {
"some": "turn_on {{ trigger.%s }}"
% "}} - {{ trigger.".join(
(
"platform",
"entity_id",
"from_state.state",
"to_state.state",
"for",
)
)
},
},
},
{
"trigger": {
"platform": "device",
"domain": DOMAIN,
"device_id": "",
"entity_id": "humidifier.entity",
"type": "turned_off",
},
"action": {
"service": "test.automation",
"data_template": {
"some": "turn_off {{ trigger.%s }}"
% "}} - {{ trigger.".join(
(
"platform",
"entity_id",
"from_state.state",
"to_state.state",
"for",
)
)
},
},
},
]
},
)
# Fake that the humidity is changing
hass.states.async_set("humidifier.entity", STATE_ON, {const.ATTR_HUMIDITY: 7})
await hass.async_block_till_done()
assert len(calls) == 1
assert calls[0].data["some"] == "target_humidity_changed_below"
# Fake that the humidity is changing
hass.states.async_set("humidifier.entity", STATE_ON, {const.ATTR_HUMIDITY: 37})
await hass.async_block_till_done()
assert len(calls) == 2
assert calls[1].data["some"] == "target_humidity_changed_above"
# Wait 6 minutes
async_fire_time_changed(hass, dt_util.utcnow() + datetime.timedelta(minutes=6))
await hass.async_block_till_done()
assert len(calls) == 3
assert calls[2].data["some"] == "target_humidity_changed_above_for"
# Fake turn off
hass.states.async_set("humidifier.entity", STATE_OFF, {const.ATTR_HUMIDITY: 37})
await hass.async_block_till_done()
assert len(calls) == 4
assert (
calls[3].data["some"] == "turn_off device - humidifier.entity - on - off - None"
)
# Fake turn on
hass.states.async_set("humidifier.entity", STATE_ON, {const.ATTR_HUMIDITY: 37})
await hass.async_block_till_done()
assert len(calls) == 5
assert (
calls[4].data["some"] == "turn_on device - humidifier.entity - off - on - None"
) | [
"async",
"def",
"test_if_fires_on_state_change",
"(",
"hass",
",",
"calls",
")",
":",
"hass",
".",
"states",
".",
"async_set",
"(",
"\"humidifier.entity\"",
",",
"STATE_ON",
",",
"{",
"const",
".",
"ATTR_HUMIDITY",
":",
"23",
",",
"const",
".",
"ATTR_MODE",
":",
"\"home\"",
",",
"const",
".",
"ATTR_AVAILABLE_MODES",
":",
"[",
"\"home\"",
",",
"\"away\"",
"]",
",",
"ATTR_SUPPORTED_FEATURES",
":",
"1",
",",
"}",
",",
")",
"assert",
"await",
"async_setup_component",
"(",
"hass",
",",
"automation",
".",
"DOMAIN",
",",
"{",
"automation",
".",
"DOMAIN",
":",
"[",
"{",
"\"trigger\"",
":",
"{",
"\"platform\"",
":",
"\"device\"",
",",
"\"domain\"",
":",
"DOMAIN",
",",
"\"device_id\"",
":",
"\"\"",
",",
"\"entity_id\"",
":",
"\"humidifier.entity\"",
",",
"\"type\"",
":",
"\"target_humidity_changed\"",
",",
"\"below\"",
":",
"20",
",",
"}",
",",
"\"action\"",
":",
"{",
"\"service\"",
":",
"\"test.automation\"",
",",
"\"data_template\"",
":",
"{",
"\"some\"",
":",
"\"target_humidity_changed_below\"",
"}",
",",
"}",
",",
"}",
",",
"{",
"\"trigger\"",
":",
"{",
"\"platform\"",
":",
"\"device\"",
",",
"\"domain\"",
":",
"DOMAIN",
",",
"\"device_id\"",
":",
"\"\"",
",",
"\"entity_id\"",
":",
"\"humidifier.entity\"",
",",
"\"type\"",
":",
"\"target_humidity_changed\"",
",",
"\"above\"",
":",
"30",
",",
"}",
",",
"\"action\"",
":",
"{",
"\"service\"",
":",
"\"test.automation\"",
",",
"\"data_template\"",
":",
"{",
"\"some\"",
":",
"\"target_humidity_changed_above\"",
"}",
",",
"}",
",",
"}",
",",
"{",
"\"trigger\"",
":",
"{",
"\"platform\"",
":",
"\"device\"",
",",
"\"domain\"",
":",
"DOMAIN",
",",
"\"device_id\"",
":",
"\"\"",
",",
"\"entity_id\"",
":",
"\"humidifier.entity\"",
",",
"\"type\"",
":",
"\"target_humidity_changed\"",
",",
"\"above\"",
":",
"30",
",",
"\"for\"",
":",
"{",
"\"seconds\"",
":",
"5",
"}",
",",
"}",
",",
"\"action\"",
":",
"{",
"\"service\"",
":",
"\"test.automation\"",
",",
"\"data_template\"",
":",
"{",
"\"some\"",
":",
"\"target_humidity_changed_above_for\"",
"}",
",",
"}",
",",
"}",
",",
"{",
"\"trigger\"",
":",
"{",
"\"platform\"",
":",
"\"device\"",
",",
"\"domain\"",
":",
"DOMAIN",
",",
"\"device_id\"",
":",
"\"\"",
",",
"\"entity_id\"",
":",
"\"humidifier.entity\"",
",",
"\"type\"",
":",
"\"turned_on\"",
",",
"}",
",",
"\"action\"",
":",
"{",
"\"service\"",
":",
"\"test.automation\"",
",",
"\"data_template\"",
":",
"{",
"\"some\"",
":",
"\"turn_on {{ trigger.%s }}\"",
"%",
"\"}} - {{ trigger.\"",
".",
"join",
"(",
"(",
"\"platform\"",
",",
"\"entity_id\"",
",",
"\"from_state.state\"",
",",
"\"to_state.state\"",
",",
"\"for\"",
",",
")",
")",
"}",
",",
"}",
",",
"}",
",",
"{",
"\"trigger\"",
":",
"{",
"\"platform\"",
":",
"\"device\"",
",",
"\"domain\"",
":",
"DOMAIN",
",",
"\"device_id\"",
":",
"\"\"",
",",
"\"entity_id\"",
":",
"\"humidifier.entity\"",
",",
"\"type\"",
":",
"\"turned_off\"",
",",
"}",
",",
"\"action\"",
":",
"{",
"\"service\"",
":",
"\"test.automation\"",
",",
"\"data_template\"",
":",
"{",
"\"some\"",
":",
"\"turn_off {{ trigger.%s }}\"",
"%",
"\"}} - {{ trigger.\"",
".",
"join",
"(",
"(",
"\"platform\"",
",",
"\"entity_id\"",
",",
"\"from_state.state\"",
",",
"\"to_state.state\"",
",",
"\"for\"",
",",
")",
")",
"}",
",",
"}",
",",
"}",
",",
"]",
"}",
",",
")",
"# Fake that the humidity is changing",
"hass",
".",
"states",
".",
"async_set",
"(",
"\"humidifier.entity\"",
",",
"STATE_ON",
",",
"{",
"const",
".",
"ATTR_HUMIDITY",
":",
"7",
"}",
")",
"await",
"hass",
".",
"async_block_till_done",
"(",
")",
"assert",
"len",
"(",
"calls",
")",
"==",
"1",
"assert",
"calls",
"[",
"0",
"]",
".",
"data",
"[",
"\"some\"",
"]",
"==",
"\"target_humidity_changed_below\"",
"# Fake that the humidity is changing",
"hass",
".",
"states",
".",
"async_set",
"(",
"\"humidifier.entity\"",
",",
"STATE_ON",
",",
"{",
"const",
".",
"ATTR_HUMIDITY",
":",
"37",
"}",
")",
"await",
"hass",
".",
"async_block_till_done",
"(",
")",
"assert",
"len",
"(",
"calls",
")",
"==",
"2",
"assert",
"calls",
"[",
"1",
"]",
".",
"data",
"[",
"\"some\"",
"]",
"==",
"\"target_humidity_changed_above\"",
"# Wait 6 minutes",
"async_fire_time_changed",
"(",
"hass",
",",
"dt_util",
".",
"utcnow",
"(",
")",
"+",
"datetime",
".",
"timedelta",
"(",
"minutes",
"=",
"6",
")",
")",
"await",
"hass",
".",
"async_block_till_done",
"(",
")",
"assert",
"len",
"(",
"calls",
")",
"==",
"3",
"assert",
"calls",
"[",
"2",
"]",
".",
"data",
"[",
"\"some\"",
"]",
"==",
"\"target_humidity_changed_above_for\"",
"# Fake turn off",
"hass",
".",
"states",
".",
"async_set",
"(",
"\"humidifier.entity\"",
",",
"STATE_OFF",
",",
"{",
"const",
".",
"ATTR_HUMIDITY",
":",
"37",
"}",
")",
"await",
"hass",
".",
"async_block_till_done",
"(",
")",
"assert",
"len",
"(",
"calls",
")",
"==",
"4",
"assert",
"(",
"calls",
"[",
"3",
"]",
".",
"data",
"[",
"\"some\"",
"]",
"==",
"\"turn_off device - humidifier.entity - on - off - None\"",
")",
"# Fake turn on",
"hass",
".",
"states",
".",
"async_set",
"(",
"\"humidifier.entity\"",
",",
"STATE_ON",
",",
"{",
"const",
".",
"ATTR_HUMIDITY",
":",
"37",
"}",
")",
"await",
"hass",
".",
"async_block_till_done",
"(",
")",
"assert",
"len",
"(",
"calls",
")",
"==",
"5",
"assert",
"(",
"calls",
"[",
"4",
"]",
".",
"data",
"[",
"\"some\"",
"]",
"==",
"\"turn_on device - humidifier.entity - off - on - None\"",
")"
] | [
89,
0
] | [
234,
5
] | python | en | ['en', 'en', 'en'] | True |
test_invalid_config | (hass, calls) | Test for turn_on and turn_off triggers firing. | Test for turn_on and turn_off triggers firing. | async def test_invalid_config(hass, calls):
"""Test for turn_on and turn_off triggers firing."""
hass.states.async_set(
"humidifier.entity",
STATE_ON,
{
const.ATTR_HUMIDITY: 23,
const.ATTR_MODE: "home",
const.ATTR_AVAILABLE_MODES: ["home", "away"],
ATTR_SUPPORTED_FEATURES: 1,
},
)
assert await async_setup_component(
hass,
automation.DOMAIN,
{
automation.DOMAIN: [
{
"trigger": {
"platform": "device",
"domain": DOMAIN,
"device_id": "",
"entity_id": "humidifier.entity",
"type": "target_humidity_changed",
"below": 20,
"invalid": "invalid",
},
"action": {
"service": "test.automation",
"data_template": {"some": "target_humidity_changed"},
},
},
]
},
)
# Fake that the humidity is changing
hass.states.async_set("humidifier.entity", STATE_ON, {const.ATTR_HUMIDITY: 7})
await hass.async_block_till_done()
# Should not trigger for invalid config
assert len(calls) == 0 | [
"async",
"def",
"test_invalid_config",
"(",
"hass",
",",
"calls",
")",
":",
"hass",
".",
"states",
".",
"async_set",
"(",
"\"humidifier.entity\"",
",",
"STATE_ON",
",",
"{",
"const",
".",
"ATTR_HUMIDITY",
":",
"23",
",",
"const",
".",
"ATTR_MODE",
":",
"\"home\"",
",",
"const",
".",
"ATTR_AVAILABLE_MODES",
":",
"[",
"\"home\"",
",",
"\"away\"",
"]",
",",
"ATTR_SUPPORTED_FEATURES",
":",
"1",
",",
"}",
",",
")",
"assert",
"await",
"async_setup_component",
"(",
"hass",
",",
"automation",
".",
"DOMAIN",
",",
"{",
"automation",
".",
"DOMAIN",
":",
"[",
"{",
"\"trigger\"",
":",
"{",
"\"platform\"",
":",
"\"device\"",
",",
"\"domain\"",
":",
"DOMAIN",
",",
"\"device_id\"",
":",
"\"\"",
",",
"\"entity_id\"",
":",
"\"humidifier.entity\"",
",",
"\"type\"",
":",
"\"target_humidity_changed\"",
",",
"\"below\"",
":",
"20",
",",
"\"invalid\"",
":",
"\"invalid\"",
",",
"}",
",",
"\"action\"",
":",
"{",
"\"service\"",
":",
"\"test.automation\"",
",",
"\"data_template\"",
":",
"{",
"\"some\"",
":",
"\"target_humidity_changed\"",
"}",
",",
"}",
",",
"}",
",",
"]",
"}",
",",
")",
"# Fake that the humidity is changing",
"hass",
".",
"states",
".",
"async_set",
"(",
"\"humidifier.entity\"",
",",
"STATE_ON",
",",
"{",
"const",
".",
"ATTR_HUMIDITY",
":",
"7",
"}",
")",
"await",
"hass",
".",
"async_block_till_done",
"(",
")",
"# Should not trigger for invalid config",
"assert",
"len",
"(",
"calls",
")",
"==",
"0"
] | [
237,
0
] | [
278,
26
] | python | en | ['en', 'en', 'en'] | True |
test_get_trigger_capabilities_on | (hass) | Test we get the expected capabilities from a humidifier trigger. | Test we get the expected capabilities from a humidifier trigger. | async def test_get_trigger_capabilities_on(hass):
"""Test we get the expected capabilities from a humidifier trigger."""
capabilities = await device_trigger.async_get_trigger_capabilities(
hass,
{
"platform": "device",
"domain": "humidifier",
"type": "turned_on",
"entity_id": "humidifier.upstairs",
"above": "23",
},
)
assert capabilities and "extra_fields" in capabilities
assert voluptuous_serialize.convert(
capabilities["extra_fields"], custom_serializer=cv.custom_serializer
) == [{"name": "for", "optional": True, "type": "positive_time_period_dict"}] | [
"async",
"def",
"test_get_trigger_capabilities_on",
"(",
"hass",
")",
":",
"capabilities",
"=",
"await",
"device_trigger",
".",
"async_get_trigger_capabilities",
"(",
"hass",
",",
"{",
"\"platform\"",
":",
"\"device\"",
",",
"\"domain\"",
":",
"\"humidifier\"",
",",
"\"type\"",
":",
"\"turned_on\"",
",",
"\"entity_id\"",
":",
"\"humidifier.upstairs\"",
",",
"\"above\"",
":",
"\"23\"",
",",
"}",
",",
")",
"assert",
"capabilities",
"and",
"\"extra_fields\"",
"in",
"capabilities",
"assert",
"voluptuous_serialize",
".",
"convert",
"(",
"capabilities",
"[",
"\"extra_fields\"",
"]",
",",
"custom_serializer",
"=",
"cv",
".",
"custom_serializer",
")",
"==",
"[",
"{",
"\"name\"",
":",
"\"for\"",
",",
"\"optional\"",
":",
"True",
",",
"\"type\"",
":",
"\"positive_time_period_dict\"",
"}",
"]"
] | [
281,
0
] | [
298,
81
] | python | en | ['en', 'en', 'en'] | True |
test_get_trigger_capabilities_off | (hass) | Test we get the expected capabilities from a humidifier trigger. | Test we get the expected capabilities from a humidifier trigger. | async def test_get_trigger_capabilities_off(hass):
"""Test we get the expected capabilities from a humidifier trigger."""
capabilities = await device_trigger.async_get_trigger_capabilities(
hass,
{
"platform": "device",
"domain": "humidifier",
"type": "turned_off",
"entity_id": "humidifier.upstairs",
"above": "23",
},
)
assert capabilities and "extra_fields" in capabilities
assert voluptuous_serialize.convert(
capabilities["extra_fields"], custom_serializer=cv.custom_serializer
) == [{"name": "for", "optional": True, "type": "positive_time_period_dict"}] | [
"async",
"def",
"test_get_trigger_capabilities_off",
"(",
"hass",
")",
":",
"capabilities",
"=",
"await",
"device_trigger",
".",
"async_get_trigger_capabilities",
"(",
"hass",
",",
"{",
"\"platform\"",
":",
"\"device\"",
",",
"\"domain\"",
":",
"\"humidifier\"",
",",
"\"type\"",
":",
"\"turned_off\"",
",",
"\"entity_id\"",
":",
"\"humidifier.upstairs\"",
",",
"\"above\"",
":",
"\"23\"",
",",
"}",
",",
")",
"assert",
"capabilities",
"and",
"\"extra_fields\"",
"in",
"capabilities",
"assert",
"voluptuous_serialize",
".",
"convert",
"(",
"capabilities",
"[",
"\"extra_fields\"",
"]",
",",
"custom_serializer",
"=",
"cv",
".",
"custom_serializer",
")",
"==",
"[",
"{",
"\"name\"",
":",
"\"for\"",
",",
"\"optional\"",
":",
"True",
",",
"\"type\"",
":",
"\"positive_time_period_dict\"",
"}",
"]"
] | [
301,
0
] | [
318,
81
] | python | en | ['en', 'en', 'en'] | True |
test_get_trigger_capabilities_humidity | (hass) | Test we get the expected capabilities from a humidifier trigger. | Test we get the expected capabilities from a humidifier trigger. | async def test_get_trigger_capabilities_humidity(hass):
"""Test we get the expected capabilities from a humidifier trigger."""
capabilities = await device_trigger.async_get_trigger_capabilities(
hass,
{
"platform": "device",
"domain": "humidifier",
"type": "target_humidity_changed",
"entity_id": "humidifier.upstairs",
"above": "23",
},
)
assert capabilities and "extra_fields" in capabilities
assert voluptuous_serialize.convert(
capabilities["extra_fields"], custom_serializer=cv.custom_serializer
) == [
{
"description": {"suffix": "%"},
"name": "above",
"optional": True,
"type": "integer",
},
{
"description": {"suffix": "%"},
"name": "below",
"optional": True,
"type": "integer",
},
{"name": "for", "optional": True, "type": "positive_time_period_dict"},
] | [
"async",
"def",
"test_get_trigger_capabilities_humidity",
"(",
"hass",
")",
":",
"capabilities",
"=",
"await",
"device_trigger",
".",
"async_get_trigger_capabilities",
"(",
"hass",
",",
"{",
"\"platform\"",
":",
"\"device\"",
",",
"\"domain\"",
":",
"\"humidifier\"",
",",
"\"type\"",
":",
"\"target_humidity_changed\"",
",",
"\"entity_id\"",
":",
"\"humidifier.upstairs\"",
",",
"\"above\"",
":",
"\"23\"",
",",
"}",
",",
")",
"assert",
"capabilities",
"and",
"\"extra_fields\"",
"in",
"capabilities",
"assert",
"voluptuous_serialize",
".",
"convert",
"(",
"capabilities",
"[",
"\"extra_fields\"",
"]",
",",
"custom_serializer",
"=",
"cv",
".",
"custom_serializer",
")",
"==",
"[",
"{",
"\"description\"",
":",
"{",
"\"suffix\"",
":",
"\"%\"",
"}",
",",
"\"name\"",
":",
"\"above\"",
",",
"\"optional\"",
":",
"True",
",",
"\"type\"",
":",
"\"integer\"",
",",
"}",
",",
"{",
"\"description\"",
":",
"{",
"\"suffix\"",
":",
"\"%\"",
"}",
",",
"\"name\"",
":",
"\"below\"",
",",
"\"optional\"",
":",
"True",
",",
"\"type\"",
":",
"\"integer\"",
",",
"}",
",",
"{",
"\"name\"",
":",
"\"for\"",
",",
"\"optional\"",
":",
"True",
",",
"\"type\"",
":",
"\"positive_time_period_dict\"",
"}",
",",
"]"
] | [
321,
0
] | [
352,
5
] | python | en | ['en', 'en', 'en'] | True |
call_shell_with_timeout | (command, timeout, *, log_return_code=True) | Run a shell command with a timeout.
If log_return_code is set to False, it will not print an error if a non-zero
return code is returned.
| Run a shell command with a timeout. | def call_shell_with_timeout(command, timeout, *, log_return_code=True):
"""Run a shell command with a timeout.
If log_return_code is set to False, it will not print an error if a non-zero
return code is returned.
"""
try:
_LOGGER.debug("Running command: %s", command)
subprocess.check_output(
command, shell=True, timeout=timeout # nosec # shell by design
)
return 0
except subprocess.CalledProcessError as proc_exception:
if log_return_code:
_LOGGER.error("Command failed: %s", command)
return proc_exception.returncode
except subprocess.TimeoutExpired:
_LOGGER.error("Timeout for command: %s", command)
return -1
except subprocess.SubprocessError:
_LOGGER.error("Error trying to exec command: %s", command)
return -1 | [
"def",
"call_shell_with_timeout",
"(",
"command",
",",
"timeout",
",",
"*",
",",
"log_return_code",
"=",
"True",
")",
":",
"try",
":",
"_LOGGER",
".",
"debug",
"(",
"\"Running command: %s\"",
",",
"command",
")",
"subprocess",
".",
"check_output",
"(",
"command",
",",
"shell",
"=",
"True",
",",
"timeout",
"=",
"timeout",
"# nosec # shell by design",
")",
"return",
"0",
"except",
"subprocess",
".",
"CalledProcessError",
"as",
"proc_exception",
":",
"if",
"log_return_code",
":",
"_LOGGER",
".",
"error",
"(",
"\"Command failed: %s\"",
",",
"command",
")",
"return",
"proc_exception",
".",
"returncode",
"except",
"subprocess",
".",
"TimeoutExpired",
":",
"_LOGGER",
".",
"error",
"(",
"\"Timeout for command: %s\"",
",",
"command",
")",
"return",
"-",
"1",
"except",
"subprocess",
".",
"SubprocessError",
":",
"_LOGGER",
".",
"error",
"(",
"\"Error trying to exec command: %s\"",
",",
"command",
")",
"return",
"-",
"1"
] | [
8,
0
] | [
29,
17
] | python | en | ['en', 'en', 'en'] | True |
check_output_or_log | (command, timeout) | Run a shell command with a timeout and return the output. | Run a shell command with a timeout and return the output. | def check_output_or_log(command, timeout):
"""Run a shell command with a timeout and return the output."""
try:
return_value = subprocess.check_output(
command, shell=True, timeout=timeout # nosec # shell by design
)
return return_value.strip().decode("utf-8")
except subprocess.CalledProcessError:
_LOGGER.error("Command failed: %s", command)
except subprocess.TimeoutExpired:
_LOGGER.error("Timeout for command: %s", command)
except subprocess.SubprocessError:
_LOGGER.error("Error trying to exec command: %s", command)
return None | [
"def",
"check_output_or_log",
"(",
"command",
",",
"timeout",
")",
":",
"try",
":",
"return_value",
"=",
"subprocess",
".",
"check_output",
"(",
"command",
",",
"shell",
"=",
"True",
",",
"timeout",
"=",
"timeout",
"# nosec # shell by design",
")",
"return",
"return_value",
".",
"strip",
"(",
")",
".",
"decode",
"(",
"\"utf-8\"",
")",
"except",
"subprocess",
".",
"CalledProcessError",
":",
"_LOGGER",
".",
"error",
"(",
"\"Command failed: %s\"",
",",
"command",
")",
"except",
"subprocess",
".",
"TimeoutExpired",
":",
"_LOGGER",
".",
"error",
"(",
"\"Timeout for command: %s\"",
",",
"command",
")",
"except",
"subprocess",
".",
"SubprocessError",
":",
"_LOGGER",
".",
"error",
"(",
"\"Error trying to exec command: %s\"",
",",
"command",
")",
"return",
"None"
] | [
32,
0
] | [
46,
15
] | python | en | ['en', 'en', 'en'] | True |
Tuner.generate_parameters | (self, parameter_id, **kwargs) |
Abstract method which provides a set of hyper-parameters.
This method will get called when the framework is about to launch a new trial,
if user does not override :meth:`generate_multiple_parameters`.
The return value of this method will be received by trials via :func:`nni.get_next_parameter`.
It should fit in the search space, though the framework will not verify this.
User code must override either this method or :meth:`generate_multiple_parameters`.
Parameters
----------
parameter_id : int
Unique identifier for requested hyper-parameters. This will later be used in :meth:`receive_trial_result`.
**kwargs
Unstable parameters which should be ignored by normal users.
Returns
-------
any
The hyper-parameters, a dict in most cases, but could be any JSON-serializable type when needed.
Raises
------
nni.NoMoreTrialError
If the search space is fully explored, tuner can raise this exception.
|
Abstract method which provides a set of hyper-parameters. | def generate_parameters(self, parameter_id, **kwargs):
"""
Abstract method which provides a set of hyper-parameters.
This method will get called when the framework is about to launch a new trial,
if user does not override :meth:`generate_multiple_parameters`.
The return value of this method will be received by trials via :func:`nni.get_next_parameter`.
It should fit in the search space, though the framework will not verify this.
User code must override either this method or :meth:`generate_multiple_parameters`.
Parameters
----------
parameter_id : int
Unique identifier for requested hyper-parameters. This will later be used in :meth:`receive_trial_result`.
**kwargs
Unstable parameters which should be ignored by normal users.
Returns
-------
any
The hyper-parameters, a dict in most cases, but could be any JSON-serializable type when needed.
Raises
------
nni.NoMoreTrialError
If the search space is fully explored, tuner can raise this exception.
"""
# FIXME: some tuners raise NoMoreTrialError when they are waiting for more trial results
# we need to design a new exception for this purpose
raise NotImplementedError('Tuner: generate_parameters not implemented') | [
"def",
"generate_parameters",
"(",
"self",
",",
"parameter_id",
",",
"*",
"*",
"kwargs",
")",
":",
"# FIXME: some tuners raise NoMoreTrialError when they are waiting for more trial results",
"# we need to design a new exception for this purpose",
"raise",
"NotImplementedError",
"(",
"'Tuner: generate_parameters not implemented'",
")"
] | [
69,
4
] | [
100,
79
] | python | en | ['en', 'error', 'th'] | False |
Tuner.generate_multiple_parameters | (self, parameter_id_list, **kwargs) |
Callback method which provides multiple sets of hyper-parameters.
This method will get called when the framework is about to launch one or more new trials.
If user does not override this method, it will invoke :meth:`generate_parameters` on each parameter ID.
See :meth:`generate_parameters` for details.
User code must override either this method or :meth:`generate_parameters`.
Parameters
----------
parameter_id_list : list of int
Unique identifiers for each set of requested hyper-parameters.
These will later be used in :meth:`receive_trial_result`.
**kwargs
Unstable parameters which should be ignored by normal users.
Returns
-------
list
List of hyper-parameters. An empty list indicates there are no more trials.
|
Callback method which provides multiple sets of hyper-parameters. | def generate_multiple_parameters(self, parameter_id_list, **kwargs):
"""
Callback method which provides multiple sets of hyper-parameters.
This method will get called when the framework is about to launch one or more new trials.
If user does not override this method, it will invoke :meth:`generate_parameters` on each parameter ID.
See :meth:`generate_parameters` for details.
User code must override either this method or :meth:`generate_parameters`.
Parameters
----------
parameter_id_list : list of int
Unique identifiers for each set of requested hyper-parameters.
These will later be used in :meth:`receive_trial_result`.
**kwargs
Unstable parameters which should be ignored by normal users.
Returns
-------
list
List of hyper-parameters. An empty list indicates there are no more trials.
"""
result = []
for parameter_id in parameter_id_list:
try:
_logger.debug("generating param for %s", parameter_id)
res = self.generate_parameters(parameter_id, **kwargs)
except nni.NoMoreTrialError:
return result
result.append(res)
return result | [
"def",
"generate_multiple_parameters",
"(",
"self",
",",
"parameter_id_list",
",",
"*",
"*",
"kwargs",
")",
":",
"result",
"=",
"[",
"]",
"for",
"parameter_id",
"in",
"parameter_id_list",
":",
"try",
":",
"_logger",
".",
"debug",
"(",
"\"generating param for %s\"",
",",
"parameter_id",
")",
"res",
"=",
"self",
".",
"generate_parameters",
"(",
"parameter_id",
",",
"*",
"*",
"kwargs",
")",
"except",
"nni",
".",
"NoMoreTrialError",
":",
"return",
"result",
"result",
".",
"append",
"(",
"res",
")",
"return",
"result"
] | [
102,
4
] | [
135,
21
] | python | en | ['en', 'error', 'th'] | False |
Tuner.receive_trial_result | (self, parameter_id, parameters, value, **kwargs) |
Abstract method invoked when a trial reports its final result. Must override.
This method only listens to results of algorithm-generated hyper-parameters.
Currently customized trials added from web UI will not report result to this method.
Parameters
----------
parameter_id : int
Unique identifier of used hyper-parameters, same with :meth:`generate_parameters`.
parameters
Hyper-parameters generated by :meth:`generate_parameters`.
value
Result from trial (the return value of :func:`nni.report_final_result`).
**kwargs
Unstable parameters which should be ignored by normal users.
|
Abstract method invoked when a trial reports its final result. Must override. | def receive_trial_result(self, parameter_id, parameters, value, **kwargs):
"""
Abstract method invoked when a trial reports its final result. Must override.
This method only listens to results of algorithm-generated hyper-parameters.
Currently customized trials added from web UI will not report result to this method.
Parameters
----------
parameter_id : int
Unique identifier of used hyper-parameters, same with :meth:`generate_parameters`.
parameters
Hyper-parameters generated by :meth:`generate_parameters`.
value
Result from trial (the return value of :func:`nni.report_final_result`).
**kwargs
Unstable parameters which should be ignored by normal users.
"""
raise NotImplementedError('Tuner: receive_trial_result not implemented') | [
"def",
"receive_trial_result",
"(",
"self",
",",
"parameter_id",
",",
"parameters",
",",
"value",
",",
"*",
"*",
"kwargs",
")",
":",
"raise",
"NotImplementedError",
"(",
"'Tuner: receive_trial_result not implemented'",
")"
] | [
137,
4
] | [
155,
80
] | python | en | ['en', 'error', 'th'] | False |
Tuner.trial_end | (self, parameter_id, success, **kwargs) |
Abstract method invoked when a trial is completed or terminated. Do nothing by default.
Parameters
----------
parameter_id : int
Unique identifier for hyper-parameters used by this trial.
success : bool
True if the trial successfully completed; False if failed or terminated.
**kwargs
Unstable parameters which should be ignored by normal users.
|
Abstract method invoked when a trial is completed or terminated. Do nothing by default. | def trial_end(self, parameter_id, success, **kwargs):
"""
Abstract method invoked when a trial is completed or terminated. Do nothing by default.
Parameters
----------
parameter_id : int
Unique identifier for hyper-parameters used by this trial.
success : bool
True if the trial successfully completed; False if failed or terminated.
**kwargs
Unstable parameters which should be ignored by normal users.
""" | [
"def",
"trial_end",
"(",
"self",
",",
"parameter_id",
",",
"success",
",",
"*",
"*",
"kwargs",
")",
":"
] | [
167,
4
] | [
179,
11
] | python | en | ['en', 'error', 'th'] | False |
Tuner.update_search_space | (self, search_space) |
Abstract method for updating the search space. Must override.
Tuners are advised to support updating search space at run-time.
If a tuner can only set search space once before generating first hyper-parameters,
it should explicitly document this behaviour.
Parameters
----------
search_space
JSON object defined by experiment owner.
|
Abstract method for updating the search space. Must override. | def update_search_space(self, search_space):
"""
Abstract method for updating the search space. Must override.
Tuners are advised to support updating search space at run-time.
If a tuner can only set search space once before generating first hyper-parameters,
it should explicitly document this behaviour.
Parameters
----------
search_space
JSON object defined by experiment owner.
"""
raise NotImplementedError('Tuner: update_search_space not implemented') | [
"def",
"update_search_space",
"(",
"self",
",",
"search_space",
")",
":",
"raise",
"NotImplementedError",
"(",
"'Tuner: update_search_space not implemented'",
")"
] | [
181,
4
] | [
194,
79
] | python | en | ['en', 'error', 'th'] | False |
Tuner.load_checkpoint | (self) |
Internal API under revising, not recommended for end users.
|
Internal API under revising, not recommended for end users.
| def load_checkpoint(self):
"""
Internal API under revising, not recommended for end users.
"""
checkpoin_path = self.get_checkpoint_path()
_logger.info('Load checkpoint ignored by tuner, checkpoint path: %s', checkpoin_path) | [
"def",
"load_checkpoint",
"(",
"self",
")",
":",
"checkpoin_path",
"=",
"self",
".",
"get_checkpoint_path",
"(",
")",
"_logger",
".",
"info",
"(",
"'Load checkpoint ignored by tuner, checkpoint path: %s'",
",",
"checkpoin_path",
")"
] | [
196,
4
] | [
201,
93
] | python | en | ['en', 'error', 'th'] | False |
Tuner.save_checkpoint | (self) |
Internal API under revising, not recommended for end users.
|
Internal API under revising, not recommended for end users.
| def save_checkpoint(self):
"""
Internal API under revising, not recommended for end users.
"""
checkpoin_path = self.get_checkpoint_path()
_logger.info('Save checkpoint ignored by tuner, checkpoint path: %s', checkpoin_path) | [
"def",
"save_checkpoint",
"(",
"self",
")",
":",
"checkpoin_path",
"=",
"self",
".",
"get_checkpoint_path",
"(",
")",
"_logger",
".",
"info",
"(",
"'Save checkpoint ignored by tuner, checkpoint path: %s'",
",",
"checkpoin_path",
")"
] | [
203,
4
] | [
208,
93
] | python | en | ['en', 'error', 'th'] | False |
Tuner.import_data | (self, data) |
Internal API under revising, not recommended for end users.
|
Internal API under revising, not recommended for end users.
| def import_data(self, data):
"""
Internal API under revising, not recommended for end users.
"""
# Import additional data for tuning
# data: a list of dictionarys, each of which has at least two keys, 'parameter' and 'value'
pass | [
"def",
"import_data",
"(",
"self",
",",
"data",
")",
":",
"# Import additional data for tuning",
"# data: a list of dictionarys, each of which has at least two keys, 'parameter' and 'value'",
"pass"
] | [
210,
4
] | [
216,
12
] | python | en | ['en', 'error', 'th'] | False |
async_setup_entry | (hass, config_entry, async_add_entities) | Set up SmartHab covers from a config entry. | Set up SmartHab covers from a config entry. | async def async_setup_entry(hass, config_entry, async_add_entities):
"""Set up SmartHab covers from a config entry."""
hub = hass.data[DOMAIN][config_entry.entry_id][DATA_HUB]
entities = (
SmartHabCover(cover)
for cover in await hub.async_get_device_list()
if isinstance(cover, pysmarthab.Shutter)
)
async_add_entities(entities, True) | [
"async",
"def",
"async_setup_entry",
"(",
"hass",
",",
"config_entry",
",",
"async_add_entities",
")",
":",
"hub",
"=",
"hass",
".",
"data",
"[",
"DOMAIN",
"]",
"[",
"config_entry",
".",
"entry_id",
"]",
"[",
"DATA_HUB",
"]",
"entities",
"=",
"(",
"SmartHabCover",
"(",
"cover",
")",
"for",
"cover",
"in",
"await",
"hub",
".",
"async_get_device_list",
"(",
")",
"if",
"isinstance",
"(",
"cover",
",",
"pysmarthab",
".",
"Shutter",
")",
")",
"async_add_entities",
"(",
"entities",
",",
"True",
")"
] | [
23,
0
] | [
33,
38
] | python | en | ['en', 'en', 'en'] | True |
SmartHabCover.__init__ | (self, cover) | Initialize a SmartHabCover. | Initialize a SmartHabCover. | def __init__(self, cover):
"""Initialize a SmartHabCover."""
self._cover = cover | [
"def",
"__init__",
"(",
"self",
",",
"cover",
")",
":",
"self",
".",
"_cover",
"=",
"cover"
] | [
39,
4
] | [
41,
27
] | python | en | ['en', 'en', 'en'] | True |
SmartHabCover.unique_id | (self) | Return a unique ID. | Return a unique ID. | def unique_id(self) -> str:
"""Return a unique ID."""
return self._cover.device_id | [
"def",
"unique_id",
"(",
"self",
")",
"->",
"str",
":",
"return",
"self",
".",
"_cover",
".",
"device_id"
] | [
44,
4
] | [
46,
36
] | python | ca | ['fr', 'ca', 'en'] | False |
SmartHabCover.name | (self) | Return the display name of this cover. | Return the display name of this cover. | def name(self) -> str:
"""Return the display name of this cover."""
return self._cover.label | [
"def",
"name",
"(",
"self",
")",
"->",
"str",
":",
"return",
"self",
".",
"_cover",
".",
"label"
] | [
49,
4
] | [
51,
32
] | python | en | ['en', 'en', 'en'] | True |
SmartHabCover.current_cover_position | (self) | Return current position of cover.
None is unknown, 0 is closed, 100 is fully open.
| Return current position of cover. | def current_cover_position(self) -> int:
"""Return current position of cover.
None is unknown, 0 is closed, 100 is fully open.
"""
return self._cover.state | [
"def",
"current_cover_position",
"(",
"self",
")",
"->",
"int",
":",
"return",
"self",
".",
"_cover",
".",
"state"
] | [
54,
4
] | [
59,
32
] | python | en | ['en', 'en', 'en'] | True |
SmartHabCover.supported_features | (self) | Flag supported features. | Flag supported features. | def supported_features(self) -> int:
"""Flag supported features."""
return SUPPORT_OPEN | SUPPORT_CLOSE | SUPPORT_SET_POSITION | [
"def",
"supported_features",
"(",
"self",
")",
"->",
"int",
":",
"return",
"SUPPORT_OPEN",
"|",
"SUPPORT_CLOSE",
"|",
"SUPPORT_SET_POSITION"
] | [
62,
4
] | [
64,
66
] | python | en | ['da', 'en', 'en'] | True |
SmartHabCover.is_closed | (self) | Return if the cover is closed or not. | Return if the cover is closed or not. | def is_closed(self) -> bool:
"""Return if the cover is closed or not."""
return self._cover.state == 0 | [
"def",
"is_closed",
"(",
"self",
")",
"->",
"bool",
":",
"return",
"self",
".",
"_cover",
".",
"state",
"==",
"0"
] | [
67,
4
] | [
69,
37
] | python | en | ['en', 'en', 'en'] | True |
SmartHabCover.device_class | (self) | Return the class of this device, from component DEVICE_CLASSES. | Return the class of this device, from component DEVICE_CLASSES. | def device_class(self) -> str:
"""Return the class of this device, from component DEVICE_CLASSES."""
return DEVICE_CLASS_WINDOW | [
"def",
"device_class",
"(",
"self",
")",
"->",
"str",
":",
"return",
"DEVICE_CLASS_WINDOW"
] | [
72,
4
] | [
74,
34
] | python | en | ['en', 'en', 'en'] | True |
SmartHabCover.async_open_cover | (self, **kwargs) | Open the cover. | Open the cover. | async def async_open_cover(self, **kwargs):
"""Open the cover."""
await self._cover.async_open() | [
"async",
"def",
"async_open_cover",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"await",
"self",
".",
"_cover",
".",
"async_open",
"(",
")"
] | [
76,
4
] | [
78,
38
] | python | en | ['en', 'en', 'en'] | True |
SmartHabCover.async_close_cover | (self, **kwargs) | Close cover. | Close cover. | async def async_close_cover(self, **kwargs):
"""Close cover."""
await self._cover.async_close() | [
"async",
"def",
"async_close_cover",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"await",
"self",
".",
"_cover",
".",
"async_close",
"(",
")"
] | [
80,
4
] | [
82,
39
] | python | en | ['en', 'la', 'en'] | False |
SmartHabCover.async_set_cover_position | (self, **kwargs) | Move the cover to a specific position. | Move the cover to a specific position. | async def async_set_cover_position(self, **kwargs):
"""Move the cover to a specific position."""
await self._cover.async_set_state(kwargs[ATTR_POSITION]) | [
"async",
"def",
"async_set_cover_position",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"await",
"self",
".",
"_cover",
".",
"async_set_state",
"(",
"kwargs",
"[",
"ATTR_POSITION",
"]",
")"
] | [
84,
4
] | [
86,
64
] | python | en | ['en', 'en', 'en'] | True |
SmartHabCover.async_update | (self) | Fetch new state data for this cover. | Fetch new state data for this cover. | async def async_update(self):
"""Fetch new state data for this cover."""
try:
await self._cover.async_update()
except Timeout:
_LOGGER.error(
"Reached timeout while updating cover %s from API", self.entity_id
) | [
"async",
"def",
"async_update",
"(",
"self",
")",
":",
"try",
":",
"await",
"self",
".",
"_cover",
".",
"async_update",
"(",
")",
"except",
"Timeout",
":",
"_LOGGER",
".",
"error",
"(",
"\"Reached timeout while updating cover %s from API\"",
",",
"self",
".",
"entity_id",
")"
] | [
88,
4
] | [
95,
13
] | python | en | ['en', 'en', 'en'] | True |
async_setup_entry | (hass, config_entry) | Set up MQTT device automation dynamically through MQTT discovery. | Set up MQTT device automation dynamically through MQTT discovery. | async def async_setup_entry(hass, config_entry):
"""Set up MQTT device automation dynamically through MQTT discovery."""
async def async_device_removed(event):
"""Handle the removal of a device."""
if event.data["action"] != "remove":
return
await device_trigger.async_device_removed(hass, event.data["device_id"])
async def async_discover(discovery_payload):
"""Discover and add an MQTT device automation."""
discovery_data = discovery_payload.discovery_data
try:
config = PLATFORM_SCHEMA(discovery_payload)
if config[CONF_AUTOMATION_TYPE] == AUTOMATION_TYPE_TRIGGER:
await device_trigger.async_setup_trigger(
hass, config, config_entry, discovery_data
)
except Exception:
clear_discovery_hash(hass, discovery_data[ATTR_DISCOVERY_HASH])
raise
async_dispatcher_connect(
hass, MQTT_DISCOVERY_NEW.format("device_automation", "mqtt"), async_discover
)
hass.bus.async_listen(EVENT_DEVICE_REGISTRY_UPDATED, async_device_removed) | [
"async",
"def",
"async_setup_entry",
"(",
"hass",
",",
"config_entry",
")",
":",
"async",
"def",
"async_device_removed",
"(",
"event",
")",
":",
"\"\"\"Handle the removal of a device.\"\"\"",
"if",
"event",
".",
"data",
"[",
"\"action\"",
"]",
"!=",
"\"remove\"",
":",
"return",
"await",
"device_trigger",
".",
"async_device_removed",
"(",
"hass",
",",
"event",
".",
"data",
"[",
"\"device_id\"",
"]",
")",
"async",
"def",
"async_discover",
"(",
"discovery_payload",
")",
":",
"\"\"\"Discover and add an MQTT device automation.\"\"\"",
"discovery_data",
"=",
"discovery_payload",
".",
"discovery_data",
"try",
":",
"config",
"=",
"PLATFORM_SCHEMA",
"(",
"discovery_payload",
")",
"if",
"config",
"[",
"CONF_AUTOMATION_TYPE",
"]",
"==",
"AUTOMATION_TYPE_TRIGGER",
":",
"await",
"device_trigger",
".",
"async_setup_trigger",
"(",
"hass",
",",
"config",
",",
"config_entry",
",",
"discovery_data",
")",
"except",
"Exception",
":",
"clear_discovery_hash",
"(",
"hass",
",",
"discovery_data",
"[",
"ATTR_DISCOVERY_HASH",
"]",
")",
"raise",
"async_dispatcher_connect",
"(",
"hass",
",",
"MQTT_DISCOVERY_NEW",
".",
"format",
"(",
"\"device_automation\"",
",",
"\"mqtt\"",
")",
",",
"async_discover",
")",
"hass",
".",
"bus",
".",
"async_listen",
"(",
"EVENT_DEVICE_REGISTRY_UPDATED",
",",
"async_device_removed",
")"
] | [
25,
0
] | [
50,
78
] | python | en | ['en', 'en', 'en'] | True |
async_setup_entry | (
hass: HomeAssistant, config_entry: ConfigEntry, async_add_entities
) | Set up Yeelight from a config entry. | Set up Yeelight from a config entry. | async def async_setup_entry(
hass: HomeAssistant, config_entry: ConfigEntry, async_add_entities
) -> None:
"""Set up Yeelight from a config entry."""
device = hass.data[DOMAIN][DATA_CONFIG_ENTRIES][config_entry.entry_id][DATA_DEVICE]
if device.is_nightlight_supported:
_LOGGER.debug("Adding nightlight mode sensor for %s", device.name)
async_add_entities([YeelightNightlightModeSensor(device, config_entry)]) | [
"async",
"def",
"async_setup_entry",
"(",
"hass",
":",
"HomeAssistant",
",",
"config_entry",
":",
"ConfigEntry",
",",
"async_add_entities",
")",
"->",
"None",
":",
"device",
"=",
"hass",
".",
"data",
"[",
"DOMAIN",
"]",
"[",
"DATA_CONFIG_ENTRIES",
"]",
"[",
"config_entry",
".",
"entry_id",
"]",
"[",
"DATA_DEVICE",
"]",
"if",
"device",
".",
"is_nightlight_supported",
":",
"_LOGGER",
".",
"debug",
"(",
"\"Adding nightlight mode sensor for %s\"",
",",
"device",
".",
"name",
")",
"async_add_entities",
"(",
"[",
"YeelightNightlightModeSensor",
"(",
"device",
",",
"config_entry",
")",
"]",
")"
] | [
13,
0
] | [
20,
80
] | python | en | ['en', 'en', 'en'] | True |
YeelightNightlightModeSensor.async_added_to_hass | (self) | Handle entity which will be added. | Handle entity which will be added. | async def async_added_to_hass(self):
"""Handle entity which will be added."""
self.async_on_remove(
async_dispatcher_connect(
self.hass,
DATA_UPDATED.format(self._device.host),
self.async_write_ha_state,
)
) | [
"async",
"def",
"async_added_to_hass",
"(",
"self",
")",
":",
"self",
".",
"async_on_remove",
"(",
"async_dispatcher_connect",
"(",
"self",
".",
"hass",
",",
"DATA_UPDATED",
".",
"format",
"(",
"self",
".",
"_device",
".",
"host",
")",
",",
"self",
".",
"async_write_ha_state",
",",
")",
")"
] | [
26,
4
] | [
34,
9
] | python | en | ['en', 'en', 'en'] | True |
YeelightNightlightModeSensor.unique_id | (self) | Return a unique ID. | Return a unique ID. | def unique_id(self) -> str:
"""Return a unique ID."""
return f"{self._unique_id}-nightlight_sensor" | [
"def",
"unique_id",
"(",
"self",
")",
"->",
"str",
":",
"return",
"f\"{self._unique_id}-nightlight_sensor\""
] | [
37,
4
] | [
39,
53
] | python | ca | ['fr', 'ca', 'en'] | False |
YeelightNightlightModeSensor.name | (self) | Return the name of the sensor. | Return the name of the sensor. | def name(self):
"""Return the name of the sensor."""
return f"{self._device.name} nightlight" | [
"def",
"name",
"(",
"self",
")",
":",
"return",
"f\"{self._device.name} nightlight\""
] | [
42,
4
] | [
44,
48
] | python | en | ['en', 'mi', 'en'] | True |
YeelightNightlightModeSensor.is_on | (self) | Return true if nightlight mode is on. | Return true if nightlight mode is on. | def is_on(self):
"""Return true if nightlight mode is on."""
return self._device.is_nightlight_enabled | [
"def",
"is_on",
"(",
"self",
")",
":",
"return",
"self",
".",
"_device",
".",
"is_nightlight_enabled"
] | [
47,
4
] | [
49,
49
] | python | en | ['en', 'fy', 'en'] | True |
get_scanner | (hass, config) | Validate the configuration and return a Xiaomi Device Scanner. | Validate the configuration and return a Xiaomi Device Scanner. | def get_scanner(hass, config):
"""Validate the configuration and return a Xiaomi Device Scanner."""
scanner = XiaomiDeviceScanner(config[DOMAIN])
return scanner if scanner.success_init else None | [
"def",
"get_scanner",
"(",
"hass",
",",
"config",
")",
":",
"scanner",
"=",
"XiaomiDeviceScanner",
"(",
"config",
"[",
"DOMAIN",
"]",
")",
"return",
"scanner",
"if",
"scanner",
".",
"success_init",
"else",
"None"
] | [
25,
0
] | [
29,
52
] | python | en | ['en', 'en', 'en'] | True |
_retrieve_list | (host, token, **kwargs) | Get device list for the given host. | Get device list for the given host. | def _retrieve_list(host, token, **kwargs):
"""Get device list for the given host."""
url = "http://{}/cgi-bin/luci/;stok={}/api/misystem/devicelist"
url = url.format(host, token)
try:
res = requests.get(url, timeout=5, **kwargs)
except requests.exceptions.Timeout:
_LOGGER.exception("Connection to the router timed out at URL %s", url)
return
if res.status_code != HTTP_OK:
_LOGGER.exception("Connection failed with http code %s", res.status_code)
return
try:
result = res.json()
except ValueError:
# If json decoder could not parse the response
_LOGGER.exception("Failed to parse response from mi router")
return
try:
xiaomi_code = result["code"]
except KeyError:
_LOGGER.exception("No field code in response from mi router. %s", result)
return
if xiaomi_code == 0:
try:
return result["list"]
except KeyError:
_LOGGER.exception("No list in response from mi router. %s", result)
return
else:
_LOGGER.info(
"Receive wrong Xiaomi code %s, expected 0 in response %s",
xiaomi_code,
result,
)
return | [
"def",
"_retrieve_list",
"(",
"host",
",",
"token",
",",
"*",
"*",
"kwargs",
")",
":",
"url",
"=",
"\"http://{}/cgi-bin/luci/;stok={}/api/misystem/devicelist\"",
"url",
"=",
"url",
".",
"format",
"(",
"host",
",",
"token",
")",
"try",
":",
"res",
"=",
"requests",
".",
"get",
"(",
"url",
",",
"timeout",
"=",
"5",
",",
"*",
"*",
"kwargs",
")",
"except",
"requests",
".",
"exceptions",
".",
"Timeout",
":",
"_LOGGER",
".",
"exception",
"(",
"\"Connection to the router timed out at URL %s\"",
",",
"url",
")",
"return",
"if",
"res",
".",
"status_code",
"!=",
"HTTP_OK",
":",
"_LOGGER",
".",
"exception",
"(",
"\"Connection failed with http code %s\"",
",",
"res",
".",
"status_code",
")",
"return",
"try",
":",
"result",
"=",
"res",
".",
"json",
"(",
")",
"except",
"ValueError",
":",
"# If json decoder could not parse the response",
"_LOGGER",
".",
"exception",
"(",
"\"Failed to parse response from mi router\"",
")",
"return",
"try",
":",
"xiaomi_code",
"=",
"result",
"[",
"\"code\"",
"]",
"except",
"KeyError",
":",
"_LOGGER",
".",
"exception",
"(",
"\"No field code in response from mi router. %s\"",
",",
"result",
")",
"return",
"if",
"xiaomi_code",
"==",
"0",
":",
"try",
":",
"return",
"result",
"[",
"\"list\"",
"]",
"except",
"KeyError",
":",
"_LOGGER",
".",
"exception",
"(",
"\"No list in response from mi router. %s\"",
",",
"result",
")",
"return",
"else",
":",
"_LOGGER",
".",
"info",
"(",
"\"Receive wrong Xiaomi code %s, expected 0 in response %s\"",
",",
"xiaomi_code",
",",
"result",
",",
")",
"return"
] | [
105,
0
] | [
140,
14
] | python | en | ['en', 'en', 'en'] | True |
_get_token | (host, username, password) | Get authentication token for the given host+username+password. | Get authentication token for the given host+username+password. | def _get_token(host, username, password):
"""Get authentication token for the given host+username+password."""
url = f"http://{host}/cgi-bin/luci/api/xqsystem/login"
data = {"username": username, "password": password}
try:
res = requests.post(url, data=data, timeout=5)
except requests.exceptions.Timeout:
_LOGGER.exception("Connection to the router timed out")
return
if res.status_code == HTTP_OK:
try:
result = res.json()
except ValueError:
# If JSON decoder could not parse the response
_LOGGER.exception("Failed to parse response from mi router")
return
try:
return result["token"]
except KeyError:
error_message = (
"Xiaomi token cannot be refreshed, response from "
+ "url: [%s] \nwith parameter: [%s] \nwas: [%s]"
)
_LOGGER.exception(error_message, url, data, result)
return
else:
_LOGGER.error(
"Invalid response: [%s] at url: [%s] with data [%s]", res, url, data
) | [
"def",
"_get_token",
"(",
"host",
",",
"username",
",",
"password",
")",
":",
"url",
"=",
"f\"http://{host}/cgi-bin/luci/api/xqsystem/login\"",
"data",
"=",
"{",
"\"username\"",
":",
"username",
",",
"\"password\"",
":",
"password",
"}",
"try",
":",
"res",
"=",
"requests",
".",
"post",
"(",
"url",
",",
"data",
"=",
"data",
",",
"timeout",
"=",
"5",
")",
"except",
"requests",
".",
"exceptions",
".",
"Timeout",
":",
"_LOGGER",
".",
"exception",
"(",
"\"Connection to the router timed out\"",
")",
"return",
"if",
"res",
".",
"status_code",
"==",
"HTTP_OK",
":",
"try",
":",
"result",
"=",
"res",
".",
"json",
"(",
")",
"except",
"ValueError",
":",
"# If JSON decoder could not parse the response",
"_LOGGER",
".",
"exception",
"(",
"\"Failed to parse response from mi router\"",
")",
"return",
"try",
":",
"return",
"result",
"[",
"\"token\"",
"]",
"except",
"KeyError",
":",
"error_message",
"=",
"(",
"\"Xiaomi token cannot be refreshed, response from \"",
"+",
"\"url: [%s] \\nwith parameter: [%s] \\nwas: [%s]\"",
")",
"_LOGGER",
".",
"exception",
"(",
"error_message",
",",
"url",
",",
"data",
",",
"result",
")",
"return",
"else",
":",
"_LOGGER",
".",
"error",
"(",
"\"Invalid response: [%s] at url: [%s] with data [%s]\"",
",",
"res",
",",
"url",
",",
"data",
")"
] | [
143,
0
] | [
171,
9
] | python | en | ['en', 'en', 'en'] | True |
XiaomiDeviceScanner.__init__ | (self, config) | Initialize the scanner. | Initialize the scanner. | def __init__(self, config):
"""Initialize the scanner."""
self.host = config[CONF_HOST]
self.username = config[CONF_USERNAME]
self.password = config[CONF_PASSWORD]
self.last_results = {}
self.token = _get_token(self.host, self.username, self.password)
self.mac2name = None
self.success_init = self.token is not None | [
"def",
"__init__",
"(",
"self",
",",
"config",
")",
":",
"self",
".",
"host",
"=",
"config",
"[",
"CONF_HOST",
"]",
"self",
".",
"username",
"=",
"config",
"[",
"CONF_USERNAME",
"]",
"self",
".",
"password",
"=",
"config",
"[",
"CONF_PASSWORD",
"]",
"self",
".",
"last_results",
"=",
"{",
"}",
"self",
".",
"token",
"=",
"_get_token",
"(",
"self",
".",
"host",
",",
"self",
".",
"username",
",",
"self",
".",
"password",
")",
"self",
".",
"mac2name",
"=",
"None",
"self",
".",
"success_init",
"=",
"self",
".",
"token",
"is",
"not",
"None"
] | [
38,
4
] | [
48,
50
] | python | en | ['en', 'en', 'en'] | True |
XiaomiDeviceScanner.scan_devices | (self) | Scan for new devices and return a list with found device IDs. | Scan for new devices and return a list with found device IDs. | def scan_devices(self):
"""Scan for new devices and return a list with found device IDs."""
self._update_info()
return self.last_results | [
"def",
"scan_devices",
"(",
"self",
")",
":",
"self",
".",
"_update_info",
"(",
")",
"return",
"self",
".",
"last_results"
] | [
50,
4
] | [
53,
32
] | python | en | ['en', 'en', 'en'] | True |
XiaomiDeviceScanner.get_device_name | (self, device) | Return the name of the given device or None if we don't know. | Return the name of the given device or None if we don't know. | def get_device_name(self, device):
"""Return the name of the given device or None if we don't know."""
if self.mac2name is None:
result = self._retrieve_list_with_retry()
if result:
hosts = [x for x in result if "mac" in x and "name" in x]
mac2name_list = [(x["mac"].upper(), x["name"]) for x in hosts]
self.mac2name = dict(mac2name_list)
else:
# Error, handled in the _retrieve_list_with_retry
return
return self.mac2name.get(device.upper(), None) | [
"def",
"get_device_name",
"(",
"self",
",",
"device",
")",
":",
"if",
"self",
".",
"mac2name",
"is",
"None",
":",
"result",
"=",
"self",
".",
"_retrieve_list_with_retry",
"(",
")",
"if",
"result",
":",
"hosts",
"=",
"[",
"x",
"for",
"x",
"in",
"result",
"if",
"\"mac\"",
"in",
"x",
"and",
"\"name\"",
"in",
"x",
"]",
"mac2name_list",
"=",
"[",
"(",
"x",
"[",
"\"mac\"",
"]",
".",
"upper",
"(",
")",
",",
"x",
"[",
"\"name\"",
"]",
")",
"for",
"x",
"in",
"hosts",
"]",
"self",
".",
"mac2name",
"=",
"dict",
"(",
"mac2name_list",
")",
"else",
":",
"# Error, handled in the _retrieve_list_with_retry",
"return",
"return",
"self",
".",
"mac2name",
".",
"get",
"(",
"device",
".",
"upper",
"(",
")",
",",
"None",
")"
] | [
55,
4
] | [
66,
54
] | python | en | ['en', 'en', 'en'] | True |
XiaomiDeviceScanner._update_info | (self) | Ensure the information from the router are up to date.
Returns true if scanning successful.
| Ensure the information from the router are up to date. | def _update_info(self):
"""Ensure the information from the router are up to date.
Returns true if scanning successful.
"""
if not self.success_init:
return False
result = self._retrieve_list_with_retry()
if result:
self._store_result(result)
return True
return False | [
"def",
"_update_info",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"success_init",
":",
"return",
"False",
"result",
"=",
"self",
".",
"_retrieve_list_with_retry",
"(",
")",
"if",
"result",
":",
"self",
".",
"_store_result",
"(",
"result",
")",
"return",
"True",
"return",
"False"
] | [
68,
4
] | [
80,
20
] | python | en | ['en', 'en', 'en'] | True |
XiaomiDeviceScanner._retrieve_list_with_retry | (self) | Retrieve the device list with a retry if token is invalid.
Return the list if successful.
| Retrieve the device list with a retry if token is invalid. | def _retrieve_list_with_retry(self):
"""Retrieve the device list with a retry if token is invalid.
Return the list if successful.
"""
_LOGGER.debug("Refreshing device list")
result = _retrieve_list(self.host, self.token)
if result:
return result
_LOGGER.debug("Refreshing token and retrying device list refresh")
self.token = _get_token(self.host, self.username, self.password)
return _retrieve_list(self.host, self.token) | [
"def",
"_retrieve_list_with_retry",
"(",
"self",
")",
":",
"_LOGGER",
".",
"debug",
"(",
"\"Refreshing device list\"",
")",
"result",
"=",
"_retrieve_list",
"(",
"self",
".",
"host",
",",
"self",
".",
"token",
")",
"if",
"result",
":",
"return",
"result",
"_LOGGER",
".",
"debug",
"(",
"\"Refreshing token and retrying device list refresh\"",
")",
"self",
".",
"token",
"=",
"_get_token",
"(",
"self",
".",
"host",
",",
"self",
".",
"username",
",",
"self",
".",
"password",
")",
"return",
"_retrieve_list",
"(",
"self",
".",
"host",
",",
"self",
".",
"token",
")"
] | [
82,
4
] | [
94,
52
] | python | en | ['en', 'en', 'en'] | True |
XiaomiDeviceScanner._store_result | (self, result) | Extract and store the device list in self.last_results. | Extract and store the device list in self.last_results. | def _store_result(self, result):
"""Extract and store the device list in self.last_results."""
self.last_results = []
for device_entry in result:
# Check if the device is marked as connected
if int(device_entry["online"]) == 1:
self.last_results.append(device_entry["mac"]) | [
"def",
"_store_result",
"(",
"self",
",",
"result",
")",
":",
"self",
".",
"last_results",
"=",
"[",
"]",
"for",
"device_entry",
"in",
"result",
":",
"# Check if the device is marked as connected",
"if",
"int",
"(",
"device_entry",
"[",
"\"online\"",
"]",
")",
"==",
"1",
":",
"self",
".",
"last_results",
".",
"append",
"(",
"device_entry",
"[",
"\"mac\"",
"]",
")"
] | [
96,
4
] | [
102,
61
] | python | en | ['en', 'en', 'en'] | True |
NgramCounter.__init__ | (self, n, vocabulary, unknown="<UNK>") |
n is the size of the ngram
|
n is the size of the ngram
| def __init__(self, n, vocabulary, unknown="<UNK>"):
"""
n is the size of the ngram
"""
if n < 1:
raise ValueError("ngram size must be greater than or equal to 1")
self.n = n
self.unknown = unknown
self.padding = {
"pad_left": True,
"pad_right": True,
"left_pad_symbol": "<s>",
"right_pad_symbol": "</s>"
}
self.vocabulary = vocabulary
self.allgrams = defaultdict(ConditionalFreqDist)
self.ngrams = FreqDist()
self.unigrams = FreqDist() | [
"def",
"__init__",
"(",
"self",
",",
"n",
",",
"vocabulary",
",",
"unknown",
"=",
"\"<UNK>\"",
")",
":",
"if",
"n",
"<",
"1",
":",
"raise",
"ValueError",
"(",
"\"ngram size must be greater than or equal to 1\"",
")",
"self",
".",
"n",
"=",
"n",
"self",
".",
"unknown",
"=",
"unknown",
"self",
".",
"padding",
"=",
"{",
"\"pad_left\"",
":",
"True",
",",
"\"pad_right\"",
":",
"True",
",",
"\"left_pad_symbol\"",
":",
"\"<s>\"",
",",
"\"right_pad_symbol\"",
":",
"\"</s>\"",
"}",
"self",
".",
"vocabulary",
"=",
"vocabulary",
"self",
".",
"allgrams",
"=",
"defaultdict",
"(",
"ConditionalFreqDist",
")",
"self",
".",
"ngrams",
"=",
"FreqDist",
"(",
")",
"self",
".",
"unigrams",
"=",
"FreqDist",
"(",
")"
] | [
24,
4
] | [
43,
34
] | python | en | ['en', 'error', 'th'] | False |
NgramCounter.to_ngrams | (self, sequence) |
Wrapper for NLTK ngrams method
|
Wrapper for NLTK ngrams method
| def to_ngrams(self, sequence):
"""
Wrapper for NLTK ngrams method
"""
return ngrams(sequence, self.n, **self.padding) | [
"def",
"to_ngrams",
"(",
"self",
",",
"sequence",
")",
":",
"return",
"ngrams",
"(",
"sequence",
",",
"self",
".",
"n",
",",
"*",
"*",
"self",
".",
"padding",
")"
] | [
67,
4
] | [
71,
55
] | python | en | ['en', 'error', 'th'] | False |
BaseNgramModel.__init__ | (self, ngram_counter) |
BaseNgramModel is initialized with an NgramCounter.
|
BaseNgramModel is initialized with an NgramCounter.
| def __init__(self, ngram_counter):
"""
BaseNgramModel is initialized with an NgramCounter.
"""
self.n = ngram_counter.n
self.ngram_counter = ngram_counter
self.ngrams = ngram_counter.ngrams
self._check_against_vocab = self.ngram_counter.check_against_vocab | [
"def",
"__init__",
"(",
"self",
",",
"ngram_counter",
")",
":",
"self",
".",
"n",
"=",
"ngram_counter",
".",
"n",
"self",
".",
"ngram_counter",
"=",
"ngram_counter",
"self",
".",
"ngrams",
"=",
"ngram_counter",
".",
"ngrams",
"self",
".",
"_check_against_vocab",
"=",
"self",
".",
"ngram_counter",
".",
"check_against_vocab"
] | [
80,
4
] | [
87,
74
] | python | en | ['en', 'error', 'th'] | False |
BaseNgramModel.check_context | (self, context) |
Ensures that the context is not longer than or equal to the model's
n-gram order.
Returns the context as a tuple.
|
Ensures that the context is not longer than or equal to the model's
n-gram order. | def check_context(self, context):
"""
Ensures that the context is not longer than or equal to the model's
n-gram order.
Returns the context as a tuple.
"""
if len(context) >= self.n:
raise ValueError("Context too long for this n-gram")
return tuple(context) | [
"def",
"check_context",
"(",
"self",
",",
"context",
")",
":",
"if",
"len",
"(",
"context",
")",
">=",
"self",
".",
"n",
":",
"raise",
"ValueError",
"(",
"\"Context too long for this n-gram\"",
")",
"return",
"tuple",
"(",
"context",
")"
] | [
89,
4
] | [
99,
29
] | python | en | ['en', 'error', 'th'] | False |
BaseNgramModel.score | (self, word, context) |
For a given string representation of a word, and a string word context,
returns the maximum likelihood score that the word will follow the
context.
|
For a given string representation of a word, and a string word context,
returns the maximum likelihood score that the word will follow the
context.
| def score(self, word, context):
"""
For a given string representation of a word, and a string word context,
returns the maximum likelihood score that the word will follow the
context.
"""
context = self.check_context(context)
return self.ngrams[context].freq(word) | [
"def",
"score",
"(",
"self",
",",
"word",
",",
"context",
")",
":",
"context",
"=",
"self",
".",
"check_context",
"(",
"context",
")",
"return",
"self",
".",
"ngrams",
"[",
"context",
"]",
".",
"freq",
"(",
"word",
")"
] | [
101,
4
] | [
109,
46
] | python | en | ['en', 'error', 'th'] | False |
BaseNgramModel.logscore | (self, word, context) |
For a given string representation of a word, and a word context,
computes the log probability of this word in this context.
|
For a given string representation of a word, and a word context,
computes the log probability of this word in this context.
| def logscore(self, word, context):
"""
For a given string representation of a word, and a word context,
computes the log probability of this word in this context.
"""
score = self.score(word, context)
if score == 0.0:
return float("-inf")
return log(score, 2) | [
"def",
"logscore",
"(",
"self",
",",
"word",
",",
"context",
")",
":",
"score",
"=",
"self",
".",
"score",
"(",
"word",
",",
"context",
")",
"if",
"score",
"==",
"0.0",
":",
"return",
"float",
"(",
"\"-inf\"",
")",
"return",
"log",
"(",
"score",
",",
"2",
")"
] | [
111,
4
] | [
120,
28
] | python | en | ['en', 'error', 'th'] | False |
BaseNgramModel.entropy | (self, text) |
Calculate the approximate cross-entropy of the n-gram model for a
given text represented as a list of comma-separated strings.
This is the average log probability of each word in the text.
|
Calculate the approximate cross-entropy of the n-gram model for a
given text represented as a list of comma-separated strings.
This is the average log probability of each word in the text.
| def entropy(self, text):
"""
Calculate the approximate cross-entropy of the n-gram model for a
given text represented as a list of comma-separated strings.
This is the average log probability of each word in the text.
"""
normed_text = (self._check_against_vocab(word) for word in text)
entropy = 0.0
processed_ngrams = 0
for ngram in self.ngram_counter.to_ngrams(normed_text):
context, word = tuple(ngram[:-1]), ngram[-1]
entropy += self.logscore(word, context)
processed_ngrams += 1
return - (entropy / processed_ngrams) | [
"def",
"entropy",
"(",
"self",
",",
"text",
")",
":",
"normed_text",
"=",
"(",
"self",
".",
"_check_against_vocab",
"(",
"word",
")",
"for",
"word",
"in",
"text",
")",
"entropy",
"=",
"0.0",
"processed_ngrams",
"=",
"0",
"for",
"ngram",
"in",
"self",
".",
"ngram_counter",
".",
"to_ngrams",
"(",
"normed_text",
")",
":",
"context",
",",
"word",
"=",
"tuple",
"(",
"ngram",
"[",
":",
"-",
"1",
"]",
")",
",",
"ngram",
"[",
"-",
"1",
"]",
"entropy",
"+=",
"self",
".",
"logscore",
"(",
"word",
",",
"context",
")",
"processed_ngrams",
"+=",
"1",
"return",
"-",
"(",
"entropy",
"/",
"processed_ngrams",
")"
] | [
122,
4
] | [
135,
45
] | python | en | ['en', 'error', 'th'] | False |
BaseNgramModel.perplexity | (self, text) |
Given list of comma-separated strings, calculates the perplexity
of the text.
|
Given list of comma-separated strings, calculates the perplexity
of the text.
| def perplexity(self, text):
"""
Given list of comma-separated strings, calculates the perplexity
of the text.
"""
return pow(2.0, self.entropy(text)) | [
"def",
"perplexity",
"(",
"self",
",",
"text",
")",
":",
"return",
"pow",
"(",
"2.0",
",",
"self",
".",
"entropy",
"(",
"text",
")",
")"
] | [
137,
4
] | [
142,
43
] | python | en | ['en', 'error', 'th'] | False |
AddKNgramModel.__init__ | (self, k, *args) |
Expects an input value, k, a number by which
to increment word counts during scoring.
|
Expects an input value, k, a number by which
to increment word counts during scoring.
| def __init__(self, k, *args):
"""
Expects an input value, k, a number by which
to increment word counts during scoring.
"""
super(AddKNgramModel, self).__init__(*args)
self.k = k
self.k_norm = len(self.ngram_counter.vocabulary) * k | [
"def",
"__init__",
"(",
"self",
",",
"k",
",",
"*",
"args",
")",
":",
"super",
"(",
"AddKNgramModel",
",",
"self",
")",
".",
"__init__",
"(",
"*",
"args",
")",
"self",
".",
"k",
"=",
"k",
"self",
".",
"k_norm",
"=",
"len",
"(",
"self",
".",
"ngram_counter",
".",
"vocabulary",
")",
"*",
"k"
] | [
150,
4
] | [
158,
60
] | python | en | ['en', 'error', 'th'] | False |
AddKNgramModel.score | (self, word, context) |
With Add-k-smoothing, the score is normalized with
a k value.
|
With Add-k-smoothing, the score is normalized with
a k value.
| def score(self, word, context):
"""
With Add-k-smoothing, the score is normalized with
a k value.
"""
context = self.check_context(context)
context_freqdist = self.ngrams[context]
word_count = context_freqdist[word]
context_count = context_freqdist.N()
return (word_count + self.k) / \
(context_count + self.k_norm) | [
"def",
"score",
"(",
"self",
",",
"word",
",",
"context",
")",
":",
"context",
"=",
"self",
".",
"check_context",
"(",
"context",
")",
"context_freqdist",
"=",
"self",
".",
"ngrams",
"[",
"context",
"]",
"word_count",
"=",
"context_freqdist",
"[",
"word",
"]",
"context_count",
"=",
"context_freqdist",
".",
"N",
"(",
")",
"return",
"(",
"word_count",
"+",
"self",
".",
"k",
")",
"/",
"(",
"context_count",
"+",
"self",
".",
"k_norm",
")"
] | [
160,
4
] | [
170,
44
] | python | en | ['en', 'error', 'th'] | False |
KneserNeyModel.score | (self, word, context) |
Use KneserNeyProbDist from NLTK to get score
|
Use KneserNeyProbDist from NLTK to get score
| def score(self, word, context):
"""
Use KneserNeyProbDist from NLTK to get score
"""
trigram = tuple((context[0], context[1], word))
return self.model.prob(trigram) | [
"def",
"score",
"(",
"self",
",",
"word",
",",
"context",
")",
":",
"trigram",
"=",
"tuple",
"(",
"(",
"context",
"[",
"0",
"]",
",",
"context",
"[",
"1",
"]",
",",
"word",
")",
")",
"return",
"self",
".",
"model",
".",
"prob",
"(",
"trigram",
")"
] | [
191,
4
] | [
196,
39
] | python | en | ['en', 'error', 'th'] | False |
setup_platform | (hass, config, add_entities, discovery_info=None) | Set up a Rain Bird sensor. | Set up a Rain Bird sensor. | def setup_platform(hass, config, add_entities, discovery_info=None):
"""Set up a Rain Bird sensor."""
if discovery_info is None:
return
controller = hass.data[DATA_RAINBIRD][discovery_info[RAINBIRD_CONTROLLER]]
add_entities(
[RainBirdSensor(controller, sensor_type) for sensor_type in SENSOR_TYPES], True
) | [
"def",
"setup_platform",
"(",
"hass",
",",
"config",
",",
"add_entities",
",",
"discovery_info",
"=",
"None",
")",
":",
"if",
"discovery_info",
"is",
"None",
":",
"return",
"controller",
"=",
"hass",
".",
"data",
"[",
"DATA_RAINBIRD",
"]",
"[",
"discovery_info",
"[",
"RAINBIRD_CONTROLLER",
"]",
"]",
"add_entities",
"(",
"[",
"RainBirdSensor",
"(",
"controller",
",",
"sensor_type",
")",
"for",
"sensor_type",
"in",
"SENSOR_TYPES",
"]",
",",
"True",
")"
] | [
18,
0
] | [
27,
5
] | python | en | ['en', 'su', 'en'] | True |
RainBirdSensor.__init__ | (self, controller: RainbirdController, sensor_type) | Initialize the Rain Bird sensor. | Initialize the Rain Bird sensor. | def __init__(self, controller: RainbirdController, sensor_type):
"""Initialize the Rain Bird sensor."""
self._sensor_type = sensor_type
self._controller = controller
self._name = SENSOR_TYPES[self._sensor_type][0]
self._icon = SENSOR_TYPES[self._sensor_type][2]
self._unit_of_measurement = SENSOR_TYPES[self._sensor_type][1]
self._state = None | [
"def",
"__init__",
"(",
"self",
",",
"controller",
":",
"RainbirdController",
",",
"sensor_type",
")",
":",
"self",
".",
"_sensor_type",
"=",
"sensor_type",
"self",
".",
"_controller",
"=",
"controller",
"self",
".",
"_name",
"=",
"SENSOR_TYPES",
"[",
"self",
".",
"_sensor_type",
"]",
"[",
"0",
"]",
"self",
".",
"_icon",
"=",
"SENSOR_TYPES",
"[",
"self",
".",
"_sensor_type",
"]",
"[",
"2",
"]",
"self",
".",
"_unit_of_measurement",
"=",
"SENSOR_TYPES",
"[",
"self",
".",
"_sensor_type",
"]",
"[",
"1",
"]",
"self",
".",
"_state",
"=",
"None"
] | [
33,
4
] | [
40,
26
] | python | en | ['en', 'eu', 'en'] | True |
RainBirdSensor.state | (self) | Return the state of the sensor. | Return the state of the sensor. | def state(self):
"""Return the state of the sensor."""
return self._state | [
"def",
"state",
"(",
"self",
")",
":",
"return",
"self",
".",
"_state"
] | [
43,
4
] | [
45,
26
] | python | en | ['en', 'en', 'en'] | True |
RainBirdSensor.update | (self) | Get the latest data and updates the states. | Get the latest data and updates the states. | def update(self):
"""Get the latest data and updates the states."""
_LOGGER.debug("Updating sensor: %s", self._name)
if self._sensor_type == SENSOR_TYPE_RAINSENSOR:
self._state = self._controller.get_rain_sensor_state()
elif self._sensor_type == SENSOR_TYPE_RAINDELAY:
self._state = self._controller.get_rain_delay() | [
"def",
"update",
"(",
"self",
")",
":",
"_LOGGER",
".",
"debug",
"(",
"\"Updating sensor: %s\"",
",",
"self",
".",
"_name",
")",
"if",
"self",
".",
"_sensor_type",
"==",
"SENSOR_TYPE_RAINSENSOR",
":",
"self",
".",
"_state",
"=",
"self",
".",
"_controller",
".",
"get_rain_sensor_state",
"(",
")",
"elif",
"self",
".",
"_sensor_type",
"==",
"SENSOR_TYPE_RAINDELAY",
":",
"self",
".",
"_state",
"=",
"self",
".",
"_controller",
".",
"get_rain_delay",
"(",
")"
] | [
47,
4
] | [
53,
59
] | python | en | ['en', 'en', 'en'] | True |
RainBirdSensor.name | (self) | Return the name of this camera. | Return the name of this camera. | def name(self):
"""Return the name of this camera."""
return self._name | [
"def",
"name",
"(",
"self",
")",
":",
"return",
"self",
".",
"_name"
] | [
56,
4
] | [
58,
25
] | python | en | ['en', 'en', 'en'] | True |
RainBirdSensor.unit_of_measurement | (self) | Return the units of measurement. | Return the units of measurement. | def unit_of_measurement(self):
"""Return the units of measurement."""
return self._unit_of_measurement | [
"def",
"unit_of_measurement",
"(",
"self",
")",
":",
"return",
"self",
".",
"_unit_of_measurement"
] | [
61,
4
] | [
63,
40
] | python | en | ['en', 'bg', 'en'] | True |
RainBirdSensor.icon | (self) | Return icon. | Return icon. | def icon(self):
"""Return icon."""
return self._icon | [
"def",
"icon",
"(",
"self",
")",
":",
"return",
"self",
".",
"_icon"
] | [
66,
4
] | [
68,
25
] | python | en | ['en', 'la', 'en'] | False |
async_setup | (hass, config) | Set up the Broadlink integration. | Set up the Broadlink integration. | async def async_setup(hass, config):
"""Set up the Broadlink integration."""
hass.data[DOMAIN] = BroadlinkData()
return True | [
"async",
"def",
"async_setup",
"(",
"hass",
",",
"config",
")",
":",
"hass",
".",
"data",
"[",
"DOMAIN",
"]",
"=",
"BroadlinkData",
"(",
")",
"return",
"True"
] | [
15,
0
] | [
18,
15
] | python | en | ['en', 'da', 'en'] | True |
async_setup_entry | (hass, entry) | Set up a Broadlink device from a config entry. | Set up a Broadlink device from a config entry. | async def async_setup_entry(hass, entry):
"""Set up a Broadlink device from a config entry."""
device = BroadlinkDevice(hass, entry)
return await device.async_setup() | [
"async",
"def",
"async_setup_entry",
"(",
"hass",
",",
"entry",
")",
":",
"device",
"=",
"BroadlinkDevice",
"(",
"hass",
",",
"entry",
")",
"return",
"await",
"device",
".",
"async_setup",
"(",
")"
] | [
21,
0
] | [
24,
37
] | python | en | ['en', 'en', 'en'] | True |
async_unload_entry | (hass, entry) | Unload a config entry. | Unload a config entry. | async def async_unload_entry(hass, entry):
"""Unload a config entry."""
device = hass.data[DOMAIN].devices.pop(entry.entry_id)
return await device.async_unload() | [
"async",
"def",
"async_unload_entry",
"(",
"hass",
",",
"entry",
")",
":",
"device",
"=",
"hass",
".",
"data",
"[",
"DOMAIN",
"]",
".",
"devices",
".",
"pop",
"(",
"entry",
".",
"entry_id",
")",
"return",
"await",
"device",
".",
"async_unload",
"(",
")"
] | [
27,
0
] | [
30,
38
] | python | en | ['en', 'es', 'en'] | True |
BondEntity.__init__ | (
self, hub: BondHub, device: BondDevice, sub_device: Optional[str] = None
) | Initialize entity with API and device info. | Initialize entity with API and device info. | def __init__(
self, hub: BondHub, device: BondDevice, sub_device: Optional[str] = None
):
"""Initialize entity with API and device info."""
self._hub = hub
self._device = device
self._sub_device = sub_device
self._available = True | [
"def",
"__init__",
"(",
"self",
",",
"hub",
":",
"BondHub",
",",
"device",
":",
"BondDevice",
",",
"sub_device",
":",
"Optional",
"[",
"str",
"]",
"=",
"None",
")",
":",
"self",
".",
"_hub",
"=",
"hub",
"self",
".",
"_device",
"=",
"device",
"self",
".",
"_sub_device",
"=",
"sub_device",
"self",
".",
"_available",
"=",
"True"
] | [
20,
4
] | [
27,
30
] | python | en | ['en', 'en', 'en'] | True |
BondEntity.unique_id | (self) | Get unique ID for the entity. | Get unique ID for the entity. | def unique_id(self) -> Optional[str]:
"""Get unique ID for the entity."""
hub_id = self._hub.bond_id
device_id = self._device.device_id
sub_device_id: str = f"_{self._sub_device}" if self._sub_device else ""
return f"{hub_id}_{device_id}{sub_device_id}" | [
"def",
"unique_id",
"(",
"self",
")",
"->",
"Optional",
"[",
"str",
"]",
":",
"hub_id",
"=",
"self",
".",
"_hub",
".",
"bond_id",
"device_id",
"=",
"self",
".",
"_device",
".",
"device_id",
"sub_device_id",
":",
"str",
"=",
"f\"_{self._sub_device}\"",
"if",
"self",
".",
"_sub_device",
"else",
"\"\"",
"return",
"f\"{hub_id}_{device_id}{sub_device_id}\""
] | [
30,
4
] | [
35,
53
] | python | en | ['en', 'en', 'en'] | True |
BondEntity.name | (self) | Get entity name. | Get entity name. | def name(self) -> Optional[str]:
"""Get entity name."""
return self._device.name | [
"def",
"name",
"(",
"self",
")",
"->",
"Optional",
"[",
"str",
"]",
":",
"return",
"self",
".",
"_device",
".",
"name"
] | [
38,
4
] | [
40,
32
] | python | en | ['en', 'en', 'en'] | True |
BondEntity.device_info | (self) | Get a an HA device representing this Bond controlled device. | Get a an HA device representing this Bond controlled device. | def device_info(self) -> Optional[Dict[str, Any]]:
"""Get a an HA device representing this Bond controlled device."""
return {
ATTR_NAME: self.name,
"identifiers": {(DOMAIN, self._device.device_id)},
"via_device": (DOMAIN, self._hub.bond_id),
} | [
"def",
"device_info",
"(",
"self",
")",
"->",
"Optional",
"[",
"Dict",
"[",
"str",
",",
"Any",
"]",
"]",
":",
"return",
"{",
"ATTR_NAME",
":",
"self",
".",
"name",
",",
"\"identifiers\"",
":",
"{",
"(",
"DOMAIN",
",",
"self",
".",
"_device",
".",
"device_id",
")",
"}",
",",
"\"via_device\"",
":",
"(",
"DOMAIN",
",",
"self",
".",
"_hub",
".",
"bond_id",
")",
",",
"}"
] | [
43,
4
] | [
49,
9
] | python | en | ['en', 'en', 'en'] | True |
BondEntity.assumed_state | (self) | Let HA know this entity relies on an assumed state tracked by Bond. | Let HA know this entity relies on an assumed state tracked by Bond. | def assumed_state(self) -> bool:
"""Let HA know this entity relies on an assumed state tracked by Bond."""
return self._hub.is_bridge and not self._device.trust_state | [
"def",
"assumed_state",
"(",
"self",
")",
"->",
"bool",
":",
"return",
"self",
".",
"_hub",
".",
"is_bridge",
"and",
"not",
"self",
".",
"_device",
".",
"trust_state"
] | [
52,
4
] | [
54,
67
] | python | en | ['en', 'en', 'en'] | True |
BondEntity.available | (self) | Report availability of this entity based on last API call results. | Report availability of this entity based on last API call results. | def available(self) -> bool:
"""Report availability of this entity based on last API call results."""
return self._available | [
"def",
"available",
"(",
"self",
")",
"->",
"bool",
":",
"return",
"self",
".",
"_available"
] | [
57,
4
] | [
59,
30
] | python | en | ['en', 'en', 'en'] | True |
BondEntity.async_update | (self) | Fetch assumed state of the cover from the hub using API. | Fetch assumed state of the cover from the hub using API. | async def async_update(self):
"""Fetch assumed state of the cover from the hub using API."""
try:
state: dict = await self._hub.bond.device_state(self._device.device_id)
except (ClientError, AsyncIOTimeoutError, OSError) as error:
if self._available:
_LOGGER.warning(
"Entity %s has become unavailable", self.entity_id, exc_info=error
)
self._available = False
else:
_LOGGER.debug("Device state for %s is:\n%s", self.entity_id, state)
if not self._available:
_LOGGER.info("Entity %s has come back", self.entity_id)
self._available = True
self._apply_state(state) | [
"async",
"def",
"async_update",
"(",
"self",
")",
":",
"try",
":",
"state",
":",
"dict",
"=",
"await",
"self",
".",
"_hub",
".",
"bond",
".",
"device_state",
"(",
"self",
".",
"_device",
".",
"device_id",
")",
"except",
"(",
"ClientError",
",",
"AsyncIOTimeoutError",
",",
"OSError",
")",
"as",
"error",
":",
"if",
"self",
".",
"_available",
":",
"_LOGGER",
".",
"warning",
"(",
"\"Entity %s has become unavailable\"",
",",
"self",
".",
"entity_id",
",",
"exc_info",
"=",
"error",
")",
"self",
".",
"_available",
"=",
"False",
"else",
":",
"_LOGGER",
".",
"debug",
"(",
"\"Device state for %s is:\\n%s\"",
",",
"self",
".",
"entity_id",
",",
"state",
")",
"if",
"not",
"self",
".",
"_available",
":",
"_LOGGER",
".",
"info",
"(",
"\"Entity %s has come back\"",
",",
"self",
".",
"entity_id",
")",
"self",
".",
"_available",
"=",
"True",
"self",
".",
"_apply_state",
"(",
"state",
")"
] | [
61,
4
] | [
76,
36
] | python | en | ['en', 'en', 'en'] | True |
async_setup_entry | (hass, config_entry, async_add_entities) | Set up the August sensors. | Set up the August sensors. | async def async_setup_entry(hass, config_entry, async_add_entities):
"""Set up the August sensors."""
powerwall_data = hass.data[DOMAIN][config_entry.entry_id]
_LOGGER.debug("Powerwall_data: %s", powerwall_data)
coordinator = powerwall_data[POWERWALL_COORDINATOR]
site_info = powerwall_data[POWERWALL_API_SITE_INFO]
device_type = powerwall_data[POWERWALL_API_DEVICE_TYPE]
status = powerwall_data[POWERWALL_API_STATUS]
powerwalls_serial_numbers = powerwall_data[POWERWALL_API_SERIAL_NUMBERS]
entities = []
for meter in MeterType:
entities.append(
PowerWallEnergySensor(
meter,
coordinator,
site_info,
status,
device_type,
powerwalls_serial_numbers,
)
)
entities.append(
PowerWallChargeSensor(
coordinator, site_info, status, device_type, powerwalls_serial_numbers
)
)
async_add_entities(entities, True) | [
"async",
"def",
"async_setup_entry",
"(",
"hass",
",",
"config_entry",
",",
"async_add_entities",
")",
":",
"powerwall_data",
"=",
"hass",
".",
"data",
"[",
"DOMAIN",
"]",
"[",
"config_entry",
".",
"entry_id",
"]",
"_LOGGER",
".",
"debug",
"(",
"\"Powerwall_data: %s\"",
",",
"powerwall_data",
")",
"coordinator",
"=",
"powerwall_data",
"[",
"POWERWALL_COORDINATOR",
"]",
"site_info",
"=",
"powerwall_data",
"[",
"POWERWALL_API_SITE_INFO",
"]",
"device_type",
"=",
"powerwall_data",
"[",
"POWERWALL_API_DEVICE_TYPE",
"]",
"status",
"=",
"powerwall_data",
"[",
"POWERWALL_API_STATUS",
"]",
"powerwalls_serial_numbers",
"=",
"powerwall_data",
"[",
"POWERWALL_API_SERIAL_NUMBERS",
"]",
"entities",
"=",
"[",
"]",
"for",
"meter",
"in",
"MeterType",
":",
"entities",
".",
"append",
"(",
"PowerWallEnergySensor",
"(",
"meter",
",",
"coordinator",
",",
"site_info",
",",
"status",
",",
"device_type",
",",
"powerwalls_serial_numbers",
",",
")",
")",
"entities",
".",
"append",
"(",
"PowerWallChargeSensor",
"(",
"coordinator",
",",
"site_info",
",",
"status",
",",
"device_type",
",",
"powerwalls_serial_numbers",
")",
")",
"async_add_entities",
"(",
"entities",
",",
"True",
")"
] | [
28,
0
] | [
58,
38
] | python | en | ['en', 'en', 'en'] | True |
PowerWallChargeSensor.unit_of_measurement | (self) | Return the unit of measurement. | Return the unit of measurement. | def unit_of_measurement(self):
"""Return the unit of measurement."""
return PERCENTAGE | [
"def",
"unit_of_measurement",
"(",
"self",
")",
":",
"return",
"PERCENTAGE"
] | [
65,
4
] | [
67,
25
] | python | en | ['en', 'la', 'en'] | True |
PowerWallChargeSensor.name | (self) | Device Name. | Device Name. | def name(self):
"""Device Name."""
return "Powerwall Charge" | [
"def",
"name",
"(",
"self",
")",
":",
"return",
"\"Powerwall Charge\""
] | [
70,
4
] | [
72,
33
] | python | en | ['en', 'en', 'en'] | False |
PowerWallChargeSensor.device_class | (self) | Device Class. | Device Class. | def device_class(self):
"""Device Class."""
return DEVICE_CLASS_BATTERY | [
"def",
"device_class",
"(",
"self",
")",
":",
"return",
"DEVICE_CLASS_BATTERY"
] | [
75,
4
] | [
77,
35
] | python | en | ['en', 'zh', 'en'] | False |
PowerWallChargeSensor.unique_id | (self) | Device Uniqueid. | Device Uniqueid. | def unique_id(self):
"""Device Uniqueid."""
return f"{self.base_unique_id}_charge" | [
"def",
"unique_id",
"(",
"self",
")",
":",
"return",
"f\"{self.base_unique_id}_charge\""
] | [
80,
4
] | [
82,
46
] | python | fr | ['fr', 'fr', 'en'] | False |
PowerWallChargeSensor.state | (self) | Get the current value in percentage. | Get the current value in percentage. | def state(self):
"""Get the current value in percentage."""
return round(self.coordinator.data[POWERWALL_API_CHARGE]) | [
"def",
"state",
"(",
"self",
")",
":",
"return",
"round",
"(",
"self",
".",
"coordinator",
".",
"data",
"[",
"POWERWALL_API_CHARGE",
"]",
")"
] | [
85,
4
] | [
87,
65
] | python | en | ['en', 'en', 'en'] | True |
PowerWallEnergySensor.__init__ | (
self,
meter: MeterType,
coordinator,
site_info,
status,
device_type,
powerwalls_serial_numbers,
) | Initialize the sensor. | Initialize the sensor. | def __init__(
self,
meter: MeterType,
coordinator,
site_info,
status,
device_type,
powerwalls_serial_numbers,
):
"""Initialize the sensor."""
super().__init__(
coordinator, site_info, status, device_type, powerwalls_serial_numbers
)
self._meter = meter | [
"def",
"__init__",
"(",
"self",
",",
"meter",
":",
"MeterType",
",",
"coordinator",
",",
"site_info",
",",
"status",
",",
"device_type",
",",
"powerwalls_serial_numbers",
",",
")",
":",
"super",
"(",
")",
".",
"__init__",
"(",
"coordinator",
",",
"site_info",
",",
"status",
",",
"device_type",
",",
"powerwalls_serial_numbers",
")",
"self",
".",
"_meter",
"=",
"meter"
] | [
93,
4
] | [
106,
27
] | python | en | ['en', 'en', 'en'] | True |
PowerWallEnergySensor.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 ENERGY_KILO_WATT | [
"def",
"unit_of_measurement",
"(",
"self",
")",
":",
"return",
"ENERGY_KILO_WATT"
] | [
109,
4
] | [
111,
31
] | python | en | ['en', 'la', 'en'] | True |
PowerWallEnergySensor.name | (self) | Device Name. | Device Name. | def name(self):
"""Device Name."""
return f"Powerwall {self._meter.value.title()} Now" | [
"def",
"name",
"(",
"self",
")",
":",
"return",
"f\"Powerwall {self._meter.value.title()} Now\""
] | [
114,
4
] | [
116,
59
] | python | en | ['en', 'en', 'en'] | False |
PowerWallEnergySensor.device_class | (self) | Device Class. | Device Class. | def device_class(self):
"""Device Class."""
return DEVICE_CLASS_POWER | [
"def",
"device_class",
"(",
"self",
")",
":",
"return",
"DEVICE_CLASS_POWER"
] | [
119,
4
] | [
121,
33
] | python | en | ['en', 'zh', 'en'] | False |
PowerWallEnergySensor.unique_id | (self) | Device Uniqueid. | Device Uniqueid. | def unique_id(self):
"""Device Uniqueid."""
return f"{self.base_unique_id}_{self._meter.value}_instant_power" | [
"def",
"unique_id",
"(",
"self",
")",
":",
"return",
"f\"{self.base_unique_id}_{self._meter.value}_instant_power\""
] | [
124,
4
] | [
126,
73
] | python | fr | ['fr', 'fr', 'en'] | False |
PowerWallEnergySensor.state | (self) | Get the current value in kW. | Get the current value in kW. | def state(self):
"""Get the current value in kW."""
return (
self.coordinator.data[POWERWALL_API_METERS]
.get_meter(self._meter)
.get_power(precision=3)
) | [
"def",
"state",
"(",
"self",
")",
":",
"return",
"(",
"self",
".",
"coordinator",
".",
"data",
"[",
"POWERWALL_API_METERS",
"]",
".",
"get_meter",
"(",
"self",
".",
"_meter",
")",
".",
"get_power",
"(",
"precision",
"=",
"3",
")",
")"
] | [
129,
4
] | [
135,
9
] | python | en | ['en', 'en', 'en'] | True |
PowerWallEnergySensor.device_state_attributes | (self) | Return the device specific state attributes. | Return the device specific state attributes. | def device_state_attributes(self):
"""Return the device specific state attributes."""
meter = self.coordinator.data[POWERWALL_API_METERS].get_meter(self._meter)
return {
ATTR_FREQUENCY: round(meter.frequency, 1),
ATTR_ENERGY_EXPORTED: meter.get_energy_exported(),
ATTR_ENERGY_IMPORTED: meter.get_energy_imported(),
ATTR_INSTANT_AVERAGE_VOLTAGE: round(meter.avarage_voltage, 1),
ATTR_IS_ACTIVE: meter.is_active(),
} | [
"def",
"device_state_attributes",
"(",
"self",
")",
":",
"meter",
"=",
"self",
".",
"coordinator",
".",
"data",
"[",
"POWERWALL_API_METERS",
"]",
".",
"get_meter",
"(",
"self",
".",
"_meter",
")",
"return",
"{",
"ATTR_FREQUENCY",
":",
"round",
"(",
"meter",
".",
"frequency",
",",
"1",
")",
",",
"ATTR_ENERGY_EXPORTED",
":",
"meter",
".",
"get_energy_exported",
"(",
")",
",",
"ATTR_ENERGY_IMPORTED",
":",
"meter",
".",
"get_energy_imported",
"(",
")",
",",
"ATTR_INSTANT_AVERAGE_VOLTAGE",
":",
"round",
"(",
"meter",
".",
"avarage_voltage",
",",
"1",
")",
",",
"ATTR_IS_ACTIVE",
":",
"meter",
".",
"is_active",
"(",
")",
",",
"}"
] | [
138,
4
] | [
147,
9
] | python | en | ['en', 'en', 'en'] | True |
test_create_covers | (hass) | Test creation of covers. | Test creation of covers. | async def test_create_covers(hass):
"""Test creation of covers."""
await async_init_integration(hass)
state = hass.states.get("cover.large_garage_door")
assert state.state == STATE_CLOSED
expected_attributes = {
"device_class": "garage",
"friendly_name": "Large Garage Door",
"supported_features": 3,
}
# Only test for a subset of attributes in case
# HA changes the implementation and a new one appears
assert all(
state.attributes[key] == expected_attributes[key] for key in expected_attributes
)
state = hass.states.get("cover.small_garage_door")
assert state.state == STATE_CLOSED
expected_attributes = {
"device_class": "garage",
"friendly_name": "Small Garage Door",
"supported_features": 3,
}
# Only test for a subset of attributes in case
# HA changes the implementation and a new one appears
assert all(
state.attributes[key] == expected_attributes[key] for key in expected_attributes
)
state = hass.states.get("cover.gate")
assert state.state == STATE_CLOSED
expected_attributes = {
"device_class": "gate",
"friendly_name": "Gate",
"supported_features": 3,
}
# Only test for a subset of attributes in case
# HA changes the implementation and a new one appears
assert all(
state.attributes[key] == expected_attributes[key] for key in expected_attributes
) | [
"async",
"def",
"test_create_covers",
"(",
"hass",
")",
":",
"await",
"async_init_integration",
"(",
"hass",
")",
"state",
"=",
"hass",
".",
"states",
".",
"get",
"(",
"\"cover.large_garage_door\"",
")",
"assert",
"state",
".",
"state",
"==",
"STATE_CLOSED",
"expected_attributes",
"=",
"{",
"\"device_class\"",
":",
"\"garage\"",
",",
"\"friendly_name\"",
":",
"\"Large Garage Door\"",
",",
"\"supported_features\"",
":",
"3",
",",
"}",
"# Only test for a subset of attributes in case",
"# HA changes the implementation and a new one appears",
"assert",
"all",
"(",
"state",
".",
"attributes",
"[",
"key",
"]",
"==",
"expected_attributes",
"[",
"key",
"]",
"for",
"key",
"in",
"expected_attributes",
")",
"state",
"=",
"hass",
".",
"states",
".",
"get",
"(",
"\"cover.small_garage_door\"",
")",
"assert",
"state",
".",
"state",
"==",
"STATE_CLOSED",
"expected_attributes",
"=",
"{",
"\"device_class\"",
":",
"\"garage\"",
",",
"\"friendly_name\"",
":",
"\"Small Garage Door\"",
",",
"\"supported_features\"",
":",
"3",
",",
"}",
"# Only test for a subset of attributes in case",
"# HA changes the implementation and a new one appears",
"assert",
"all",
"(",
"state",
".",
"attributes",
"[",
"key",
"]",
"==",
"expected_attributes",
"[",
"key",
"]",
"for",
"key",
"in",
"expected_attributes",
")",
"state",
"=",
"hass",
".",
"states",
".",
"get",
"(",
"\"cover.gate\"",
")",
"assert",
"state",
".",
"state",
"==",
"STATE_CLOSED",
"expected_attributes",
"=",
"{",
"\"device_class\"",
":",
"\"gate\"",
",",
"\"friendly_name\"",
":",
"\"Gate\"",
",",
"\"supported_features\"",
":",
"3",
",",
"}",
"# Only test for a subset of attributes in case",
"# HA changes the implementation and a new one appears",
"assert",
"all",
"(",
"state",
".",
"attributes",
"[",
"key",
"]",
"==",
"expected_attributes",
"[",
"key",
"]",
"for",
"key",
"in",
"expected_attributes",
")"
] | [
7,
0
] | [
49,
5
] | python | en | ['en', 'en', 'en'] | True |
setup_push_receiver | (hass, aioclient_mock) | Fixture that sets up a mocked push receiver. | Fixture that sets up a mocked push receiver. | async def setup_push_receiver(hass, aioclient_mock):
"""Fixture that sets up a mocked push receiver."""
push_url = "https://mobile-push.home-assistant.dev/push"
from datetime import datetime, timedelta
now = datetime.now() + timedelta(hours=24)
iso_time = now.strftime("%Y-%m-%dT%H:%M:%SZ")
aioclient_mock.post(
push_url,
json={
"rateLimits": {
"attempts": 1,
"successful": 1,
"errors": 0,
"total": 1,
"maximum": 150,
"remaining": 149,
"resetsAt": iso_time,
}
},
)
entry = MockConfigEntry(
connection_class="cloud_push",
data={
"app_data": {"push_token": "PUSH_TOKEN", "push_url": push_url},
"app_id": "io.homeassistant.mobile_app",
"app_name": "mobile_app tests",
"app_version": "1.0",
"device_id": "4d5e6f",
"device_name": "Test",
"manufacturer": "Home Assistant",
"model": "mobile_app",
"os_name": "Linux",
"os_version": "5.0.6",
"secret": "123abc",
"supports_encryption": False,
"user_id": "1a2b3c",
"webhook_id": "webhook_id",
},
domain=DOMAIN,
source="registration",
title="mobile_app test entry",
version=1,
)
entry.add_to_hass(hass)
await async_setup_component(hass, DOMAIN, {DOMAIN: {}})
await hass.async_block_till_done()
loaded_late_entry = MockConfigEntry(
connection_class="cloud_push",
data={
"app_data": {"push_token": "PUSH_TOKEN2", "push_url": f"{push_url}2"},
"app_id": "io.homeassistant.mobile_app",
"app_name": "mobile_app tests",
"app_version": "1.0",
"device_id": "4d5e6f2",
"device_name": "Loaded Late",
"manufacturer": "Home Assistant",
"model": "mobile_app",
"os_name": "Linux",
"os_version": "5.0.6",
"secret": "123abc2",
"supports_encryption": False,
"user_id": "1a2b3c2",
"webhook_id": "webhook_id_2",
},
domain=DOMAIN,
source="registration",
title="mobile_app 2 test entry",
version=1,
)
loaded_late_entry.add_to_hass(hass)
assert await hass.config_entries.async_setup(loaded_late_entry.entry_id)
await hass.async_block_till_done()
assert hass.services.has_service("notify", "mobile_app_loaded_late")
assert await hass.config_entries.async_remove(loaded_late_entry.entry_id)
await hass.async_block_till_done()
assert hass.services.has_service("notify", "mobile_app_test")
assert not hass.services.has_service("notify", "mobile_app_loaded_late")
loaded_late_entry.add_to_hass(hass)
assert await hass.config_entries.async_setup(loaded_late_entry.entry_id)
await hass.async_block_till_done()
assert hass.services.has_service("notify", "mobile_app_test")
assert hass.services.has_service("notify", "mobile_app_loaded_late") | [
"async",
"def",
"setup_push_receiver",
"(",
"hass",
",",
"aioclient_mock",
")",
":",
"push_url",
"=",
"\"https://mobile-push.home-assistant.dev/push\"",
"from",
"datetime",
"import",
"datetime",
",",
"timedelta",
"now",
"=",
"datetime",
".",
"now",
"(",
")",
"+",
"timedelta",
"(",
"hours",
"=",
"24",
")",
"iso_time",
"=",
"now",
".",
"strftime",
"(",
"\"%Y-%m-%dT%H:%M:%SZ\"",
")",
"aioclient_mock",
".",
"post",
"(",
"push_url",
",",
"json",
"=",
"{",
"\"rateLimits\"",
":",
"{",
"\"attempts\"",
":",
"1",
",",
"\"successful\"",
":",
"1",
",",
"\"errors\"",
":",
"0",
",",
"\"total\"",
":",
"1",
",",
"\"maximum\"",
":",
"150",
",",
"\"remaining\"",
":",
"149",
",",
"\"resetsAt\"",
":",
"iso_time",
",",
"}",
"}",
",",
")",
"entry",
"=",
"MockConfigEntry",
"(",
"connection_class",
"=",
"\"cloud_push\"",
",",
"data",
"=",
"{",
"\"app_data\"",
":",
"{",
"\"push_token\"",
":",
"\"PUSH_TOKEN\"",
",",
"\"push_url\"",
":",
"push_url",
"}",
",",
"\"app_id\"",
":",
"\"io.homeassistant.mobile_app\"",
",",
"\"app_name\"",
":",
"\"mobile_app tests\"",
",",
"\"app_version\"",
":",
"\"1.0\"",
",",
"\"device_id\"",
":",
"\"4d5e6f\"",
",",
"\"device_name\"",
":",
"\"Test\"",
",",
"\"manufacturer\"",
":",
"\"Home Assistant\"",
",",
"\"model\"",
":",
"\"mobile_app\"",
",",
"\"os_name\"",
":",
"\"Linux\"",
",",
"\"os_version\"",
":",
"\"5.0.6\"",
",",
"\"secret\"",
":",
"\"123abc\"",
",",
"\"supports_encryption\"",
":",
"False",
",",
"\"user_id\"",
":",
"\"1a2b3c\"",
",",
"\"webhook_id\"",
":",
"\"webhook_id\"",
",",
"}",
",",
"domain",
"=",
"DOMAIN",
",",
"source",
"=",
"\"registration\"",
",",
"title",
"=",
"\"mobile_app test entry\"",
",",
"version",
"=",
"1",
",",
")",
"entry",
".",
"add_to_hass",
"(",
"hass",
")",
"await",
"async_setup_component",
"(",
"hass",
",",
"DOMAIN",
",",
"{",
"DOMAIN",
":",
"{",
"}",
"}",
")",
"await",
"hass",
".",
"async_block_till_done",
"(",
")",
"loaded_late_entry",
"=",
"MockConfigEntry",
"(",
"connection_class",
"=",
"\"cloud_push\"",
",",
"data",
"=",
"{",
"\"app_data\"",
":",
"{",
"\"push_token\"",
":",
"\"PUSH_TOKEN2\"",
",",
"\"push_url\"",
":",
"f\"{push_url}2\"",
"}",
",",
"\"app_id\"",
":",
"\"io.homeassistant.mobile_app\"",
",",
"\"app_name\"",
":",
"\"mobile_app tests\"",
",",
"\"app_version\"",
":",
"\"1.0\"",
",",
"\"device_id\"",
":",
"\"4d5e6f2\"",
",",
"\"device_name\"",
":",
"\"Loaded Late\"",
",",
"\"manufacturer\"",
":",
"\"Home Assistant\"",
",",
"\"model\"",
":",
"\"mobile_app\"",
",",
"\"os_name\"",
":",
"\"Linux\"",
",",
"\"os_version\"",
":",
"\"5.0.6\"",
",",
"\"secret\"",
":",
"\"123abc2\"",
",",
"\"supports_encryption\"",
":",
"False",
",",
"\"user_id\"",
":",
"\"1a2b3c2\"",
",",
"\"webhook_id\"",
":",
"\"webhook_id_2\"",
",",
"}",
",",
"domain",
"=",
"DOMAIN",
",",
"source",
"=",
"\"registration\"",
",",
"title",
"=",
"\"mobile_app 2 test entry\"",
",",
"version",
"=",
"1",
",",
")",
"loaded_late_entry",
".",
"add_to_hass",
"(",
"hass",
")",
"assert",
"await",
"hass",
".",
"config_entries",
".",
"async_setup",
"(",
"loaded_late_entry",
".",
"entry_id",
")",
"await",
"hass",
".",
"async_block_till_done",
"(",
")",
"assert",
"hass",
".",
"services",
".",
"has_service",
"(",
"\"notify\"",
",",
"\"mobile_app_loaded_late\"",
")",
"assert",
"await",
"hass",
".",
"config_entries",
".",
"async_remove",
"(",
"loaded_late_entry",
".",
"entry_id",
")",
"await",
"hass",
".",
"async_block_till_done",
"(",
")",
"assert",
"hass",
".",
"services",
".",
"has_service",
"(",
"\"notify\"",
",",
"\"mobile_app_test\"",
")",
"assert",
"not",
"hass",
".",
"services",
".",
"has_service",
"(",
"\"notify\"",
",",
"\"mobile_app_loaded_late\"",
")",
"loaded_late_entry",
".",
"add_to_hass",
"(",
"hass",
")",
"assert",
"await",
"hass",
".",
"config_entries",
".",
"async_setup",
"(",
"loaded_late_entry",
".",
"entry_id",
")",
"await",
"hass",
".",
"async_block_till_done",
"(",
")",
"assert",
"hass",
".",
"services",
".",
"has_service",
"(",
"\"notify\"",
",",
"\"mobile_app_test\"",
")",
"assert",
"hass",
".",
"services",
".",
"has_service",
"(",
"\"notify\"",
",",
"\"mobile_app_loaded_late\"",
")"
] | [
11,
0
] | [
103,
72
] | python | en | ['en', 'en', 'en'] | True |
test_notify_works | (hass, aioclient_mock, setup_push_receiver) | Test notify works. | Test notify works. | async def test_notify_works(hass, aioclient_mock, setup_push_receiver):
"""Test notify works."""
assert hass.services.has_service("notify", "mobile_app_test") is True
assert await hass.services.async_call(
"notify", "mobile_app_test", {"message": "Hello world"}, blocking=True
)
assert len(aioclient_mock.mock_calls) == 1
call = aioclient_mock.mock_calls
call_json = call[0][2]
assert call_json["push_token"] == "PUSH_TOKEN"
assert call_json["message"] == "Hello world"
assert call_json["registration_info"]["app_id"] == "io.homeassistant.mobile_app"
assert call_json["registration_info"]["app_version"] == "1.0" | [
"async",
"def",
"test_notify_works",
"(",
"hass",
",",
"aioclient_mock",
",",
"setup_push_receiver",
")",
":",
"assert",
"hass",
".",
"services",
".",
"has_service",
"(",
"\"notify\"",
",",
"\"mobile_app_test\"",
")",
"is",
"True",
"assert",
"await",
"hass",
".",
"services",
".",
"async_call",
"(",
"\"notify\"",
",",
"\"mobile_app_test\"",
",",
"{",
"\"message\"",
":",
"\"Hello world\"",
"}",
",",
"blocking",
"=",
"True",
")",
"assert",
"len",
"(",
"aioclient_mock",
".",
"mock_calls",
")",
"==",
"1",
"call",
"=",
"aioclient_mock",
".",
"mock_calls",
"call_json",
"=",
"call",
"[",
"0",
"]",
"[",
"2",
"]",
"assert",
"call_json",
"[",
"\"push_token\"",
"]",
"==",
"\"PUSH_TOKEN\"",
"assert",
"call_json",
"[",
"\"message\"",
"]",
"==",
"\"Hello world\"",
"assert",
"call_json",
"[",
"\"registration_info\"",
"]",
"[",
"\"app_id\"",
"]",
"==",
"\"io.homeassistant.mobile_app\"",
"assert",
"call_json",
"[",
"\"registration_info\"",
"]",
"[",
"\"app_version\"",
"]",
"==",
"\"1.0\""
] | [
106,
0
] | [
121,
65
] | python | en | ['en', 'pl', 'en'] | True |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.