Search is not available for this dataset
identifier
stringlengths 1
155
| parameters
stringlengths 2
6.09k
| docstring
stringlengths 11
63.4k
| docstring_summary
stringlengths 0
63.4k
| function
stringlengths 29
99.8k
| function_tokens
sequence | start_point
sequence | end_point
sequence | language
stringclasses 1
value | docstring_language
stringlengths 2
7
| docstring_language_predictions
stringlengths 18
23
| is_langid_reliable
stringclasses 2
values |
---|---|---|---|---|---|---|---|---|---|---|---|
NotionSensor.state | (self) | Return the state of the sensor. | Return the state of the sensor. | def state(self) -> str:
"""Return the state of the sensor."""
return self._state | [
"def",
"state",
"(",
"self",
")",
"->",
"str",
":",
"return",
"self",
".",
"_state"
] | [
69,
4
] | [
71,
26
] | python | en | ['en', 'en', 'en'] | True |
NotionSensor.unit_of_measurement | (self) | Return the unit of measurement. | Return the unit of measurement. | def unit_of_measurement(self) -> str:
"""Return the unit of measurement."""
return self._unit | [
"def",
"unit_of_measurement",
"(",
"self",
")",
"->",
"str",
":",
"return",
"self",
".",
"_unit"
] | [
74,
4
] | [
76,
25
] | python | en | ['en', 'la', 'en'] | True |
NotionSensor._async_update_from_latest_data | (self) | Fetch new state data for the sensor. | Fetch new state data for the sensor. | def _async_update_from_latest_data(self) -> None:
"""Fetch new state data for the sensor."""
task = self.coordinator.data["tasks"][self._task_id]
if task["task_type"] == SENSOR_TEMPERATURE:
self._state = round(float(task["status"]["value"]), 1)
else:
_LOGGER.error(
"Unknown task type: %s: %s",
self.coordinator.data["sensors"][self._sensor_id],
task["task_type"],
) | [
"def",
"_async_update_from_latest_data",
"(",
"self",
")",
"->",
"None",
":",
"task",
"=",
"self",
".",
"coordinator",
".",
"data",
"[",
"\"tasks\"",
"]",
"[",
"self",
".",
"_task_id",
"]",
"if",
"task",
"[",
"\"task_type\"",
"]",
"==",
"SENSOR_TEMPERATURE",
":",
"self",
".",
"_state",
"=",
"round",
"(",
"float",
"(",
"task",
"[",
"\"status\"",
"]",
"[",
"\"value\"",
"]",
")",
",",
"1",
")",
"else",
":",
"_LOGGER",
".",
"error",
"(",
"\"Unknown task type: %s: %s\"",
",",
"self",
".",
"coordinator",
".",
"data",
"[",
"\"sensors\"",
"]",
"[",
"self",
".",
"_sensor_id",
"]",
",",
"task",
"[",
"\"task_type\"",
"]",
",",
")"
] | [
79,
4
] | [
90,
13
] | python | en | ['en', 'en', 'en'] | True |
async_setup_entry | (hass, config_entry, async_add_entities) | Set up Z-Wave binary sensors from Config Entry. | Set up Z-Wave binary sensors from Config Entry. | async def async_setup_entry(hass, config_entry, async_add_entities):
"""Set up Z-Wave binary sensors from Config Entry."""
@callback
def async_add_binary_sensor(binary_sensor):
"""Add Z-Wave binary sensor."""
async_add_entities([binary_sensor])
async_dispatcher_connect(hass, "zwave_new_binary_sensor", async_add_binary_sensor) | [
"async",
"def",
"async_setup_entry",
"(",
"hass",
",",
"config_entry",
",",
"async_add_entities",
")",
":",
"@",
"callback",
"def",
"async_add_binary_sensor",
"(",
"binary_sensor",
")",
":",
"\"\"\"Add Z-Wave binary sensor.\"\"\"",
"async_add_entities",
"(",
"[",
"binary_sensor",
"]",
")",
"async_dispatcher_connect",
"(",
"hass",
",",
"\"zwave_new_binary_sensor\"",
",",
"async_add_binary_sensor",
")"
] | [
16,
0
] | [
24,
86
] | python | en | ['en', 'en', 'en'] | True |
get_device | (values, **kwargs) | Create Z-Wave entity device. | Create Z-Wave entity device. | def get_device(values, **kwargs):
"""Create Z-Wave entity device."""
device_mapping = workaround.get_device_mapping(values.primary)
if device_mapping == workaround.WORKAROUND_NO_OFF_EVENT:
return ZWaveTriggerSensor(values, "motion")
if workaround.get_device_component_mapping(values.primary) == DOMAIN:
return ZWaveBinarySensor(values, None)
if values.primary.command_class == COMMAND_CLASS_SENSOR_BINARY:
return ZWaveBinarySensor(values, None)
return None | [
"def",
"get_device",
"(",
"values",
",",
"*",
"*",
"kwargs",
")",
":",
"device_mapping",
"=",
"workaround",
".",
"get_device_mapping",
"(",
"values",
".",
"primary",
")",
"if",
"device_mapping",
"==",
"workaround",
".",
"WORKAROUND_NO_OFF_EVENT",
":",
"return",
"ZWaveTriggerSensor",
"(",
"values",
",",
"\"motion\"",
")",
"if",
"workaround",
".",
"get_device_component_mapping",
"(",
"values",
".",
"primary",
")",
"==",
"DOMAIN",
":",
"return",
"ZWaveBinarySensor",
"(",
"values",
",",
"None",
")",
"if",
"values",
".",
"primary",
".",
"command_class",
"==",
"COMMAND_CLASS_SENSOR_BINARY",
":",
"return",
"ZWaveBinarySensor",
"(",
"values",
",",
"None",
")",
"return",
"None"
] | [
27,
0
] | [
38,
15
] | python | en | ['en', 'pl', 'en'] | True |
ZWaveBinarySensor.__init__ | (self, values, device_class) | Initialize the sensor. | Initialize the sensor. | def __init__(self, values, device_class):
"""Initialize the sensor."""
ZWaveDeviceEntity.__init__(self, values, DOMAIN)
self._sensor_type = device_class
self._state = self.values.primary.data | [
"def",
"__init__",
"(",
"self",
",",
"values",
",",
"device_class",
")",
":",
"ZWaveDeviceEntity",
".",
"__init__",
"(",
"self",
",",
"values",
",",
"DOMAIN",
")",
"self",
".",
"_sensor_type",
"=",
"device_class",
"self",
".",
"_state",
"=",
"self",
".",
"values",
".",
"primary",
".",
"data"
] | [
44,
4
] | [
48,
46
] | python | en | ['en', 'en', 'en'] | True |
ZWaveBinarySensor.update_properties | (self) | Handle data changes for node values. | Handle data changes for node values. | def update_properties(self):
"""Handle data changes for node values."""
self._state = self.values.primary.data | [
"def",
"update_properties",
"(",
"self",
")",
":",
"self",
".",
"_state",
"=",
"self",
".",
"values",
".",
"primary",
".",
"data"
] | [
50,
4
] | [
52,
46
] | python | en | ['fr', 'en', 'en'] | True |
ZWaveBinarySensor.is_on | (self) | Return true if the binary sensor is on. | Return true if the binary sensor is on. | def is_on(self):
"""Return true if the binary sensor is on."""
return self._state | [
"def",
"is_on",
"(",
"self",
")",
":",
"return",
"self",
".",
"_state"
] | [
55,
4
] | [
57,
26
] | python | en | ['en', 'fy', 'en'] | True |
ZWaveBinarySensor.device_class | (self) | Return the class of this sensor, from DEVICE_CLASSES. | Return the class of this sensor, from DEVICE_CLASSES. | def device_class(self):
"""Return the class of this sensor, from DEVICE_CLASSES."""
return self._sensor_type | [
"def",
"device_class",
"(",
"self",
")",
":",
"return",
"self",
".",
"_sensor_type"
] | [
60,
4
] | [
62,
32
] | python | en | ['en', 'en', 'en'] | True |
ZWaveTriggerSensor.__init__ | (self, values, device_class) | Initialize the sensor. | Initialize the sensor. | def __init__(self, values, device_class):
"""Initialize the sensor."""
super().__init__(values, device_class)
# Set default off delay to 60 sec
self.re_arm_sec = 60
self.invalidate_after = None | [
"def",
"__init__",
"(",
"self",
",",
"values",
",",
"device_class",
")",
":",
"super",
"(",
")",
".",
"__init__",
"(",
"values",
",",
"device_class",
")",
"# Set default off delay to 60 sec",
"self",
".",
"re_arm_sec",
"=",
"60",
"self",
".",
"invalidate_after",
"=",
"None"
] | [
68,
4
] | [
73,
36
] | python | en | ['en', 'en', 'en'] | True |
ZWaveTriggerSensor.update_properties | (self) | Handle value changes for this entity's node. | Handle value changes for this entity's node. | def update_properties(self):
"""Handle value changes for this entity's node."""
self._state = self.values.primary.data
_LOGGER.debug("off_delay=%s", self.values.off_delay)
# Set re_arm_sec if off_delay is provided from the sensor
if self.values.off_delay:
_LOGGER.debug("off_delay.data=%s", self.values.off_delay.data)
self.re_arm_sec = self.values.off_delay.data * 8
# only allow this value to be true for re_arm secs
if not self.hass:
return
self.invalidate_after = dt_util.utcnow() + datetime.timedelta(
seconds=self.re_arm_sec
)
track_point_in_time(
self.hass, self.async_update_ha_state, self.invalidate_after
) | [
"def",
"update_properties",
"(",
"self",
")",
":",
"self",
".",
"_state",
"=",
"self",
".",
"values",
".",
"primary",
".",
"data",
"_LOGGER",
".",
"debug",
"(",
"\"off_delay=%s\"",
",",
"self",
".",
"values",
".",
"off_delay",
")",
"# Set re_arm_sec if off_delay is provided from the sensor",
"if",
"self",
".",
"values",
".",
"off_delay",
":",
"_LOGGER",
".",
"debug",
"(",
"\"off_delay.data=%s\"",
",",
"self",
".",
"values",
".",
"off_delay",
".",
"data",
")",
"self",
".",
"re_arm_sec",
"=",
"self",
".",
"values",
".",
"off_delay",
".",
"data",
"*",
"8",
"# only allow this value to be true for re_arm secs",
"if",
"not",
"self",
".",
"hass",
":",
"return",
"self",
".",
"invalidate_after",
"=",
"dt_util",
".",
"utcnow",
"(",
")",
"+",
"datetime",
".",
"timedelta",
"(",
"seconds",
"=",
"self",
".",
"re_arm_sec",
")",
"track_point_in_time",
"(",
"self",
".",
"hass",
",",
"self",
".",
"async_update_ha_state",
",",
"self",
".",
"invalidate_after",
")"
] | [
75,
4
] | [
92,
9
] | python | en | ['en', 'en', 'en'] | True |
ZWaveTriggerSensor.is_on | (self) | Return true if movement has happened within the rearm time. | Return true if movement has happened within the rearm time. | def is_on(self):
"""Return true if movement has happened within the rearm time."""
return self._state and (
self.invalidate_after is None or self.invalidate_after > dt_util.utcnow()
) | [
"def",
"is_on",
"(",
"self",
")",
":",
"return",
"self",
".",
"_state",
"and",
"(",
"self",
".",
"invalidate_after",
"is",
"None",
"or",
"self",
".",
"invalidate_after",
">",
"dt_util",
".",
"utcnow",
"(",
")",
")"
] | [
95,
4
] | [
99,
9
] | python | en | ['en', 'en', 'en'] | True |
mock_dev_track | (mock_device_tracker_conf) | Mock device tracker config loading. | Mock device tracker config loading. | def mock_dev_track(mock_device_tracker_conf):
"""Mock device tracker config loading."""
pass | [
"def",
"mock_dev_track",
"(",
"mock_device_tracker_conf",
")",
":",
"pass"
] | [
35,
0
] | [
37,
8
] | python | en | ['da', 'en', 'en'] | True |
mock_client | (hass, aiohttp_client) | Start the Home Assistant HTTP component. | Start the Home Assistant HTTP component. | def mock_client(hass, aiohttp_client):
"""Start the Home Assistant HTTP component."""
mock_component(hass, "group")
mock_component(hass, "zone")
mock_component(hass, "device_tracker")
MockConfigEntry(
domain="owntracks", data={"webhook_id": "owntracks_test", "secret": "abcd"}
).add_to_hass(hass)
hass.loop.run_until_complete(async_setup_component(hass, "owntracks", {}))
return hass.loop.run_until_complete(aiohttp_client(hass.http.app)) | [
"def",
"mock_client",
"(",
"hass",
",",
"aiohttp_client",
")",
":",
"mock_component",
"(",
"hass",
",",
"\"group\"",
")",
"mock_component",
"(",
"hass",
",",
"\"zone\"",
")",
"mock_component",
"(",
"hass",
",",
"\"device_tracker\"",
")",
"MockConfigEntry",
"(",
"domain",
"=",
"\"owntracks\"",
",",
"data",
"=",
"{",
"\"webhook_id\"",
":",
"\"owntracks_test\"",
",",
"\"secret\"",
":",
"\"abcd\"",
"}",
")",
".",
"add_to_hass",
"(",
"hass",
")",
"hass",
".",
"loop",
".",
"run_until_complete",
"(",
"async_setup_component",
"(",
"hass",
",",
"\"owntracks\"",
",",
"{",
"}",
")",
")",
"return",
"hass",
".",
"loop",
".",
"run_until_complete",
"(",
"aiohttp_client",
"(",
"hass",
".",
"http",
".",
"app",
")",
")"
] | [
41,
0
] | [
52,
70
] | python | en | ['en', 'en', 'en'] | True |
test_handle_valid_message | (mock_client) | Test that we forward messages correctly to OwnTracks. | Test that we forward messages correctly to OwnTracks. | async def test_handle_valid_message(mock_client):
"""Test that we forward messages correctly to OwnTracks."""
resp = await mock_client.post(
"/api/webhook/owntracks_test",
json=LOCATION_MESSAGE,
headers={"X-Limit-u": "Paulus", "X-Limit-d": "Pixel"},
)
assert resp.status == 200
json = await resp.json()
assert json == [] | [
"async",
"def",
"test_handle_valid_message",
"(",
"mock_client",
")",
":",
"resp",
"=",
"await",
"mock_client",
".",
"post",
"(",
"\"/api/webhook/owntracks_test\"",
",",
"json",
"=",
"LOCATION_MESSAGE",
",",
"headers",
"=",
"{",
"\"X-Limit-u\"",
":",
"\"Paulus\"",
",",
"\"X-Limit-d\"",
":",
"\"Pixel\"",
"}",
",",
")",
"assert",
"resp",
".",
"status",
"==",
"200",
"json",
"=",
"await",
"resp",
".",
"json",
"(",
")",
"assert",
"json",
"==",
"[",
"]"
] | [
55,
0
] | [
66,
21
] | python | en | ['en', 'en', 'en'] | True |
test_handle_valid_minimal_message | (mock_client) | Test that we forward messages correctly to OwnTracks. | Test that we forward messages correctly to OwnTracks. | async def test_handle_valid_minimal_message(mock_client):
"""Test that we forward messages correctly to OwnTracks."""
resp = await mock_client.post(
"/api/webhook/owntracks_test",
json=MINIMAL_LOCATION_MESSAGE,
headers={"X-Limit-u": "Paulus", "X-Limit-d": "Pixel"},
)
assert resp.status == 200
json = await resp.json()
assert json == [] | [
"async",
"def",
"test_handle_valid_minimal_message",
"(",
"mock_client",
")",
":",
"resp",
"=",
"await",
"mock_client",
".",
"post",
"(",
"\"/api/webhook/owntracks_test\"",
",",
"json",
"=",
"MINIMAL_LOCATION_MESSAGE",
",",
"headers",
"=",
"{",
"\"X-Limit-u\"",
":",
"\"Paulus\"",
",",
"\"X-Limit-d\"",
":",
"\"Pixel\"",
"}",
",",
")",
"assert",
"resp",
".",
"status",
"==",
"200",
"json",
"=",
"await",
"resp",
".",
"json",
"(",
")",
"assert",
"json",
"==",
"[",
"]"
] | [
69,
0
] | [
80,
21
] | python | en | ['en', 'en', 'en'] | True |
test_handle_value_error | (mock_client) | Test we don't disclose that this is a valid webhook. | Test we don't disclose that this is a valid webhook. | async def test_handle_value_error(mock_client):
"""Test we don't disclose that this is a valid webhook."""
resp = await mock_client.post(
"/api/webhook/owntracks_test",
json="",
headers={"X-Limit-u": "Paulus", "X-Limit-d": "Pixel"},
)
assert resp.status == 200
json = await resp.text()
assert json == "" | [
"async",
"def",
"test_handle_value_error",
"(",
"mock_client",
")",
":",
"resp",
"=",
"await",
"mock_client",
".",
"post",
"(",
"\"/api/webhook/owntracks_test\"",
",",
"json",
"=",
"\"\"",
",",
"headers",
"=",
"{",
"\"X-Limit-u\"",
":",
"\"Paulus\"",
",",
"\"X-Limit-d\"",
":",
"\"Pixel\"",
"}",
",",
")",
"assert",
"resp",
".",
"status",
"==",
"200",
"json",
"=",
"await",
"resp",
".",
"text",
"(",
")",
"assert",
"json",
"==",
"\"\""
] | [
83,
0
] | [
94,
21
] | python | en | ['en', 'en', 'en'] | True |
test_returns_error_missing_username | (mock_client, caplog) | Test that an error is returned when username is missing. | Test that an error is returned when username is missing. | async def test_returns_error_missing_username(mock_client, caplog):
"""Test that an error is returned when username is missing."""
resp = await mock_client.post(
"/api/webhook/owntracks_test",
json=LOCATION_MESSAGE,
headers={"X-Limit-d": "Pixel"},
)
# Needs to be 200 or OwnTracks keeps retrying bad packet.
assert resp.status == 200
json = await resp.json()
assert json == []
assert "No topic or user found" in caplog.text | [
"async",
"def",
"test_returns_error_missing_username",
"(",
"mock_client",
",",
"caplog",
")",
":",
"resp",
"=",
"await",
"mock_client",
".",
"post",
"(",
"\"/api/webhook/owntracks_test\"",
",",
"json",
"=",
"LOCATION_MESSAGE",
",",
"headers",
"=",
"{",
"\"X-Limit-d\"",
":",
"\"Pixel\"",
"}",
",",
")",
"# Needs to be 200 or OwnTracks keeps retrying bad packet.",
"assert",
"resp",
".",
"status",
"==",
"200",
"json",
"=",
"await",
"resp",
".",
"json",
"(",
")",
"assert",
"json",
"==",
"[",
"]",
"assert",
"\"No topic or user found\"",
"in",
"caplog",
".",
"text"
] | [
97,
0
] | [
109,
50
] | python | en | ['en', 'en', 'en'] | True |
test_returns_error_incorrect_json | (mock_client, caplog) | Test that an error is returned when username is missing. | Test that an error is returned when username is missing. | async def test_returns_error_incorrect_json(mock_client, caplog):
"""Test that an error is returned when username is missing."""
resp = await mock_client.post(
"/api/webhook/owntracks_test", data="not json", headers={"X-Limit-d": "Pixel"}
)
# Needs to be 200 or OwnTracks keeps retrying bad packet.
assert resp.status == 200
json = await resp.json()
assert json == []
assert "invalid JSON" in caplog.text | [
"async",
"def",
"test_returns_error_incorrect_json",
"(",
"mock_client",
",",
"caplog",
")",
":",
"resp",
"=",
"await",
"mock_client",
".",
"post",
"(",
"\"/api/webhook/owntracks_test\"",
",",
"data",
"=",
"\"not json\"",
",",
"headers",
"=",
"{",
"\"X-Limit-d\"",
":",
"\"Pixel\"",
"}",
")",
"# Needs to be 200 or OwnTracks keeps retrying bad packet.",
"assert",
"resp",
".",
"status",
"==",
"200",
"json",
"=",
"await",
"resp",
".",
"json",
"(",
")",
"assert",
"json",
"==",
"[",
"]",
"assert",
"\"invalid JSON\"",
"in",
"caplog",
".",
"text"
] | [
112,
0
] | [
122,
40
] | python | en | ['en', 'en', 'en'] | True |
test_returns_error_missing_device | (mock_client) | Test that an error is returned when device name is missing. | Test that an error is returned when device name is missing. | async def test_returns_error_missing_device(mock_client):
"""Test that an error is returned when device name is missing."""
resp = await mock_client.post(
"/api/webhook/owntracks_test",
json=LOCATION_MESSAGE,
headers={"X-Limit-u": "Paulus"},
)
assert resp.status == 200
json = await resp.json()
assert json == [] | [
"async",
"def",
"test_returns_error_missing_device",
"(",
"mock_client",
")",
":",
"resp",
"=",
"await",
"mock_client",
".",
"post",
"(",
"\"/api/webhook/owntracks_test\"",
",",
"json",
"=",
"LOCATION_MESSAGE",
",",
"headers",
"=",
"{",
"\"X-Limit-u\"",
":",
"\"Paulus\"",
"}",
",",
")",
"assert",
"resp",
".",
"status",
"==",
"200",
"json",
"=",
"await",
"resp",
".",
"json",
"(",
")",
"assert",
"json",
"==",
"[",
"]"
] | [
125,
0
] | [
136,
21
] | python | en | ['en', 'en', 'en'] | True |
test_context_delivers_pending_msg | () | Test that context is able to hold pending messages while being init. | Test that context is able to hold pending messages while being init. | def test_context_delivers_pending_msg():
"""Test that context is able to hold pending messages while being init."""
context = owntracks.OwnTracksContext(None, None, None, None, None, None, None, None)
context.async_see(hello="world")
context.async_see(world="hello")
received = []
context.set_async_see(lambda **data: received.append(data))
assert len(received) == 2
assert received[0] == {"hello": "world"}
assert received[1] == {"world": "hello"}
received.clear()
context.set_async_see(lambda **data: received.append(data))
assert len(received) == 0 | [
"def",
"test_context_delivers_pending_msg",
"(",
")",
":",
"context",
"=",
"owntracks",
".",
"OwnTracksContext",
"(",
"None",
",",
"None",
",",
"None",
",",
"None",
",",
"None",
",",
"None",
",",
"None",
",",
"None",
")",
"context",
".",
"async_see",
"(",
"hello",
"=",
"\"world\"",
")",
"context",
".",
"async_see",
"(",
"world",
"=",
"\"hello\"",
")",
"received",
"=",
"[",
"]",
"context",
".",
"set_async_see",
"(",
"lambda",
"*",
"*",
"data",
":",
"received",
".",
"append",
"(",
"data",
")",
")",
"assert",
"len",
"(",
"received",
")",
"==",
"2",
"assert",
"received",
"[",
"0",
"]",
"==",
"{",
"\"hello\"",
":",
"\"world\"",
"}",
"assert",
"received",
"[",
"1",
"]",
"==",
"{",
"\"world\"",
":",
"\"hello\"",
"}",
"received",
".",
"clear",
"(",
")",
"context",
".",
"set_async_see",
"(",
"lambda",
"*",
"*",
"data",
":",
"received",
".",
"append",
"(",
"data",
")",
")",
"assert",
"len",
"(",
"received",
")",
"==",
"0"
] | [
139,
0
] | [
155,
29
] | python | en | ['en', 'en', 'en'] | True |
async_setup_entry | (hass, entry, async_add_entities) | Set up Velbus sensor based on config_entry. | Set up Velbus sensor based on config_entry. | async def async_setup_entry(hass, entry, async_add_entities):
"""Set up Velbus sensor based on config_entry."""
cntrl = hass.data[DOMAIN][entry.entry_id]["cntrl"]
modules_data = hass.data[DOMAIN][entry.entry_id]["sensor"]
entities = []
for address, channel in modules_data:
module = cntrl.get_module(address)
entities.append(VelbusSensor(module, channel))
if module.get_class(channel) == "counter":
entities.append(VelbusSensor(module, channel, True))
async_add_entities(entities) | [
"async",
"def",
"async_setup_entry",
"(",
"hass",
",",
"entry",
",",
"async_add_entities",
")",
":",
"cntrl",
"=",
"hass",
".",
"data",
"[",
"DOMAIN",
"]",
"[",
"entry",
".",
"entry_id",
"]",
"[",
"\"cntrl\"",
"]",
"modules_data",
"=",
"hass",
".",
"data",
"[",
"DOMAIN",
"]",
"[",
"entry",
".",
"entry_id",
"]",
"[",
"\"sensor\"",
"]",
"entities",
"=",
"[",
"]",
"for",
"address",
",",
"channel",
"in",
"modules_data",
":",
"module",
"=",
"cntrl",
".",
"get_module",
"(",
"address",
")",
"entities",
".",
"append",
"(",
"VelbusSensor",
"(",
"module",
",",
"channel",
")",
")",
"if",
"module",
".",
"get_class",
"(",
"channel",
")",
"==",
"\"counter\"",
":",
"entities",
".",
"append",
"(",
"VelbusSensor",
"(",
"module",
",",
"channel",
",",
"True",
")",
")",
"async_add_entities",
"(",
"entities",
")"
] | [
7,
0
] | [
17,
32
] | python | en | ['en', 'zu', 'en'] | True |
VelbusSensor.__init__ | (self, module, channel, counter=False) | Initialize a sensor Velbus entity. | Initialize a sensor Velbus entity. | def __init__(self, module, channel, counter=False):
"""Initialize a sensor Velbus entity."""
super().__init__(module, channel)
self._is_counter = counter | [
"def",
"__init__",
"(",
"self",
",",
"module",
",",
"channel",
",",
"counter",
"=",
"False",
")",
":",
"super",
"(",
")",
".",
"__init__",
"(",
"module",
",",
"channel",
")",
"self",
".",
"_is_counter",
"=",
"counter"
] | [
23,
4
] | [
26,
34
] | python | es | ['es', 'fr', 'it'] | False |
VelbusSensor.unique_id | (self) | Return unique ID for counter sensors. | Return unique ID for counter sensors. | def unique_id(self):
"""Return unique ID for counter sensors."""
unique_id = super().unique_id
if self._is_counter:
unique_id = f"{unique_id}-counter"
return unique_id | [
"def",
"unique_id",
"(",
"self",
")",
":",
"unique_id",
"=",
"super",
"(",
")",
".",
"unique_id",
"if",
"self",
".",
"_is_counter",
":",
"unique_id",
"=",
"f\"{unique_id}-counter\"",
"return",
"unique_id"
] | [
29,
4
] | [
34,
24
] | python | en | ['fr', 'it', 'en'] | False |
VelbusSensor.device_class | (self) | Return the device class of the sensor. | Return the device class of the sensor. | def device_class(self):
"""Return the device class of the sensor."""
if self._module.get_class(self._channel) == "counter" and not self._is_counter:
if self._module.get_counter_unit(self._channel) == ENERGY_KILO_WATT_HOUR:
return DEVICE_CLASS_POWER
return None
return self._module.get_class(self._channel) | [
"def",
"device_class",
"(",
"self",
")",
":",
"if",
"self",
".",
"_module",
".",
"get_class",
"(",
"self",
".",
"_channel",
")",
"==",
"\"counter\"",
"and",
"not",
"self",
".",
"_is_counter",
":",
"if",
"self",
".",
"_module",
".",
"get_counter_unit",
"(",
"self",
".",
"_channel",
")",
"==",
"ENERGY_KILO_WATT_HOUR",
":",
"return",
"DEVICE_CLASS_POWER",
"return",
"None",
"return",
"self",
".",
"_module",
".",
"get_class",
"(",
"self",
".",
"_channel",
")"
] | [
37,
4
] | [
43,
52
] | python | en | ['en', 'en', 'en'] | True |
VelbusSensor.state | (self) | Return the state of the sensor. | Return the state of the sensor. | def state(self):
"""Return the state of the sensor."""
if self._is_counter:
return self._module.get_counter_state(self._channel)
return self._module.get_state(self._channel) | [
"def",
"state",
"(",
"self",
")",
":",
"if",
"self",
".",
"_is_counter",
":",
"return",
"self",
".",
"_module",
".",
"get_counter_state",
"(",
"self",
".",
"_channel",
")",
"return",
"self",
".",
"_module",
".",
"get_state",
"(",
"self",
".",
"_channel",
")"
] | [
46,
4
] | [
50,
52
] | python | en | ['en', 'en', 'en'] | True |
VelbusSensor.unit_of_measurement | (self) | Return the unit this state is expressed in. | Return the unit this state is expressed in. | def unit_of_measurement(self):
"""Return the unit this state is expressed in."""
if self._is_counter:
return self._module.get_counter_unit(self._channel)
return self._module.get_unit(self._channel) | [
"def",
"unit_of_measurement",
"(",
"self",
")",
":",
"if",
"self",
".",
"_is_counter",
":",
"return",
"self",
".",
"_module",
".",
"get_counter_unit",
"(",
"self",
".",
"_channel",
")",
"return",
"self",
".",
"_module",
".",
"get_unit",
"(",
"self",
".",
"_channel",
")"
] | [
53,
4
] | [
57,
51
] | python | en | ['en', 'en', 'en'] | True |
VelbusSensor.icon | (self) | Icon to use in the frontend. | Icon to use in the frontend. | def icon(self):
"""Icon to use in the frontend."""
if self._is_counter:
return "mdi:counter"
return None | [
"def",
"icon",
"(",
"self",
")",
":",
"if",
"self",
".",
"_is_counter",
":",
"return",
"\"mdi:counter\"",
"return",
"None"
] | [
60,
4
] | [
64,
19
] | python | en | ['en', 'en', 'en'] | True |
init | (empty=False) | Initialize the platform with entities. | Initialize the platform with entities. | def init(empty=False):
"""Initialize the platform with entities."""
global ENTITIES
ENTITIES = (
[]
if empty
else [
MockCover(
name="Simple cover",
is_on=True,
unique_id="unique_cover",
supports_tilt=False,
),
MockCover(
name="Set position cover",
is_on=True,
unique_id="unique_set_pos_cover",
current_cover_position=50,
supports_tilt=False,
),
MockCover(
name="Set tilt position cover",
is_on=True,
unique_id="unique_set_pos_tilt_cover",
current_cover_tilt_position=50,
supports_tilt=True,
),
MockCover(
name="Tilt cover",
is_on=True,
unique_id="unique_tilt_cover",
supports_tilt=True,
),
]
) | [
"def",
"init",
"(",
"empty",
"=",
"False",
")",
":",
"global",
"ENTITIES",
"ENTITIES",
"=",
"(",
"[",
"]",
"if",
"empty",
"else",
"[",
"MockCover",
"(",
"name",
"=",
"\"Simple cover\"",
",",
"is_on",
"=",
"True",
",",
"unique_id",
"=",
"\"unique_cover\"",
",",
"supports_tilt",
"=",
"False",
",",
")",
",",
"MockCover",
"(",
"name",
"=",
"\"Set position cover\"",
",",
"is_on",
"=",
"True",
",",
"unique_id",
"=",
"\"unique_set_pos_cover\"",
",",
"current_cover_position",
"=",
"50",
",",
"supports_tilt",
"=",
"False",
",",
")",
",",
"MockCover",
"(",
"name",
"=",
"\"Set tilt position cover\"",
",",
"is_on",
"=",
"True",
",",
"unique_id",
"=",
"\"unique_set_pos_tilt_cover\"",
",",
"current_cover_tilt_position",
"=",
"50",
",",
"supports_tilt",
"=",
"True",
",",
")",
",",
"MockCover",
"(",
"name",
"=",
"\"Tilt cover\"",
",",
"is_on",
"=",
"True",
",",
"unique_id",
"=",
"\"unique_tilt_cover\"",
",",
"supports_tilt",
"=",
"True",
",",
")",
",",
"]",
")"
] | [
22,
0
] | [
57,
5
] | python | en | ['en', 'en', 'en'] | True |
async_setup_platform | (
hass, config, async_add_entities_callback, discovery_info=None
) | Return mock entities. | Return mock entities. | async def async_setup_platform(
hass, config, async_add_entities_callback, discovery_info=None
):
"""Return mock entities."""
async_add_entities_callback(ENTITIES) | [
"async",
"def",
"async_setup_platform",
"(",
"hass",
",",
"config",
",",
"async_add_entities_callback",
",",
"discovery_info",
"=",
"None",
")",
":",
"async_add_entities_callback",
"(",
"ENTITIES",
")"
] | [
60,
0
] | [
64,
41
] | python | af | ['nl', 'af', 'en'] | False |
MockCover.is_closed | (self) | Return if the cover is closed or not. | Return if the cover is closed or not. | def is_closed(self):
"""Return if the cover is closed or not."""
return False | [
"def",
"is_closed",
"(",
"self",
")",
":",
"return",
"False"
] | [
71,
4
] | [
73,
20
] | python | en | ['en', 'en', 'en'] | True |
MockCover.current_cover_position | (self) | Return current position of cover. | Return current position of cover. | def current_cover_position(self):
"""Return current position of cover."""
return self._handle("current_cover_position") | [
"def",
"current_cover_position",
"(",
"self",
")",
":",
"return",
"self",
".",
"_handle",
"(",
"\"current_cover_position\"",
")"
] | [
76,
4
] | [
78,
53
] | python | en | ['en', 'en', 'en'] | True |
MockCover.current_cover_tilt_position | (self) | Return current position of cover tilt. | Return current position of cover tilt. | def current_cover_tilt_position(self):
"""Return current position of cover tilt."""
return self._handle("current_cover_tilt_position") | [
"def",
"current_cover_tilt_position",
"(",
"self",
")",
":",
"return",
"self",
".",
"_handle",
"(",
"\"current_cover_tilt_position\"",
")"
] | [
81,
4
] | [
83,
58
] | python | en | ['en', 'da', 'en'] | True |
MockCover.supported_features | (self) | Flag supported features. | Flag supported features. | def supported_features(self):
"""Flag supported features."""
supported_features = SUPPORT_OPEN | SUPPORT_CLOSE | SUPPORT_STOP
if self._handle("supports_tilt"):
supported_features |= (
SUPPORT_OPEN_TILT | SUPPORT_CLOSE_TILT | SUPPORT_STOP_TILT
)
if self.current_cover_position is not None:
supported_features |= SUPPORT_SET_POSITION
if self.current_cover_tilt_position is not None:
supported_features |= (
SUPPORT_OPEN_TILT
| SUPPORT_CLOSE_TILT
| SUPPORT_STOP_TILT
| SUPPORT_SET_TILT_POSITION
)
return supported_features | [
"def",
"supported_features",
"(",
"self",
")",
":",
"supported_features",
"=",
"SUPPORT_OPEN",
"|",
"SUPPORT_CLOSE",
"|",
"SUPPORT_STOP",
"if",
"self",
".",
"_handle",
"(",
"\"supports_tilt\"",
")",
":",
"supported_features",
"|=",
"(",
"SUPPORT_OPEN_TILT",
"|",
"SUPPORT_CLOSE_TILT",
"|",
"SUPPORT_STOP_TILT",
")",
"if",
"self",
".",
"current_cover_position",
"is",
"not",
"None",
":",
"supported_features",
"|=",
"SUPPORT_SET_POSITION",
"if",
"self",
".",
"current_cover_tilt_position",
"is",
"not",
"None",
":",
"supported_features",
"|=",
"(",
"SUPPORT_OPEN_TILT",
"|",
"SUPPORT_CLOSE_TILT",
"|",
"SUPPORT_STOP_TILT",
"|",
"SUPPORT_SET_TILT_POSITION",
")",
"return",
"supported_features"
] | [
86,
4
] | [
106,
33
] | python | en | ['da', 'en', 'en'] | True |
async_setup_entry | (hass, config_entry, async_add_entities) | Create the switches for the Ring devices. | Create the switches for the Ring devices. | async def async_setup_entry(hass, config_entry, async_add_entities):
"""Create the switches for the Ring devices."""
devices = hass.data[DOMAIN][config_entry.entry_id]["devices"]
switches = []
for device in devices["stickup_cams"]:
if device.has_capability("siren"):
switches.append(SirenSwitch(config_entry.entry_id, device))
async_add_entities(switches) | [
"async",
"def",
"async_setup_entry",
"(",
"hass",
",",
"config_entry",
",",
"async_add_entities",
")",
":",
"devices",
"=",
"hass",
".",
"data",
"[",
"DOMAIN",
"]",
"[",
"config_entry",
".",
"entry_id",
"]",
"[",
"\"devices\"",
"]",
"switches",
"=",
"[",
"]",
"for",
"device",
"in",
"devices",
"[",
"\"stickup_cams\"",
"]",
":",
"if",
"device",
".",
"has_capability",
"(",
"\"siren\"",
")",
":",
"switches",
".",
"append",
"(",
"SirenSwitch",
"(",
"config_entry",
".",
"entry_id",
",",
"device",
")",
")",
"async_add_entities",
"(",
"switches",
")"
] | [
26,
0
] | [
35,
32
] | python | en | ['en', 'en', 'en'] | True |
BaseRingSwitch.__init__ | (self, config_entry_id, device, device_type) | Initialize the switch. | Initialize the switch. | def __init__(self, config_entry_id, device, device_type):
"""Initialize the switch."""
super().__init__(config_entry_id, device)
self._device_type = device_type
self._unique_id = f"{self._device.id}-{self._device_type}" | [
"def",
"__init__",
"(",
"self",
",",
"config_entry_id",
",",
"device",
",",
"device_type",
")",
":",
"super",
"(",
")",
".",
"__init__",
"(",
"config_entry_id",
",",
"device",
")",
"self",
".",
"_device_type",
"=",
"device_type",
"self",
".",
"_unique_id",
"=",
"f\"{self._device.id}-{self._device_type}\""
] | [
41,
4
] | [
45,
66
] | python | en | ['en', 'en', 'en'] | True |
BaseRingSwitch.name | (self) | Name of the device. | Name of the device. | def name(self):
"""Name of the device."""
return f"{self._device.name} {self._device_type}" | [
"def",
"name",
"(",
"self",
")",
":",
"return",
"f\"{self._device.name} {self._device_type}\""
] | [
48,
4
] | [
50,
57
] | python | en | ['en', 'en', 'en'] | True |
BaseRingSwitch.unique_id | (self) | Return a unique ID. | Return a unique ID. | def unique_id(self):
"""Return a unique ID."""
return self._unique_id | [
"def",
"unique_id",
"(",
"self",
")",
":",
"return",
"self",
".",
"_unique_id"
] | [
53,
4
] | [
55,
30
] | python | ca | ['fr', 'ca', 'en'] | False |
SirenSwitch.__init__ | (self, config_entry_id, device) | Initialize the switch for a device with a siren. | Initialize the switch for a device with a siren. | def __init__(self, config_entry_id, device):
"""Initialize the switch for a device with a siren."""
super().__init__(config_entry_id, device, "siren")
self._no_updates_until = dt_util.utcnow()
self._siren_on = device.siren > 0 | [
"def",
"__init__",
"(",
"self",
",",
"config_entry_id",
",",
"device",
")",
":",
"super",
"(",
")",
".",
"__init__",
"(",
"config_entry_id",
",",
"device",
",",
"\"siren\"",
")",
"self",
".",
"_no_updates_until",
"=",
"dt_util",
".",
"utcnow",
"(",
")",
"self",
".",
"_siren_on",
"=",
"device",
".",
"siren",
">",
"0"
] | [
61,
4
] | [
65,
41
] | python | en | ['en', 'en', 'en'] | True |
SirenSwitch._update_callback | (self) | Call update method. | Call update method. | def _update_callback(self):
"""Call update method."""
if self._no_updates_until > dt_util.utcnow():
return
self._siren_on = self._device.siren > 0
self.async_write_ha_state() | [
"def",
"_update_callback",
"(",
"self",
")",
":",
"if",
"self",
".",
"_no_updates_until",
">",
"dt_util",
".",
"utcnow",
"(",
")",
":",
"return",
"self",
".",
"_siren_on",
"=",
"self",
".",
"_device",
".",
"siren",
">",
"0",
"self",
".",
"async_write_ha_state",
"(",
")"
] | [
68,
4
] | [
74,
35
] | python | en | ['en', 'sn', 'en'] | True |
SirenSwitch._set_switch | (self, new_state) | Update switch state, and causes Home Assistant to correctly update. | Update switch state, and causes Home Assistant to correctly update. | def _set_switch(self, new_state):
"""Update switch state, and causes Home Assistant to correctly update."""
try:
self._device.siren = new_state
except requests.Timeout:
_LOGGER.error("Time out setting %s siren to %s", self.entity_id, new_state)
return
self._siren_on = new_state > 0
self._no_updates_until = dt_util.utcnow() + SKIP_UPDATES_DELAY
self.schedule_update_ha_state() | [
"def",
"_set_switch",
"(",
"self",
",",
"new_state",
")",
":",
"try",
":",
"self",
".",
"_device",
".",
"siren",
"=",
"new_state",
"except",
"requests",
".",
"Timeout",
":",
"_LOGGER",
".",
"error",
"(",
"\"Time out setting %s siren to %s\"",
",",
"self",
".",
"entity_id",
",",
"new_state",
")",
"return",
"self",
".",
"_siren_on",
"=",
"new_state",
">",
"0",
"self",
".",
"_no_updates_until",
"=",
"dt_util",
".",
"utcnow",
"(",
")",
"+",
"SKIP_UPDATES_DELAY",
"self",
".",
"schedule_update_ha_state",
"(",
")"
] | [
76,
4
] | [
86,
39
] | python | en | ['en', 'en', 'en'] | True |
SirenSwitch.is_on | (self) | If the switch is currently on or off. | If the switch is currently on or off. | def is_on(self):
"""If the switch is currently on or off."""
return self._siren_on | [
"def",
"is_on",
"(",
"self",
")",
":",
"return",
"self",
".",
"_siren_on"
] | [
89,
4
] | [
91,
29
] | python | en | ['en', 'en', 'en'] | True |
SirenSwitch.turn_on | (self, **kwargs) | Turn the siren on for 30 seconds. | Turn the siren on for 30 seconds. | def turn_on(self, **kwargs):
"""Turn the siren on for 30 seconds."""
self._set_switch(1) | [
"def",
"turn_on",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"_set_switch",
"(",
"1",
")"
] | [
93,
4
] | [
95,
27
] | python | en | ['en', 'en', 'en'] | True |
SirenSwitch.turn_off | (self, **kwargs) | Turn the siren off. | Turn the siren off. | def turn_off(self, **kwargs):
"""Turn the siren off."""
self._set_switch(0) | [
"def",
"turn_off",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"_set_switch",
"(",
"0",
")"
] | [
97,
4
] | [
99,
27
] | python | en | ['en', 'fi', 'en'] | True |
SirenSwitch.icon | (self) | Return the icon. | Return the icon. | def icon(self):
"""Return the icon."""
return SIREN_ICON | [
"def",
"icon",
"(",
"self",
")",
":",
"return",
"SIREN_ICON"
] | [
102,
4
] | [
104,
25
] | python | en | ['en', 'sr', 'en'] | True |
get_service | (hass, config, discovery_info=None) | Get the Matrix notification service. | Get the Matrix notification service. | def get_service(hass, config, discovery_info=None):
"""Get the Matrix notification service."""
return MatrixNotificationService(config[CONF_DEFAULT_ROOM]) | [
"def",
"get_service",
"(",
"hass",
",",
"config",
",",
"discovery_info",
"=",
"None",
")",
":",
"return",
"MatrixNotificationService",
"(",
"config",
"[",
"CONF_DEFAULT_ROOM",
"]",
")"
] | [
18,
0
] | [
20,
63
] | python | en | ['en', 'en', 'en'] | True |
MatrixNotificationService.__init__ | (self, default_room) | Set up the Matrix notification service. | Set up the Matrix notification service. | def __init__(self, default_room):
"""Set up the Matrix notification service."""
self._default_room = default_room | [
"def",
"__init__",
"(",
"self",
",",
"default_room",
")",
":",
"self",
".",
"_default_room",
"=",
"default_room"
] | [
26,
4
] | [
28,
41
] | python | en | ['en', 'ny', 'en'] | True |
MatrixNotificationService.send_message | (self, message="", **kwargs) | Send the message to the Matrix server. | Send the message to the Matrix server. | def send_message(self, message="", **kwargs):
"""Send the message to the Matrix server."""
target_rooms = kwargs.get(ATTR_TARGET) or [self._default_room]
service_data = {ATTR_TARGET: target_rooms, ATTR_MESSAGE: message}
return self.hass.services.call(
DOMAIN, SERVICE_SEND_MESSAGE, service_data=service_data
) | [
"def",
"send_message",
"(",
"self",
",",
"message",
"=",
"\"\"",
",",
"*",
"*",
"kwargs",
")",
":",
"target_rooms",
"=",
"kwargs",
".",
"get",
"(",
"ATTR_TARGET",
")",
"or",
"[",
"self",
".",
"_default_room",
"]",
"service_data",
"=",
"{",
"ATTR_TARGET",
":",
"target_rooms",
",",
"ATTR_MESSAGE",
":",
"message",
"}",
"return",
"self",
".",
"hass",
".",
"services",
".",
"call",
"(",
"DOMAIN",
",",
"SERVICE_SEND_MESSAGE",
",",
"service_data",
"=",
"service_data",
")"
] | [
30,
4
] | [
38,
9
] | python | en | ['en', 'en', 'en'] | True |
mixup_data | (x, y, alpha=1.0, use_cuda=True) | Returns mixed inputs, pairs of targets, and lambda | Returns mixed inputs, pairs of targets, and lambda | def mixup_data(x, y, alpha=1.0, use_cuda=True):
'''Returns mixed inputs, pairs of targets, and lambda'''
if alpha > 0:
lam = np.random.beta(alpha, alpha)
else:
lam = 1
batch_size = x.size()[0]
if use_cuda:
index = torch.randperm(batch_size).cuda()
else:
index = torch.randperm(batch_size)
mixed_x = lam * x + (1 - lam) * x[index, :]
y_a, y_b = y, y[index]
return mixed_x, y_a, y_b, lam | [
"def",
"mixup_data",
"(",
"x",
",",
"y",
",",
"alpha",
"=",
"1.0",
",",
"use_cuda",
"=",
"True",
")",
":",
"if",
"alpha",
">",
"0",
":",
"lam",
"=",
"np",
".",
"random",
".",
"beta",
"(",
"alpha",
",",
"alpha",
")",
"else",
":",
"lam",
"=",
"1",
"batch_size",
"=",
"x",
".",
"size",
"(",
")",
"[",
"0",
"]",
"if",
"use_cuda",
":",
"index",
"=",
"torch",
".",
"randperm",
"(",
"batch_size",
")",
".",
"cuda",
"(",
")",
"else",
":",
"index",
"=",
"torch",
".",
"randperm",
"(",
"batch_size",
")",
"mixed_x",
"=",
"lam",
"*",
"x",
"+",
"(",
"1",
"-",
"lam",
")",
"*",
"x",
"[",
"index",
",",
":",
"]",
"y_a",
",",
"y_b",
"=",
"y",
",",
"y",
"[",
"index",
"]",
"return",
"mixed_x",
",",
"y_a",
",",
"y_b",
",",
"lam"
] | [
380,
0
] | [
395,
33
] | python | en | ['en', 'fil', 'en'] | True |
SubsetDistributedSampler.__init__ | (self, dataset, indices, num_replicas=None, rank=None, shuffle=True) |
Initialization.
Parameters
----------
dataset : torch.utils.data.Dataset
Dataset used for sampling.
num_replicas : int
Number of processes participating in distributed training. Default: World size.
rank : int
Rank of the current process within num_replicas. Default: Current rank.
shuffle : bool
If true (default), sampler will shuffle the indices.
|
Initialization. | def __init__(self, dataset, indices, num_replicas=None, rank=None, shuffle=True):
"""
Initialization.
Parameters
----------
dataset : torch.utils.data.Dataset
Dataset used for sampling.
num_replicas : int
Number of processes participating in distributed training. Default: World size.
rank : int
Rank of the current process within num_replicas. Default: Current rank.
shuffle : bool
If true (default), sampler will shuffle the indices.
"""
if num_replicas is None:
if not dist.is_available():
raise RuntimeError("Requires distributed package to be available")
num_replicas = dist.get_world_size()
if rank is None:
if not dist.is_available():
raise RuntimeError("Requires distributed package to be available")
rank = dist.get_rank()
self.dataset = dataset
self.num_replicas = num_replicas
self.rank = rank
self.epoch = 0
self.indices = indices
self.num_samples = int(math.ceil(len(self.indices) * 1.0 / self.num_replicas))
self.total_size = self.num_samples * self.num_replicas
self.shuffle = shuffle | [
"def",
"__init__",
"(",
"self",
",",
"dataset",
",",
"indices",
",",
"num_replicas",
"=",
"None",
",",
"rank",
"=",
"None",
",",
"shuffle",
"=",
"True",
")",
":",
"if",
"num_replicas",
"is",
"None",
":",
"if",
"not",
"dist",
".",
"is_available",
"(",
")",
":",
"raise",
"RuntimeError",
"(",
"\"Requires distributed package to be available\"",
")",
"num_replicas",
"=",
"dist",
".",
"get_world_size",
"(",
")",
"if",
"rank",
"is",
"None",
":",
"if",
"not",
"dist",
".",
"is_available",
"(",
")",
":",
"raise",
"RuntimeError",
"(",
"\"Requires distributed package to be available\"",
")",
"rank",
"=",
"dist",
".",
"get_rank",
"(",
")",
"self",
".",
"dataset",
"=",
"dataset",
"self",
".",
"num_replicas",
"=",
"num_replicas",
"self",
".",
"rank",
"=",
"rank",
"self",
".",
"epoch",
"=",
"0",
"self",
".",
"indices",
"=",
"indices",
"self",
".",
"num_samples",
"=",
"int",
"(",
"math",
".",
"ceil",
"(",
"len",
"(",
"self",
".",
"indices",
")",
"*",
"1.0",
"/",
"self",
".",
"num_replicas",
")",
")",
"self",
".",
"total_size",
"=",
"self",
".",
"num_samples",
"*",
"self",
".",
"num_replicas",
"self",
".",
"shuffle",
"=",
"shuffle"
] | [
25,
4
] | [
55,
30
] | python | en | ['en', 'error', 'th'] | False |
async_setup_platform | (hass, config, async_add_entities, discovery_info=None) | Set up the scenes for KNX platform. | Set up the scenes for KNX platform. | async def async_setup_platform(hass, config, async_add_entities, discovery_info=None):
"""Set up the scenes for KNX platform."""
entities = []
for device in hass.data[DOMAIN].xknx.devices:
if isinstance(device, XknxWeather):
entities.append(KNXWeather(device))
async_add_entities(entities) | [
"async",
"def",
"async_setup_platform",
"(",
"hass",
",",
"config",
",",
"async_add_entities",
",",
"discovery_info",
"=",
"None",
")",
":",
"entities",
"=",
"[",
"]",
"for",
"device",
"in",
"hass",
".",
"data",
"[",
"DOMAIN",
"]",
".",
"xknx",
".",
"devices",
":",
"if",
"isinstance",
"(",
"device",
",",
"XknxWeather",
")",
":",
"entities",
".",
"append",
"(",
"KNXWeather",
"(",
"device",
")",
")",
"async_add_entities",
"(",
"entities",
")"
] | [
11,
0
] | [
17,
32
] | python | en | ['en', 'da', 'en'] | True |
KNXWeather.__init__ | (self, device: XknxWeather) | Initialize of a KNX sensor. | Initialize of a KNX sensor. | def __init__(self, device: XknxWeather):
"""Initialize of a KNX sensor."""
super().__init__(device) | [
"def",
"__init__",
"(",
"self",
",",
"device",
":",
"XknxWeather",
")",
":",
"super",
"(",
")",
".",
"__init__",
"(",
"device",
")"
] | [
23,
4
] | [
25,
32
] | python | en | ['en', 'pt', 'en'] | True |
KNXWeather.temperature | (self) | Return current temperature. | Return current temperature. | def temperature(self):
"""Return current temperature."""
return self._device.temperature | [
"def",
"temperature",
"(",
"self",
")",
":",
"return",
"self",
".",
"_device",
".",
"temperature"
] | [
28,
4
] | [
30,
39
] | python | en | ['en', 'la', 'en'] | True |
KNXWeather.temperature_unit | (self) | Return temperature unit. | Return temperature unit. | def temperature_unit(self):
"""Return temperature unit."""
return TEMP_CELSIUS | [
"def",
"temperature_unit",
"(",
"self",
")",
":",
"return",
"TEMP_CELSIUS"
] | [
33,
4
] | [
35,
27
] | python | en | ['es', 'la', 'en'] | False |
KNXWeather.pressure | (self) | Return current air pressure. | Return current air pressure. | def pressure(self):
"""Return current air pressure."""
# KNX returns pA - HA requires hPa
return (
self._device.air_pressure / 100
if self._device.air_pressure is not None
else None
) | [
"def",
"pressure",
"(",
"self",
")",
":",
"# KNX returns pA - HA requires hPa",
"return",
"(",
"self",
".",
"_device",
".",
"air_pressure",
"/",
"100",
"if",
"self",
".",
"_device",
".",
"air_pressure",
"is",
"not",
"None",
"else",
"None",
")"
] | [
38,
4
] | [
45,
9
] | python | co | ['lt', 'co', 'en'] | False |
KNXWeather.condition | (self) | Return current weather condition. | Return current weather condition. | def condition(self):
"""Return current weather condition."""
return self._device.ha_current_state().value | [
"def",
"condition",
"(",
"self",
")",
":",
"return",
"self",
".",
"_device",
".",
"ha_current_state",
"(",
")",
".",
"value"
] | [
48,
4
] | [
50,
52
] | python | en | ['en', 'en', 'en'] | True |
KNXWeather.humidity | (self) | Return current humidity. | Return current humidity. | def humidity(self):
"""Return current humidity."""
return self._device.humidity if self._device.humidity is not None else None | [
"def",
"humidity",
"(",
"self",
")",
":",
"return",
"self",
".",
"_device",
".",
"humidity",
"if",
"self",
".",
"_device",
".",
"humidity",
"is",
"not",
"None",
"else",
"None"
] | [
53,
4
] | [
55,
83
] | python | en | ['en', 'sw', 'en'] | True |
KNXWeather.wind_speed | (self) | Return current wind speed in km/h. | Return current wind speed in km/h. | def wind_speed(self):
"""Return current wind speed in km/h."""
# KNX only supports wind speed in m/s
return (
self._device.wind_speed * 3.6
if self._device.wind_speed is not None
else None
) | [
"def",
"wind_speed",
"(",
"self",
")",
":",
"# KNX only supports wind speed in m/s",
"return",
"(",
"self",
".",
"_device",
".",
"wind_speed",
"*",
"3.6",
"if",
"self",
".",
"_device",
".",
"wind_speed",
"is",
"not",
"None",
"else",
"None",
")"
] | [
58,
4
] | [
65,
9
] | python | en | ['en', 'co', 'en'] | True |
test_padding | (hass) | Verify that non padding strings are allowed. | Verify that non padding strings are allowed. | async def test_padding(hass):
"""Verify that non padding strings are allowed."""
assert data_packet("Jg") == b"&"
assert data_packet("Jg=") == b"&"
assert data_packet("Jg==") == b"&" | [
"async",
"def",
"test_padding",
"(",
"hass",
")",
":",
"assert",
"data_packet",
"(",
"\"Jg\"",
")",
"==",
"b\"&\"",
"assert",
"data_packet",
"(",
"\"Jg=\"",
")",
"==",
"b\"&\"",
"assert",
"data_packet",
"(",
"\"Jg==\"",
")",
"==",
"b\"&\""
] | [
7,
0
] | [
11,
38
] | python | en | ['en', 'en', 'en'] | True |
test_valid_mac_address | (hass) | Test we convert a valid MAC address to bytes. | Test we convert a valid MAC address to bytes. | async def test_valid_mac_address(hass):
"""Test we convert a valid MAC address to bytes."""
valid = [
"A1B2C3D4E5F6",
"a1b2c3d4e5f6",
"A1B2-C3D4-E5F6",
"a1b2-c3d4-e5f6",
"A1B2.C3D4.E5F6",
"a1b2.c3d4.e5f6",
"A1-B2-C3-D4-E5-F6",
"a1-b2-c3-d4-e5-f6",
"A1:B2:C3:D4:E5:F6",
"a1:b2:c3:d4:e5:f6",
]
for mac in valid:
assert mac_address(mac) == b"\xa1\xb2\xc3\xd4\xe5\xf6" | [
"async",
"def",
"test_valid_mac_address",
"(",
"hass",
")",
":",
"valid",
"=",
"[",
"\"A1B2C3D4E5F6\"",
",",
"\"a1b2c3d4e5f6\"",
",",
"\"A1B2-C3D4-E5F6\"",
",",
"\"a1b2-c3d4-e5f6\"",
",",
"\"A1B2.C3D4.E5F6\"",
",",
"\"a1b2.c3d4.e5f6\"",
",",
"\"A1-B2-C3-D4-E5-F6\"",
",",
"\"a1-b2-c3-d4-e5-f6\"",
",",
"\"A1:B2:C3:D4:E5:F6\"",
",",
"\"a1:b2:c3:d4:e5:f6\"",
",",
"]",
"for",
"mac",
"in",
"valid",
":",
"assert",
"mac_address",
"(",
"mac",
")",
"==",
"b\"\\xa1\\xb2\\xc3\\xd4\\xe5\\xf6\""
] | [
14,
0
] | [
29,
62
] | python | en | ['en', 'lb', 'en'] | True |
test_invalid_mac_address | (hass) | Test we do not accept an invalid MAC address. | Test we do not accept an invalid MAC address. | async def test_invalid_mac_address(hass):
"""Test we do not accept an invalid MAC address."""
invalid = [
None,
123,
["a", "b", "c"],
{"abc": "def"},
"a1b2c3d4e5f",
"a1b2.c3d4.e5f",
"a1-b2-c3-d4-e5-f",
"a1b2c3d4e5f66",
"a1b2.c3d4.e5f66",
"a1-b2-c3-d4-e5-f66",
"a1b2c3d4e5fg",
"a1b2.c3d4.e5fg",
"a1-b2-c3-d4-e5-fg",
"a1b.2c3d4.e5fg",
"a1b-2-c3-d4-e5-fg",
]
for mac in invalid:
with pytest.raises((ValueError, vol.Invalid)):
mac_address(mac) | [
"async",
"def",
"test_invalid_mac_address",
"(",
"hass",
")",
":",
"invalid",
"=",
"[",
"None",
",",
"123",
",",
"[",
"\"a\"",
",",
"\"b\"",
",",
"\"c\"",
"]",
",",
"{",
"\"abc\"",
":",
"\"def\"",
"}",
",",
"\"a1b2c3d4e5f\"",
",",
"\"a1b2.c3d4.e5f\"",
",",
"\"a1-b2-c3-d4-e5-f\"",
",",
"\"a1b2c3d4e5f66\"",
",",
"\"a1b2.c3d4.e5f66\"",
",",
"\"a1-b2-c3-d4-e5-f66\"",
",",
"\"a1b2c3d4e5fg\"",
",",
"\"a1b2.c3d4.e5fg\"",
",",
"\"a1-b2-c3-d4-e5-fg\"",
",",
"\"a1b.2c3d4.e5fg\"",
",",
"\"a1b-2-c3-d4-e5-fg\"",
",",
"]",
"for",
"mac",
"in",
"invalid",
":",
"with",
"pytest",
".",
"raises",
"(",
"(",
"ValueError",
",",
"vol",
".",
"Invalid",
")",
")",
":",
"mac_address",
"(",
"mac",
")"
] | [
32,
0
] | [
53,
28
] | python | en | ['en', 'lb', 'en'] | True |
async_setup_entry | (hass, config_entry, async_add_entities) | Set up Abode switch devices. | Set up Abode switch devices. | async def async_setup_entry(hass, config_entry, async_add_entities):
"""Set up Abode switch devices."""
data = hass.data[DOMAIN]
entities = []
for device_type in DEVICE_TYPES:
for device in data.abode.get_devices(generic_type=device_type):
entities.append(AbodeSwitch(data, device))
for automation in data.abode.get_automations():
entities.append(AbodeAutomationSwitch(data, automation))
async_add_entities(entities) | [
"async",
"def",
"async_setup_entry",
"(",
"hass",
",",
"config_entry",
",",
"async_add_entities",
")",
":",
"data",
"=",
"hass",
".",
"data",
"[",
"DOMAIN",
"]",
"entities",
"=",
"[",
"]",
"for",
"device_type",
"in",
"DEVICE_TYPES",
":",
"for",
"device",
"in",
"data",
".",
"abode",
".",
"get_devices",
"(",
"generic_type",
"=",
"device_type",
")",
":",
"entities",
".",
"append",
"(",
"AbodeSwitch",
"(",
"data",
",",
"device",
")",
")",
"for",
"automation",
"in",
"data",
".",
"abode",
".",
"get_automations",
"(",
")",
":",
"entities",
".",
"append",
"(",
"AbodeAutomationSwitch",
"(",
"data",
",",
"automation",
")",
")",
"async_add_entities",
"(",
"entities",
")"
] | [
14,
0
] | [
27,
32
] | python | en | ['en', 'en', 'en'] | True |
AbodeSwitch.turn_on | (self, **kwargs) | Turn on the device. | Turn on the device. | def turn_on(self, **kwargs):
"""Turn on the device."""
self._device.switch_on() | [
"def",
"turn_on",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"_device",
".",
"switch_on",
"(",
")"
] | [
33,
4
] | [
35,
32
] | python | en | ['en', 'en', 'en'] | True |
AbodeSwitch.turn_off | (self, **kwargs) | Turn off the device. | Turn off the device. | def turn_off(self, **kwargs):
"""Turn off the device."""
self._device.switch_off() | [
"def",
"turn_off",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"_device",
".",
"switch_off",
"(",
")"
] | [
37,
4
] | [
39,
33
] | python | en | ['en', 'en', 'en'] | True |
AbodeSwitch.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._device.is_on | [
"def",
"is_on",
"(",
"self",
")",
":",
"return",
"self",
".",
"_device",
".",
"is_on"
] | [
42,
4
] | [
44,
33
] | python | en | ['en', 'fy', 'en'] | True |
AbodeAutomationSwitch.async_added_to_hass | (self) | Set up trigger automation service. | Set up trigger automation service. | async def async_added_to_hass(self):
"""Set up trigger automation service."""
await super().async_added_to_hass()
signal = f"abode_trigger_automation_{self.entity_id}"
self.async_on_remove(async_dispatcher_connect(self.hass, signal, self.trigger)) | [
"async",
"def",
"async_added_to_hass",
"(",
"self",
")",
":",
"await",
"super",
"(",
")",
".",
"async_added_to_hass",
"(",
")",
"signal",
"=",
"f\"abode_trigger_automation_{self.entity_id}\"",
"self",
".",
"async_on_remove",
"(",
"async_dispatcher_connect",
"(",
"self",
".",
"hass",
",",
"signal",
",",
"self",
".",
"trigger",
")",
")"
] | [
50,
4
] | [
55,
87
] | python | en | ['en', 'en', 'en'] | True |
AbodeAutomationSwitch.turn_on | (self, **kwargs) | Enable the automation. | Enable the automation. | def turn_on(self, **kwargs):
"""Enable the automation."""
if self._automation.enable(True):
self.schedule_update_ha_state() | [
"def",
"turn_on",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"self",
".",
"_automation",
".",
"enable",
"(",
"True",
")",
":",
"self",
".",
"schedule_update_ha_state",
"(",
")"
] | [
57,
4
] | [
60,
43
] | python | en | ['en', 'en', 'en'] | True |
AbodeAutomationSwitch.turn_off | (self, **kwargs) | Disable the automation. | Disable the automation. | def turn_off(self, **kwargs):
"""Disable the automation."""
if self._automation.enable(False):
self.schedule_update_ha_state() | [
"def",
"turn_off",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"self",
".",
"_automation",
".",
"enable",
"(",
"False",
")",
":",
"self",
".",
"schedule_update_ha_state",
"(",
")"
] | [
62,
4
] | [
65,
43
] | python | en | ['en', 'en', 'en'] | True |
AbodeAutomationSwitch.trigger | (self) | Trigger the automation. | Trigger the automation. | def trigger(self):
"""Trigger the automation."""
self._automation.trigger() | [
"def",
"trigger",
"(",
"self",
")",
":",
"self",
".",
"_automation",
".",
"trigger",
"(",
")"
] | [
67,
4
] | [
69,
34
] | python | en | ['en', 'en', 'en'] | True |
AbodeAutomationSwitch.is_on | (self) | Return True if the automation is enabled. | Return True if the automation is enabled. | def is_on(self):
"""Return True if the automation is enabled."""
return self._automation.is_enabled | [
"def",
"is_on",
"(",
"self",
")",
":",
"return",
"self",
".",
"_automation",
".",
"is_enabled"
] | [
72,
4
] | [
74,
42
] | python | en | ['en', 'en', 'en'] | True |
AbodeAutomationSwitch.icon | (self) | Return the robot icon to match Home Assistant automations. | Return the robot icon to match Home Assistant automations. | def icon(self):
"""Return the robot icon to match Home Assistant automations."""
return ICON | [
"def",
"icon",
"(",
"self",
")",
":",
"return",
"ICON"
] | [
77,
4
] | [
79,
19
] | python | en | ['en', 'en', 'en'] | True |
test_setup_failure | (hass, caplog) | Test that setup failure is handled and logged. | Test that setup failure is handled and logged. | async def test_setup_failure(hass, caplog):
"""Test that setup failure is handled and logged."""
patch_product_identify(None, side_effect=blebox_uniapi.error.ClientError)
entry = mock_config()
entry.add_to_hass(hass)
caplog.set_level(logging.ERROR)
await hass.config_entries.async_setup(entry.entry_id)
await hass.async_block_till_done()
assert "Identify failed at 172.100.123.4:80 ()" in caplog.text
assert entry.state == ENTRY_STATE_SETUP_RETRY | [
"async",
"def",
"test_setup_failure",
"(",
"hass",
",",
"caplog",
")",
":",
"patch_product_identify",
"(",
"None",
",",
"side_effect",
"=",
"blebox_uniapi",
".",
"error",
".",
"ClientError",
")",
"entry",
"=",
"mock_config",
"(",
")",
"entry",
".",
"add_to_hass",
"(",
"hass",
")",
"caplog",
".",
"set_level",
"(",
"logging",
".",
"ERROR",
")",
"await",
"hass",
".",
"config_entries",
".",
"async_setup",
"(",
"entry",
".",
"entry_id",
")",
"await",
"hass",
".",
"async_block_till_done",
"(",
")",
"assert",
"\"Identify failed at 172.100.123.4:80 ()\"",
"in",
"caplog",
".",
"text",
"assert",
"entry",
".",
"state",
"==",
"ENTRY_STATE_SETUP_RETRY"
] | [
12,
0
] | [
25,
49
] | python | en | ['en', 'en', 'en'] | True |
test_setup_failure_on_connection | (hass, caplog) | Test that setup failure is handled and logged. | Test that setup failure is handled and logged. | async def test_setup_failure_on_connection(hass, caplog):
"""Test that setup failure is handled and logged."""
patch_product_identify(None, side_effect=blebox_uniapi.error.ConnectionError)
entry = mock_config()
entry.add_to_hass(hass)
caplog.set_level(logging.ERROR)
await hass.config_entries.async_setup(entry.entry_id)
await hass.async_block_till_done()
assert "Identify failed at 172.100.123.4:80 ()" in caplog.text
assert entry.state == ENTRY_STATE_SETUP_RETRY | [
"async",
"def",
"test_setup_failure_on_connection",
"(",
"hass",
",",
"caplog",
")",
":",
"patch_product_identify",
"(",
"None",
",",
"side_effect",
"=",
"blebox_uniapi",
".",
"error",
".",
"ConnectionError",
")",
"entry",
"=",
"mock_config",
"(",
")",
"entry",
".",
"add_to_hass",
"(",
"hass",
")",
"caplog",
".",
"set_level",
"(",
"logging",
".",
"ERROR",
")",
"await",
"hass",
".",
"config_entries",
".",
"async_setup",
"(",
"entry",
".",
"entry_id",
")",
"await",
"hass",
".",
"async_block_till_done",
"(",
")",
"assert",
"\"Identify failed at 172.100.123.4:80 ()\"",
"in",
"caplog",
".",
"text",
"assert",
"entry",
".",
"state",
"==",
"ENTRY_STATE_SETUP_RETRY"
] | [
28,
0
] | [
41,
49
] | python | en | ['en', 'en', 'en'] | True |
test_unload_config_entry | (hass) | Test that unloading works properly. | Test that unloading works properly. | async def test_unload_config_entry(hass):
"""Test that unloading works properly."""
patch_product_identify(None)
entry = mock_config()
entry.add_to_hass(hass)
await hass.config_entries.async_setup(entry.entry_id)
await hass.async_block_till_done()
assert hass.data[DOMAIN]
await hass.config_entries.async_unload(entry.entry_id)
await hass.async_block_till_done()
assert not hass.data.get(DOMAIN)
assert entry.state == ENTRY_STATE_NOT_LOADED | [
"async",
"def",
"test_unload_config_entry",
"(",
"hass",
")",
":",
"patch_product_identify",
"(",
"None",
")",
"entry",
"=",
"mock_config",
"(",
")",
"entry",
".",
"add_to_hass",
"(",
"hass",
")",
"await",
"hass",
".",
"config_entries",
".",
"async_setup",
"(",
"entry",
".",
"entry_id",
")",
"await",
"hass",
".",
"async_block_till_done",
"(",
")",
"assert",
"hass",
".",
"data",
"[",
"DOMAIN",
"]",
"await",
"hass",
".",
"config_entries",
".",
"async_unload",
"(",
"entry",
".",
"entry_id",
")",
"await",
"hass",
".",
"async_block_till_done",
"(",
")",
"assert",
"not",
"hass",
".",
"data",
".",
"get",
"(",
"DOMAIN",
")",
"assert",
"entry",
".",
"state",
"==",
"ENTRY_STATE_NOT_LOADED"
] | [
44,
0
] | [
59,
48
] | python | en | ['en', 'en', 'en'] | True |
convert_time_to_utc | (timestr) | Take a string like 08:00:00 and convert it to a unix timestamp. | Take a string like 08:00:00 and convert it to a unix timestamp. | def convert_time_to_utc(timestr):
"""Take a string like 08:00:00 and convert it to a unix timestamp."""
combined = datetime.combine(
dt_util.start_of_local_day(), dt_util.parse_time(timestr)
)
if combined < datetime.now():
combined = combined + timedelta(days=1)
return dt_util.as_timestamp(combined) | [
"def",
"convert_time_to_utc",
"(",
"timestr",
")",
":",
"combined",
"=",
"datetime",
".",
"combine",
"(",
"dt_util",
".",
"start_of_local_day",
"(",
")",
",",
"dt_util",
".",
"parse_time",
"(",
"timestr",
")",
")",
"if",
"combined",
"<",
"datetime",
".",
"now",
"(",
")",
":",
"combined",
"=",
"combined",
"+",
"timedelta",
"(",
"days",
"=",
"1",
")",
"return",
"dt_util",
".",
"as_timestamp",
"(",
"combined",
")"
] | [
126,
0
] | [
133,
41
] | python | en | ['en', 'en', 'en'] | True |
setup_platform | (hass, config, add_entities_callback, discovery_info=None) | Set up the Google travel time platform. | Set up the Google travel time platform. | def setup_platform(hass, config, add_entities_callback, discovery_info=None):
"""Set up the Google travel time platform."""
def run_setup(event):
"""
Delay the setup until Home Assistant is fully initialized.
This allows any entities to be created already
"""
hass.data.setdefault(DATA_KEY, [])
options = config.get(CONF_OPTIONS)
if options.get("units") is None:
options["units"] = hass.config.units.name
travel_mode = config.get(CONF_TRAVEL_MODE)
mode = options.get(CONF_MODE)
if travel_mode is not None:
wstr = (
"Google Travel Time: travel_mode is deprecated, please "
"add mode to the options dictionary instead!"
)
_LOGGER.warning(wstr)
if mode is None:
options[CONF_MODE] = travel_mode
titled_mode = options.get(CONF_MODE).title()
formatted_name = f"{DEFAULT_NAME} - {titled_mode}"
name = config.get(CONF_NAME, formatted_name)
api_key = config.get(CONF_API_KEY)
origin = config.get(CONF_ORIGIN)
destination = config.get(CONF_DESTINATION)
sensor = GoogleTravelTimeSensor(
hass, name, api_key, origin, destination, options
)
hass.data[DATA_KEY].append(sensor)
if sensor.valid_api_connection:
add_entities_callback([sensor])
# Wait until start event is sent to load this component.
hass.bus.listen_once(EVENT_HOMEASSISTANT_START, run_setup) | [
"def",
"setup_platform",
"(",
"hass",
",",
"config",
",",
"add_entities_callback",
",",
"discovery_info",
"=",
"None",
")",
":",
"def",
"run_setup",
"(",
"event",
")",
":",
"\"\"\"\n Delay the setup until Home Assistant is fully initialized.\n\n This allows any entities to be created already\n \"\"\"",
"hass",
".",
"data",
".",
"setdefault",
"(",
"DATA_KEY",
",",
"[",
"]",
")",
"options",
"=",
"config",
".",
"get",
"(",
"CONF_OPTIONS",
")",
"if",
"options",
".",
"get",
"(",
"\"units\"",
")",
"is",
"None",
":",
"options",
"[",
"\"units\"",
"]",
"=",
"hass",
".",
"config",
".",
"units",
".",
"name",
"travel_mode",
"=",
"config",
".",
"get",
"(",
"CONF_TRAVEL_MODE",
")",
"mode",
"=",
"options",
".",
"get",
"(",
"CONF_MODE",
")",
"if",
"travel_mode",
"is",
"not",
"None",
":",
"wstr",
"=",
"(",
"\"Google Travel Time: travel_mode is deprecated, please \"",
"\"add mode to the options dictionary instead!\"",
")",
"_LOGGER",
".",
"warning",
"(",
"wstr",
")",
"if",
"mode",
"is",
"None",
":",
"options",
"[",
"CONF_MODE",
"]",
"=",
"travel_mode",
"titled_mode",
"=",
"options",
".",
"get",
"(",
"CONF_MODE",
")",
".",
"title",
"(",
")",
"formatted_name",
"=",
"f\"{DEFAULT_NAME} - {titled_mode}\"",
"name",
"=",
"config",
".",
"get",
"(",
"CONF_NAME",
",",
"formatted_name",
")",
"api_key",
"=",
"config",
".",
"get",
"(",
"CONF_API_KEY",
")",
"origin",
"=",
"config",
".",
"get",
"(",
"CONF_ORIGIN",
")",
"destination",
"=",
"config",
".",
"get",
"(",
"CONF_DESTINATION",
")",
"sensor",
"=",
"GoogleTravelTimeSensor",
"(",
"hass",
",",
"name",
",",
"api_key",
",",
"origin",
",",
"destination",
",",
"options",
")",
"hass",
".",
"data",
"[",
"DATA_KEY",
"]",
".",
"append",
"(",
"sensor",
")",
"if",
"sensor",
".",
"valid_api_connection",
":",
"add_entities_callback",
"(",
"[",
"sensor",
"]",
")",
"# Wait until start event is sent to load this component.",
"hass",
".",
"bus",
".",
"listen_once",
"(",
"EVENT_HOMEASSISTANT_START",
",",
"run_setup",
")"
] | [
136,
0
] | [
179,
62
] | python | en | ['en', 'da', 'en'] | True |
GoogleTravelTimeSensor.__init__ | (self, hass, name, api_key, origin, destination, options) | Initialize the sensor. | Initialize the sensor. | def __init__(self, hass, name, api_key, origin, destination, options):
"""Initialize the sensor."""
self._hass = hass
self._name = name
self._options = options
self._unit_of_measurement = TIME_MINUTES
self._matrix = None
self.valid_api_connection = True
# Check if location is a trackable entity
if origin.split(".", 1)[0] in TRACKABLE_DOMAINS:
self._origin_entity_id = origin
else:
self._origin = origin
if destination.split(".", 1)[0] in TRACKABLE_DOMAINS:
self._destination_entity_id = destination
else:
self._destination = destination
self._client = googlemaps.Client(api_key, timeout=10)
try:
self.update()
except googlemaps.exceptions.ApiError as exp:
_LOGGER.error(exp)
self.valid_api_connection = False
return | [
"def",
"__init__",
"(",
"self",
",",
"hass",
",",
"name",
",",
"api_key",
",",
"origin",
",",
"destination",
",",
"options",
")",
":",
"self",
".",
"_hass",
"=",
"hass",
"self",
".",
"_name",
"=",
"name",
"self",
".",
"_options",
"=",
"options",
"self",
".",
"_unit_of_measurement",
"=",
"TIME_MINUTES",
"self",
".",
"_matrix",
"=",
"None",
"self",
".",
"valid_api_connection",
"=",
"True",
"# Check if location is a trackable entity",
"if",
"origin",
".",
"split",
"(",
"\".\"",
",",
"1",
")",
"[",
"0",
"]",
"in",
"TRACKABLE_DOMAINS",
":",
"self",
".",
"_origin_entity_id",
"=",
"origin",
"else",
":",
"self",
".",
"_origin",
"=",
"origin",
"if",
"destination",
".",
"split",
"(",
"\".\"",
",",
"1",
")",
"[",
"0",
"]",
"in",
"TRACKABLE_DOMAINS",
":",
"self",
".",
"_destination_entity_id",
"=",
"destination",
"else",
":",
"self",
".",
"_destination",
"=",
"destination",
"self",
".",
"_client",
"=",
"googlemaps",
".",
"Client",
"(",
"api_key",
",",
"timeout",
"=",
"10",
")",
"try",
":",
"self",
".",
"update",
"(",
")",
"except",
"googlemaps",
".",
"exceptions",
".",
"ApiError",
"as",
"exp",
":",
"_LOGGER",
".",
"error",
"(",
"exp",
")",
"self",
".",
"valid_api_connection",
"=",
"False",
"return"
] | [
185,
4
] | [
211,
18
] | python | en | ['en', 'en', 'en'] | True |
GoogleTravelTimeSensor.state | (self) | Return the state of the sensor. | Return the state of the sensor. | def state(self):
"""Return the state of the sensor."""
if self._matrix is None:
return None
_data = self._matrix["rows"][0]["elements"][0]
if "duration_in_traffic" in _data:
return round(_data["duration_in_traffic"]["value"] / 60)
if "duration" in _data:
return round(_data["duration"]["value"] / 60)
return None | [
"def",
"state",
"(",
"self",
")",
":",
"if",
"self",
".",
"_matrix",
"is",
"None",
":",
"return",
"None",
"_data",
"=",
"self",
".",
"_matrix",
"[",
"\"rows\"",
"]",
"[",
"0",
"]",
"[",
"\"elements\"",
"]",
"[",
"0",
"]",
"if",
"\"duration_in_traffic\"",
"in",
"_data",
":",
"return",
"round",
"(",
"_data",
"[",
"\"duration_in_traffic\"",
"]",
"[",
"\"value\"",
"]",
"/",
"60",
")",
"if",
"\"duration\"",
"in",
"_data",
":",
"return",
"round",
"(",
"_data",
"[",
"\"duration\"",
"]",
"[",
"\"value\"",
"]",
"/",
"60",
")",
"return",
"None"
] | [
214,
4
] | [
224,
19
] | python | en | ['en', 'en', 'en'] | True |
GoogleTravelTimeSensor.name | (self) | Get the name of the sensor. | Get the name of the sensor. | def name(self):
"""Get the name of the sensor."""
return self._name | [
"def",
"name",
"(",
"self",
")",
":",
"return",
"self",
".",
"_name"
] | [
227,
4
] | [
229,
25
] | python | en | ['en', 'en', 'en'] | True |
GoogleTravelTimeSensor.device_state_attributes | (self) | Return the state attributes. | Return the state attributes. | def device_state_attributes(self):
"""Return the state attributes."""
if self._matrix is None:
return None
res = self._matrix.copy()
res.update(self._options)
del res["rows"]
_data = self._matrix["rows"][0]["elements"][0]
if "duration_in_traffic" in _data:
res["duration_in_traffic"] = _data["duration_in_traffic"]["text"]
if "duration" in _data:
res["duration"] = _data["duration"]["text"]
if "distance" in _data:
res["distance"] = _data["distance"]["text"]
res["origin"] = self._origin
res["destination"] = self._destination
res[ATTR_ATTRIBUTION] = ATTRIBUTION
return res | [
"def",
"device_state_attributes",
"(",
"self",
")",
":",
"if",
"self",
".",
"_matrix",
"is",
"None",
":",
"return",
"None",
"res",
"=",
"self",
".",
"_matrix",
".",
"copy",
"(",
")",
"res",
".",
"update",
"(",
"self",
".",
"_options",
")",
"del",
"res",
"[",
"\"rows\"",
"]",
"_data",
"=",
"self",
".",
"_matrix",
"[",
"\"rows\"",
"]",
"[",
"0",
"]",
"[",
"\"elements\"",
"]",
"[",
"0",
"]",
"if",
"\"duration_in_traffic\"",
"in",
"_data",
":",
"res",
"[",
"\"duration_in_traffic\"",
"]",
"=",
"_data",
"[",
"\"duration_in_traffic\"",
"]",
"[",
"\"text\"",
"]",
"if",
"\"duration\"",
"in",
"_data",
":",
"res",
"[",
"\"duration\"",
"]",
"=",
"_data",
"[",
"\"duration\"",
"]",
"[",
"\"text\"",
"]",
"if",
"\"distance\"",
"in",
"_data",
":",
"res",
"[",
"\"distance\"",
"]",
"=",
"_data",
"[",
"\"distance\"",
"]",
"[",
"\"text\"",
"]",
"res",
"[",
"\"origin\"",
"]",
"=",
"self",
".",
"_origin",
"res",
"[",
"\"destination\"",
"]",
"=",
"self",
".",
"_destination",
"res",
"[",
"ATTR_ATTRIBUTION",
"]",
"=",
"ATTRIBUTION",
"return",
"res"
] | [
232,
4
] | [
250,
18
] | python | en | ['en', 'en', 'en'] | True |
GoogleTravelTimeSensor.unit_of_measurement | (self) | Return the unit this state is expressed in. | Return the unit this state is expressed in. | def unit_of_measurement(self):
"""Return the unit this state is expressed in."""
return self._unit_of_measurement | [
"def",
"unit_of_measurement",
"(",
"self",
")",
":",
"return",
"self",
".",
"_unit_of_measurement"
] | [
253,
4
] | [
255,
40
] | python | en | ['en', 'en', 'en'] | True |
GoogleTravelTimeSensor.update | (self) | Get the latest data from Google. | Get the latest data from Google. | def update(self):
"""Get the latest data from Google."""
options_copy = self._options.copy()
dtime = options_copy.get("departure_time")
atime = options_copy.get("arrival_time")
if dtime is not None and ":" in dtime:
options_copy["departure_time"] = convert_time_to_utc(dtime)
elif dtime is not None:
options_copy["departure_time"] = dtime
elif atime is None:
options_copy["departure_time"] = "now"
if atime is not None and ":" in atime:
options_copy["arrival_time"] = convert_time_to_utc(atime)
elif atime is not None:
options_copy["arrival_time"] = atime
# Convert device_trackers to google friendly location
if hasattr(self, "_origin_entity_id"):
self._origin = self._get_location_from_entity(self._origin_entity_id)
if hasattr(self, "_destination_entity_id"):
self._destination = self._get_location_from_entity(
self._destination_entity_id
)
self._destination = self._resolve_zone(self._destination)
self._origin = self._resolve_zone(self._origin)
if self._destination is not None and self._origin is not None:
self._matrix = self._client.distance_matrix(
self._origin, self._destination, **options_copy
) | [
"def",
"update",
"(",
"self",
")",
":",
"options_copy",
"=",
"self",
".",
"_options",
".",
"copy",
"(",
")",
"dtime",
"=",
"options_copy",
".",
"get",
"(",
"\"departure_time\"",
")",
"atime",
"=",
"options_copy",
".",
"get",
"(",
"\"arrival_time\"",
")",
"if",
"dtime",
"is",
"not",
"None",
"and",
"\":\"",
"in",
"dtime",
":",
"options_copy",
"[",
"\"departure_time\"",
"]",
"=",
"convert_time_to_utc",
"(",
"dtime",
")",
"elif",
"dtime",
"is",
"not",
"None",
":",
"options_copy",
"[",
"\"departure_time\"",
"]",
"=",
"dtime",
"elif",
"atime",
"is",
"None",
":",
"options_copy",
"[",
"\"departure_time\"",
"]",
"=",
"\"now\"",
"if",
"atime",
"is",
"not",
"None",
"and",
"\":\"",
"in",
"atime",
":",
"options_copy",
"[",
"\"arrival_time\"",
"]",
"=",
"convert_time_to_utc",
"(",
"atime",
")",
"elif",
"atime",
"is",
"not",
"None",
":",
"options_copy",
"[",
"\"arrival_time\"",
"]",
"=",
"atime",
"# Convert device_trackers to google friendly location",
"if",
"hasattr",
"(",
"self",
",",
"\"_origin_entity_id\"",
")",
":",
"self",
".",
"_origin",
"=",
"self",
".",
"_get_location_from_entity",
"(",
"self",
".",
"_origin_entity_id",
")",
"if",
"hasattr",
"(",
"self",
",",
"\"_destination_entity_id\"",
")",
":",
"self",
".",
"_destination",
"=",
"self",
".",
"_get_location_from_entity",
"(",
"self",
".",
"_destination_entity_id",
")",
"self",
".",
"_destination",
"=",
"self",
".",
"_resolve_zone",
"(",
"self",
".",
"_destination",
")",
"self",
".",
"_origin",
"=",
"self",
".",
"_resolve_zone",
"(",
"self",
".",
"_origin",
")",
"if",
"self",
".",
"_destination",
"is",
"not",
"None",
"and",
"self",
".",
"_origin",
"is",
"not",
"None",
":",
"self",
".",
"_matrix",
"=",
"self",
".",
"_client",
".",
"distance_matrix",
"(",
"self",
".",
"_origin",
",",
"self",
".",
"_destination",
",",
"*",
"*",
"options_copy",
")"
] | [
257,
4
] | [
289,
13
] | python | en | ['en', 'en', 'en'] | True |
GoogleTravelTimeSensor._get_location_from_entity | (self, entity_id) | Get the location from the entity state or attributes. | Get the location from the entity state or attributes. | def _get_location_from_entity(self, entity_id):
"""Get the location from the entity state or attributes."""
entity = self._hass.states.get(entity_id)
if entity is None:
_LOGGER.error("Unable to find entity %s", entity_id)
self.valid_api_connection = False
return None
# Check if the entity has location attributes
if location.has_location(entity):
return self._get_location_from_attributes(entity)
# Check if device is in a zone
zone_entity = self._hass.states.get("zone.%s" % entity.state)
if location.has_location(zone_entity):
_LOGGER.debug(
"%s is in %s, getting zone location", entity_id, zone_entity.entity_id
)
return self._get_location_from_attributes(zone_entity)
# If zone was not found in state then use the state as the location
if entity_id.startswith("sensor."):
return entity.state
# When everything fails just return nothing
return None | [
"def",
"_get_location_from_entity",
"(",
"self",
",",
"entity_id",
")",
":",
"entity",
"=",
"self",
".",
"_hass",
".",
"states",
".",
"get",
"(",
"entity_id",
")",
"if",
"entity",
"is",
"None",
":",
"_LOGGER",
".",
"error",
"(",
"\"Unable to find entity %s\"",
",",
"entity_id",
")",
"self",
".",
"valid_api_connection",
"=",
"False",
"return",
"None",
"# Check if the entity has location attributes",
"if",
"location",
".",
"has_location",
"(",
"entity",
")",
":",
"return",
"self",
".",
"_get_location_from_attributes",
"(",
"entity",
")",
"# Check if device is in a zone",
"zone_entity",
"=",
"self",
".",
"_hass",
".",
"states",
".",
"get",
"(",
"\"zone.%s\"",
"%",
"entity",
".",
"state",
")",
"if",
"location",
".",
"has_location",
"(",
"zone_entity",
")",
":",
"_LOGGER",
".",
"debug",
"(",
"\"%s is in %s, getting zone location\"",
",",
"entity_id",
",",
"zone_entity",
".",
"entity_id",
")",
"return",
"self",
".",
"_get_location_from_attributes",
"(",
"zone_entity",
")",
"# If zone was not found in state then use the state as the location",
"if",
"entity_id",
".",
"startswith",
"(",
"\"sensor.\"",
")",
":",
"return",
"entity",
".",
"state",
"# When everything fails just return nothing",
"return",
"None"
] | [
291,
4
] | [
317,
19
] | python | en | ['en', 'en', 'en'] | True |
GoogleTravelTimeSensor._get_location_from_attributes | (entity) | Get the lat/long string from an entities attributes. | Get the lat/long string from an entities attributes. | def _get_location_from_attributes(entity):
"""Get the lat/long string from an entities attributes."""
attr = entity.attributes
return f"{attr.get(ATTR_LATITUDE)},{attr.get(ATTR_LONGITUDE)}" | [
"def",
"_get_location_from_attributes",
"(",
"entity",
")",
":",
"attr",
"=",
"entity",
".",
"attributes",
"return",
"f\"{attr.get(ATTR_LATITUDE)},{attr.get(ATTR_LONGITUDE)}\""
] | [
320,
4
] | [
323,
70
] | python | en | ['en', 'en', 'en'] | True |
validate_input | (hass: core.HomeAssistant, data) | Validate the user input allows us to connect.
Data has the keys from DATA_SCHEMA with values provided by the user.
| Validate the user input allows us to connect. | def validate_input(hass: core.HomeAssistant, data):
"""Validate the user input allows us to connect.
Data has the keys from DATA_SCHEMA with values provided by the user.
"""
try:
ruckus = Ruckus(data[CONF_HOST], data[CONF_USERNAME], data[CONF_PASSWORD])
except AuthenticationError as error:
raise InvalidAuth from error
except ConnectionError as error:
raise CannotConnect from error
mesh_name = ruckus.mesh_name()
system_info = ruckus.system_info()
try:
host_serial = system_info[API_SYSTEM_OVERVIEW][API_SERIAL]
except KeyError as error:
raise CannotConnect from error
return {
"title": mesh_name,
"serial": host_serial,
} | [
"def",
"validate_input",
"(",
"hass",
":",
"core",
".",
"HomeAssistant",
",",
"data",
")",
":",
"try",
":",
"ruckus",
"=",
"Ruckus",
"(",
"data",
"[",
"CONF_HOST",
"]",
",",
"data",
"[",
"CONF_USERNAME",
"]",
",",
"data",
"[",
"CONF_PASSWORD",
"]",
")",
"except",
"AuthenticationError",
"as",
"error",
":",
"raise",
"InvalidAuth",
"from",
"error",
"except",
"ConnectionError",
"as",
"error",
":",
"raise",
"CannotConnect",
"from",
"error",
"mesh_name",
"=",
"ruckus",
".",
"mesh_name",
"(",
")",
"system_info",
"=",
"ruckus",
".",
"system_info",
"(",
")",
"try",
":",
"host_serial",
"=",
"system_info",
"[",
"API_SYSTEM_OVERVIEW",
"]",
"[",
"API_SERIAL",
"]",
"except",
"KeyError",
"as",
"error",
":",
"raise",
"CannotConnect",
"from",
"error",
"return",
"{",
"\"title\"",
":",
"mesh_name",
",",
"\"serial\"",
":",
"host_serial",
",",
"}"
] | [
21,
0
] | [
45,
5
] | python | en | ['en', 'en', 'en'] | True |
ConfigFlow.async_step_user | (self, user_input=None) | Handle the initial step. | Handle the initial step. | async def async_step_user(self, user_input=None):
"""Handle the initial step."""
errors = {}
if user_input is not None:
try:
info = await self.hass.async_add_executor_job(
validate_input, self.hass, user_input
)
except CannotConnect:
errors["base"] = "cannot_connect"
except InvalidAuth:
errors["base"] = "invalid_auth"
except Exception: # pylint: disable=broad-except
_LOGGER.exception("Unexpected exception")
errors["base"] = "unknown"
else:
await self.async_set_unique_id(info["serial"])
self._abort_if_unique_id_configured()
return self.async_create_entry(title=info["title"], data=user_input)
return self.async_show_form(
step_id="user", data_schema=DATA_SCHEMA, errors=errors
) | [
"async",
"def",
"async_step_user",
"(",
"self",
",",
"user_input",
"=",
"None",
")",
":",
"errors",
"=",
"{",
"}",
"if",
"user_input",
"is",
"not",
"None",
":",
"try",
":",
"info",
"=",
"await",
"self",
".",
"hass",
".",
"async_add_executor_job",
"(",
"validate_input",
",",
"self",
".",
"hass",
",",
"user_input",
")",
"except",
"CannotConnect",
":",
"errors",
"[",
"\"base\"",
"]",
"=",
"\"cannot_connect\"",
"except",
"InvalidAuth",
":",
"errors",
"[",
"\"base\"",
"]",
"=",
"\"invalid_auth\"",
"except",
"Exception",
":",
"# pylint: disable=broad-except",
"_LOGGER",
".",
"exception",
"(",
"\"Unexpected exception\"",
")",
"errors",
"[",
"\"base\"",
"]",
"=",
"\"unknown\"",
"else",
":",
"await",
"self",
".",
"async_set_unique_id",
"(",
"info",
"[",
"\"serial\"",
"]",
")",
"self",
".",
"_abort_if_unique_id_configured",
"(",
")",
"return",
"self",
".",
"async_create_entry",
"(",
"title",
"=",
"info",
"[",
"\"title\"",
"]",
",",
"data",
"=",
"user_input",
")",
"return",
"self",
".",
"async_show_form",
"(",
"step_id",
"=",
"\"user\"",
",",
"data_schema",
"=",
"DATA_SCHEMA",
",",
"errors",
"=",
"errors",
")"
] | [
54,
4
] | [
76,
9
] | python | en | ['en', 'en', 'en'] | True |
setup_platform | (hass, config, add_entities, discovery_info=None) | Set up the platform for a Skybell device. | Set up the platform for a Skybell device. | def setup_platform(hass, config, add_entities, discovery_info=None):
"""Set up the platform for a Skybell device."""
skybell = hass.data.get(SKYBELL_DOMAIN)
sensors = []
for sensor_type in config.get(CONF_MONITORED_CONDITIONS):
for device in skybell.get_devices():
sensors.append(SkybellSensor(device, sensor_type))
add_entities(sensors, True) | [
"def",
"setup_platform",
"(",
"hass",
",",
"config",
",",
"add_entities",
",",
"discovery_info",
"=",
"None",
")",
":",
"skybell",
"=",
"hass",
".",
"data",
".",
"get",
"(",
"SKYBELL_DOMAIN",
")",
"sensors",
"=",
"[",
"]",
"for",
"sensor_type",
"in",
"config",
".",
"get",
"(",
"CONF_MONITORED_CONDITIONS",
")",
":",
"for",
"device",
"in",
"skybell",
".",
"get_devices",
"(",
")",
":",
"sensors",
".",
"append",
"(",
"SkybellSensor",
"(",
"device",
",",
"sensor_type",
")",
")",
"add_entities",
"(",
"sensors",
",",
"True",
")"
] | [
28,
0
] | [
37,
31
] | python | en | ['en', 'en', 'en'] | True |
SkybellSensor.__init__ | (self, device, sensor_type) | Initialize a sensor for a Skybell device. | Initialize a sensor for a Skybell device. | def __init__(self, device, sensor_type):
"""Initialize a sensor for a Skybell device."""
super().__init__(device)
self._sensor_type = sensor_type
self._icon = "mdi:{}".format(SENSOR_TYPES[self._sensor_type][1])
self._name = "{} {}".format(
self._device.name, SENSOR_TYPES[self._sensor_type][0]
)
self._state = None | [
"def",
"__init__",
"(",
"self",
",",
"device",
",",
"sensor_type",
")",
":",
"super",
"(",
")",
".",
"__init__",
"(",
"device",
")",
"self",
".",
"_sensor_type",
"=",
"sensor_type",
"self",
".",
"_icon",
"=",
"\"mdi:{}\"",
".",
"format",
"(",
"SENSOR_TYPES",
"[",
"self",
".",
"_sensor_type",
"]",
"[",
"1",
"]",
")",
"self",
".",
"_name",
"=",
"\"{} {}\"",
".",
"format",
"(",
"self",
".",
"_device",
".",
"name",
",",
"SENSOR_TYPES",
"[",
"self",
".",
"_sensor_type",
"]",
"[",
"0",
"]",
")",
"self",
".",
"_state",
"=",
"None"
] | [
43,
4
] | [
51,
26
] | python | en | ['en', 'en', 'en'] | True |
SkybellSensor.name | (self) | Return the name of the sensor. | Return the name of the sensor. | def name(self):
"""Return the name of the sensor."""
return self._name | [
"def",
"name",
"(",
"self",
")",
":",
"return",
"self",
".",
"_name"
] | [
54,
4
] | [
56,
25
] | python | en | ['en', 'mi', 'en'] | True |
SkybellSensor.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"
] | [
59,
4
] | [
61,
26
] | python | en | ['en', 'en', 'en'] | True |
SkybellSensor.icon | (self) | Icon to use in the frontend, if any. | Icon to use in the frontend, if any. | def icon(self):
"""Icon to use in the frontend, if any."""
return self._icon | [
"def",
"icon",
"(",
"self",
")",
":",
"return",
"self",
".",
"_icon"
] | [
64,
4
] | [
66,
25
] | python | en | ['en', 'en', 'en'] | True |
SkybellSensor.update | (self) | Get the latest data and updates the state. | Get the latest data and updates the state. | def update(self):
"""Get the latest data and updates the state."""
super().update()
if self._sensor_type == "chime_level":
self._state = self._device.outdoor_chime_level | [
"def",
"update",
"(",
"self",
")",
":",
"super",
"(",
")",
".",
"update",
"(",
")",
"if",
"self",
".",
"_sensor_type",
"==",
"\"chime_level\"",
":",
"self",
".",
"_state",
"=",
"self",
".",
"_device",
".",
"outdoor_chime_level"
] | [
68,
4
] | [
73,
58
] | python | en | ['en', 'en', 'en'] | True |
attach | (hass: HomeAssistantType, obj: Any) | Recursively attach hass to all template instances in list and dict. | Recursively attach hass to all template instances in list and dict. | def attach(hass: HomeAssistantType, obj: Any) -> None:
"""Recursively attach hass to all template instances in list and dict."""
if isinstance(obj, list):
for child in obj:
attach(hass, child)
elif isinstance(obj, collections.abc.Mapping):
for child_key, child_value in obj.items():
attach(hass, child_key)
attach(hass, child_value)
elif isinstance(obj, Template):
obj.hass = hass | [
"def",
"attach",
"(",
"hass",
":",
"HomeAssistantType",
",",
"obj",
":",
"Any",
")",
"->",
"None",
":",
"if",
"isinstance",
"(",
"obj",
",",
"list",
")",
":",
"for",
"child",
"in",
"obj",
":",
"attach",
"(",
"hass",
",",
"child",
")",
"elif",
"isinstance",
"(",
"obj",
",",
"collections",
".",
"abc",
".",
"Mapping",
")",
":",
"for",
"child_key",
",",
"child_value",
"in",
"obj",
".",
"items",
"(",
")",
":",
"attach",
"(",
"hass",
",",
"child_key",
")",
"attach",
"(",
"hass",
",",
"child_value",
")",
"elif",
"isinstance",
"(",
"obj",
",",
"Template",
")",
":",
"obj",
".",
"hass",
"=",
"hass"
] | [
74,
0
] | [
84,
23
] | python | en | ['en', 'en', 'en'] | True |
render_complex | (value: Any, variables: TemplateVarsType = None) | Recursive template creator helper function. | Recursive template creator helper function. | def render_complex(value: Any, variables: TemplateVarsType = None) -> Any:
"""Recursive template creator helper function."""
if isinstance(value, list):
return [render_complex(item, variables) for item in value]
if isinstance(value, collections.abc.Mapping):
return {
render_complex(key, variables): render_complex(item, variables)
for key, item in value.items()
}
if isinstance(value, Template):
return value.async_render(variables)
return value | [
"def",
"render_complex",
"(",
"value",
":",
"Any",
",",
"variables",
":",
"TemplateVarsType",
"=",
"None",
")",
"->",
"Any",
":",
"if",
"isinstance",
"(",
"value",
",",
"list",
")",
":",
"return",
"[",
"render_complex",
"(",
"item",
",",
"variables",
")",
"for",
"item",
"in",
"value",
"]",
"if",
"isinstance",
"(",
"value",
",",
"collections",
".",
"abc",
".",
"Mapping",
")",
":",
"return",
"{",
"render_complex",
"(",
"key",
",",
"variables",
")",
":",
"render_complex",
"(",
"item",
",",
"variables",
")",
"for",
"key",
",",
"item",
"in",
"value",
".",
"items",
"(",
")",
"}",
"if",
"isinstance",
"(",
"value",
",",
"Template",
")",
":",
"return",
"value",
".",
"async_render",
"(",
"variables",
")",
"return",
"value"
] | [
87,
0
] | [
99,
16
] | python | en | ['en', 'nl', 'en'] | True |
is_complex | (value: Any) | Test if data structure is a complex template. | Test if data structure is a complex template. | def is_complex(value: Any) -> bool:
"""Test if data structure is a complex template."""
if isinstance(value, Template):
return True
if isinstance(value, list):
return any(is_complex(val) for val in value)
if isinstance(value, collections.abc.Mapping):
return any(is_complex(val) for val in value.keys()) or any(
is_complex(val) for val in value.values()
)
return False | [
"def",
"is_complex",
"(",
"value",
":",
"Any",
")",
"->",
"bool",
":",
"if",
"isinstance",
"(",
"value",
",",
"Template",
")",
":",
"return",
"True",
"if",
"isinstance",
"(",
"value",
",",
"list",
")",
":",
"return",
"any",
"(",
"is_complex",
"(",
"val",
")",
"for",
"val",
"in",
"value",
")",
"if",
"isinstance",
"(",
"value",
",",
"collections",
".",
"abc",
".",
"Mapping",
")",
":",
"return",
"any",
"(",
"is_complex",
"(",
"val",
")",
"for",
"val",
"in",
"value",
".",
"keys",
"(",
")",
")",
"or",
"any",
"(",
"is_complex",
"(",
"val",
")",
"for",
"val",
"in",
"value",
".",
"values",
"(",
")",
")",
"return",
"False"
] | [
102,
0
] | [
112,
16
] | python | en | ['en', 'en', 'en'] | True |
is_template_string | (maybe_template: str) | Check if the input is a Jinja2 template. | Check if the input is a Jinja2 template. | def is_template_string(maybe_template: str) -> bool:
"""Check if the input is a Jinja2 template."""
return _RE_JINJA_DELIMITERS.search(maybe_template) is not None | [
"def",
"is_template_string",
"(",
"maybe_template",
":",
"str",
")",
"->",
"bool",
":",
"return",
"_RE_JINJA_DELIMITERS",
".",
"search",
"(",
"maybe_template",
")",
"is",
"not",
"None"
] | [
115,
0
] | [
117,
66
] | python | en | ['en', 'en', 'en'] | True |
gen_result_wrapper | (kls) | Generate a result wrapper. | Generate a result wrapper. | def gen_result_wrapper(kls):
"""Generate a result wrapper."""
class Wrapper(kls, ResultWrapper):
"""Wrapper of a kls that can store render_result."""
def __init__(self, *args: tuple, render_result: Optional[str] = None) -> None:
super().__init__(*args)
self.render_result = render_result
def __str__(self) -> str:
if self.render_result is None:
# Can't get set repr to work
if kls is set:
return str(set(self))
return kls.__str__(self)
return self.render_result
return Wrapper | [
"def",
"gen_result_wrapper",
"(",
"kls",
")",
":",
"class",
"Wrapper",
"(",
"kls",
",",
"ResultWrapper",
")",
":",
"\"\"\"Wrapper of a kls that can store render_result.\"\"\"",
"def",
"__init__",
"(",
"self",
",",
"*",
"args",
":",
"tuple",
",",
"render_result",
":",
"Optional",
"[",
"str",
"]",
"=",
"None",
")",
"->",
"None",
":",
"super",
"(",
")",
".",
"__init__",
"(",
"*",
"args",
")",
"self",
".",
"render_result",
"=",
"render_result",
"def",
"__str__",
"(",
"self",
")",
"->",
"str",
":",
"if",
"self",
".",
"render_result",
"is",
"None",
":",
"# Can't get set repr to work",
"if",
"kls",
"is",
"set",
":",
"return",
"str",
"(",
"set",
"(",
"self",
")",
")",
"return",
"kls",
".",
"__str__",
"(",
"self",
")",
"return",
"self",
".",
"render_result",
"return",
"Wrapper"
] | [
126,
0
] | [
146,
18
] | python | en | ['en', 'en', 'en'] | True |
_state_generator | (hass: HomeAssistantType, domain: Optional[str]) | State generator for a domain or all states. | State generator for a domain or all states. | def _state_generator(hass: HomeAssistantType, domain: Optional[str]) -> Generator:
"""State generator for a domain or all states."""
for state in sorted(hass.states.async_all(domain), key=attrgetter("entity_id")):
yield TemplateState(hass, state, collect=False) | [
"def",
"_state_generator",
"(",
"hass",
":",
"HomeAssistantType",
",",
"domain",
":",
"Optional",
"[",
"str",
"]",
")",
"->",
"Generator",
":",
"for",
"state",
"in",
"sorted",
"(",
"hass",
".",
"states",
".",
"async_all",
"(",
"domain",
")",
",",
"key",
"=",
"attrgetter",
"(",
"\"entity_id\"",
")",
")",
":",
"yield",
"TemplateState",
"(",
"hass",
",",
"state",
",",
"collect",
"=",
"False",
")"
] | [
758,
0
] | [
761,
55
] | python | en | ['en', 'en', 'en'] | True |
_resolve_state | (
hass: HomeAssistantType, entity_id_or_state: Any
) | Return state or entity_id if given. | Return state or entity_id if given. | def _resolve_state(
hass: HomeAssistantType, entity_id_or_state: Any
) -> Union[State, TemplateState, None]:
"""Return state or entity_id if given."""
if isinstance(entity_id_or_state, State):
return entity_id_or_state
if isinstance(entity_id_or_state, str):
return _get_state(hass, entity_id_or_state)
return None | [
"def",
"_resolve_state",
"(",
"hass",
":",
"HomeAssistantType",
",",
"entity_id_or_state",
":",
"Any",
")",
"->",
"Union",
"[",
"State",
",",
"TemplateState",
",",
"None",
"]",
":",
"if",
"isinstance",
"(",
"entity_id_or_state",
",",
"State",
")",
":",
"return",
"entity_id_or_state",
"if",
"isinstance",
"(",
"entity_id_or_state",
",",
"str",
")",
":",
"return",
"_get_state",
"(",
"hass",
",",
"entity_id_or_state",
")",
"return",
"None"
] | [
788,
0
] | [
796,
15
] | python | en | ['en', 'en', 'en'] | True |
result_as_boolean | (template_result: Optional[str]) | Convert the template result to a boolean.
True/not 0/'1'/'true'/'yes'/'on'/'enable' are considered truthy
False/0/None/'0'/'false'/'no'/'off'/'disable' are considered falsy
| Convert the template result to a boolean. | def result_as_boolean(template_result: Optional[str]) -> bool:
"""Convert the template result to a boolean.
True/not 0/'1'/'true'/'yes'/'on'/'enable' are considered truthy
False/0/None/'0'/'false'/'no'/'off'/'disable' are considered falsy
"""
try:
# Import here, not at top-level to avoid circular import
from homeassistant.helpers import ( # pylint: disable=import-outside-toplevel
config_validation as cv,
)
return cv.boolean(template_result)
except vol.Invalid:
return False | [
"def",
"result_as_boolean",
"(",
"template_result",
":",
"Optional",
"[",
"str",
"]",
")",
"->",
"bool",
":",
"try",
":",
"# Import here, not at top-level to avoid circular import",
"from",
"homeassistant",
".",
"helpers",
"import",
"(",
"# pylint: disable=import-outside-toplevel",
"config_validation",
"as",
"cv",
",",
")",
"return",
"cv",
".",
"boolean",
"(",
"template_result",
")",
"except",
"vol",
".",
"Invalid",
":",
"return",
"False"
] | [
799,
0
] | [
814,
20
] | python | en | ['en', 'en', 'en'] | True |
Subsets and Splits