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 |
---|---|---|---|---|---|---|---|---|---|---|---|
test_coordinates_function_as_attributes | (hass) | Test coordinates function. | Test coordinates function. | async def test_coordinates_function_as_attributes(hass):
"""Test coordinates function."""
hass.states.async_set(
"test.object", "happy", {"latitude": 32.87336, "longitude": -117.22943}
)
assert location.find_coordinates(hass, "test.object") == "32.87336,-117.22943" | [
"async",
"def",
"test_coordinates_function_as_attributes",
"(",
"hass",
")",
":",
"hass",
".",
"states",
".",
"async_set",
"(",
"\"test.object\"",
",",
"\"happy\"",
",",
"{",
"\"latitude\"",
":",
"32.87336",
",",
"\"longitude\"",
":",
"-",
"117.22943",
"}",
")",
"assert",
"location",
".",
"find_coordinates",
"(",
"hass",
",",
"\"test.object\"",
")",
"==",
"\"32.87336,-117.22943\""
] | [
47,
0
] | [
52,
82
] | python | en | ['en', 'en', 'en'] | True |
test_coordinates_function_as_state | (hass) | Test coordinates function. | Test coordinates function. | async def test_coordinates_function_as_state(hass):
"""Test coordinates function."""
hass.states.async_set("test.object", "32.87336,-117.22943")
assert location.find_coordinates(hass, "test.object") == "32.87336,-117.22943" | [
"async",
"def",
"test_coordinates_function_as_state",
"(",
"hass",
")",
":",
"hass",
".",
"states",
".",
"async_set",
"(",
"\"test.object\"",
",",
"\"32.87336,-117.22943\"",
")",
"assert",
"location",
".",
"find_coordinates",
"(",
"hass",
",",
"\"test.object\"",
")",
"==",
"\"32.87336,-117.22943\""
] | [
55,
0
] | [
58,
82
] | python | en | ['en', 'en', 'en'] | True |
test_coordinates_function_device_tracker_in_zone | (hass) | Test coordinates function. | Test coordinates function. | async def test_coordinates_function_device_tracker_in_zone(hass):
"""Test coordinates function."""
hass.states.async_set(
"zone.home",
"zoning",
{"latitude": 32.87336, "longitude": -117.22943},
)
hass.states.async_set("device_tracker.device", "home")
assert (
location.find_coordinates(hass, "device_tracker.device")
== "32.87336,-117.22943"
) | [
"async",
"def",
"test_coordinates_function_device_tracker_in_zone",
"(",
"hass",
")",
":",
"hass",
".",
"states",
".",
"async_set",
"(",
"\"zone.home\"",
",",
"\"zoning\"",
",",
"{",
"\"latitude\"",
":",
"32.87336",
",",
"\"longitude\"",
":",
"-",
"117.22943",
"}",
",",
")",
"hass",
".",
"states",
".",
"async_set",
"(",
"\"device_tracker.device\"",
",",
"\"home\"",
")",
"assert",
"(",
"location",
".",
"find_coordinates",
"(",
"hass",
",",
"\"device_tracker.device\"",
")",
"==",
"\"32.87336,-117.22943\"",
")"
] | [
61,
0
] | [
72,
5
] | python | en | ['en', 'en', 'en'] | True |
test_coordinates_function_device_tracker_from_input_select | (hass) | Test coordinates function. | Test coordinates function. | async def test_coordinates_function_device_tracker_from_input_select(hass):
"""Test coordinates function."""
hass.states.async_set(
"input_select.select",
"device_tracker.device",
{"options": "device_tracker.device"},
)
hass.states.async_set("device_tracker.device", "32.87336,-117.22943")
assert (
location.find_coordinates(hass, "input_select.select") == "32.87336,-117.22943"
) | [
"async",
"def",
"test_coordinates_function_device_tracker_from_input_select",
"(",
"hass",
")",
":",
"hass",
".",
"states",
".",
"async_set",
"(",
"\"input_select.select\"",
",",
"\"device_tracker.device\"",
",",
"{",
"\"options\"",
":",
"\"device_tracker.device\"",
"}",
",",
")",
"hass",
".",
"states",
".",
"async_set",
"(",
"\"device_tracker.device\"",
",",
"\"32.87336,-117.22943\"",
")",
"assert",
"(",
"location",
".",
"find_coordinates",
"(",
"hass",
",",
"\"input_select.select\"",
")",
"==",
"\"32.87336,-117.22943\"",
")"
] | [
75,
0
] | [
85,
5
] | python | en | ['en', 'en', 'en'] | True |
test_coordinates_function_returns_none_on_recursion | (hass) | Test coordinates function. | Test coordinates function. | def test_coordinates_function_returns_none_on_recursion(hass):
"""Test coordinates function."""
hass.states.async_set(
"test.first",
"test.second",
)
hass.states.async_set("test.second", "test.first")
assert location.find_coordinates(hass, "test.first") is None | [
"def",
"test_coordinates_function_returns_none_on_recursion",
"(",
"hass",
")",
":",
"hass",
".",
"states",
".",
"async_set",
"(",
"\"test.first\"",
",",
"\"test.second\"",
",",
")",
"hass",
".",
"states",
".",
"async_set",
"(",
"\"test.second\"",
",",
"\"test.first\"",
")",
"assert",
"location",
".",
"find_coordinates",
"(",
"hass",
",",
"\"test.first\"",
")",
"is",
"None"
] | [
88,
0
] | [
95,
64
] | python | en | ['en', 'en', 'en'] | True |
test_coordinates_function_returns_none_if_invalid_coord | (hass) | Test test_coordinates function. | Test test_coordinates function. | async def test_coordinates_function_returns_none_if_invalid_coord(hass):
"""Test test_coordinates function."""
hass.states.async_set(
"test.object",
"abc",
)
assert location.find_coordinates(hass, "test.object") is None | [
"async",
"def",
"test_coordinates_function_returns_none_if_invalid_coord",
"(",
"hass",
")",
":",
"hass",
".",
"states",
".",
"async_set",
"(",
"\"test.object\"",
",",
"\"abc\"",
",",
")",
"assert",
"location",
".",
"find_coordinates",
"(",
"hass",
",",
"\"test.object\"",
")",
"is",
"None"
] | [
98,
0
] | [
104,
65
] | python | en | ['en', 'de', 'en'] | True |
test_coordinates_function_returns_none_if_invalid_input | (hass) | Test test_coordinates function. | Test test_coordinates function. | def test_coordinates_function_returns_none_if_invalid_input(hass):
"""Test test_coordinates function."""
assert location.find_coordinates(hass, "test.abc") is None | [
"def",
"test_coordinates_function_returns_none_if_invalid_input",
"(",
"hass",
")",
":",
"assert",
"location",
".",
"find_coordinates",
"(",
"hass",
",",
"\"test.abc\"",
")",
"is",
"None"
] | [
107,
0
] | [
109,
62
] | python | en | ['en', 'de', '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"
] | [
113,
0
] | [
115,
8
] | python | en | ['da', 'en', 'en'] | True |
geofency_client | (loop, hass, aiohttp_client) | Geofency mock client (unauthenticated). | Geofency mock client (unauthenticated). | async def geofency_client(loop, hass, aiohttp_client):
"""Geofency mock client (unauthenticated)."""
assert await async_setup_component(hass, "persistent_notification", {})
assert await async_setup_component(
hass, DOMAIN, {DOMAIN: {CONF_MOBILE_BEACONS: ["Car 1"]}}
)
await hass.async_block_till_done()
with patch("homeassistant.components.device_tracker.legacy.update_config"):
return await aiohttp_client(hass.http.app) | [
"async",
"def",
"geofency_client",
"(",
"loop",
",",
"hass",
",",
"aiohttp_client",
")",
":",
"assert",
"await",
"async_setup_component",
"(",
"hass",
",",
"\"persistent_notification\"",
",",
"{",
"}",
")",
"assert",
"await",
"async_setup_component",
"(",
"hass",
",",
"DOMAIN",
",",
"{",
"DOMAIN",
":",
"{",
"CONF_MOBILE_BEACONS",
":",
"[",
"\"Car 1\"",
"]",
"}",
"}",
")",
"await",
"hass",
".",
"async_block_till_done",
"(",
")",
"with",
"patch",
"(",
"\"homeassistant.components.device_tracker.legacy.update_config\"",
")",
":",
"return",
"await",
"aiohttp_client",
"(",
"hass",
".",
"http",
".",
"app",
")"
] | [
119,
0
] | [
129,
50
] | python | en | ['en', 'en', 'sw'] | True |
setup_zones | (loop, hass) | Set up Zone config in HA. | Set up Zone config in HA. | async def setup_zones(loop, hass):
"""Set up Zone config in HA."""
assert await async_setup_component(
hass,
zone.DOMAIN,
{
"zone": {
"name": "Home",
"latitude": HOME_LATITUDE,
"longitude": HOME_LONGITUDE,
"radius": 100,
}
},
)
await hass.async_block_till_done() | [
"async",
"def",
"setup_zones",
"(",
"loop",
",",
"hass",
")",
":",
"assert",
"await",
"async_setup_component",
"(",
"hass",
",",
"zone",
".",
"DOMAIN",
",",
"{",
"\"zone\"",
":",
"{",
"\"name\"",
":",
"\"Home\"",
",",
"\"latitude\"",
":",
"HOME_LATITUDE",
",",
"\"longitude\"",
":",
"HOME_LONGITUDE",
",",
"\"radius\"",
":",
"100",
",",
"}",
"}",
",",
")",
"await",
"hass",
".",
"async_block_till_done",
"(",
")"
] | [
133,
0
] | [
147,
38
] | python | en | ['en', 'en', 'en'] | True |
webhook_id | (hass, geofency_client) | Initialize the Geofency component and get the webhook_id. | Initialize the Geofency component and get the webhook_id. | async def webhook_id(hass, geofency_client):
"""Initialize the Geofency component and get the webhook_id."""
await async_process_ha_core_config(
hass,
{"internal_url": "http://example.local:8123"},
)
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": "user"}
)
assert result["type"] == data_entry_flow.RESULT_TYPE_FORM, result
result = await hass.config_entries.flow.async_configure(result["flow_id"], {})
assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY
await hass.async_block_till_done()
return result["result"].data["webhook_id"] | [
"async",
"def",
"webhook_id",
"(",
"hass",
",",
"geofency_client",
")",
":",
"await",
"async_process_ha_core_config",
"(",
"hass",
",",
"{",
"\"internal_url\"",
":",
"\"http://example.local:8123\"",
"}",
",",
")",
"result",
"=",
"await",
"hass",
".",
"config_entries",
".",
"flow",
".",
"async_init",
"(",
"DOMAIN",
",",
"context",
"=",
"{",
"\"source\"",
":",
"\"user\"",
"}",
")",
"assert",
"result",
"[",
"\"type\"",
"]",
"==",
"data_entry_flow",
".",
"RESULT_TYPE_FORM",
",",
"result",
"result",
"=",
"await",
"hass",
".",
"config_entries",
".",
"flow",
".",
"async_configure",
"(",
"result",
"[",
"\"flow_id\"",
"]",
",",
"{",
"}",
")",
"assert",
"result",
"[",
"\"type\"",
"]",
"==",
"data_entry_flow",
".",
"RESULT_TYPE_CREATE_ENTRY",
"await",
"hass",
".",
"async_block_till_done",
"(",
")",
"return",
"result",
"[",
"\"result\"",
"]",
".",
"data",
"[",
"\"webhook_id\"",
"]"
] | [
151,
0
] | [
166,
46
] | python | en | ['en', 'en', 'en'] | True |
test_data_validation | (geofency_client, webhook_id) | Test data validation. | Test data validation. | async def test_data_validation(geofency_client, webhook_id):
"""Test data validation."""
url = f"/api/webhook/{webhook_id}"
# No data
req = await geofency_client.post(url)
assert req.status == HTTP_UNPROCESSABLE_ENTITY
missing_attributes = ["address", "device", "entry", "latitude", "longitude", "name"]
# missing attributes
for attribute in missing_attributes:
copy = GPS_ENTER_HOME.copy()
del copy[attribute]
req = await geofency_client.post(url, data=copy)
assert req.status == HTTP_UNPROCESSABLE_ENTITY | [
"async",
"def",
"test_data_validation",
"(",
"geofency_client",
",",
"webhook_id",
")",
":",
"url",
"=",
"f\"/api/webhook/{webhook_id}\"",
"# No data",
"req",
"=",
"await",
"geofency_client",
".",
"post",
"(",
"url",
")",
"assert",
"req",
".",
"status",
"==",
"HTTP_UNPROCESSABLE_ENTITY",
"missing_attributes",
"=",
"[",
"\"address\"",
",",
"\"device\"",
",",
"\"entry\"",
",",
"\"latitude\"",
",",
"\"longitude\"",
",",
"\"name\"",
"]",
"# missing attributes",
"for",
"attribute",
"in",
"missing_attributes",
":",
"copy",
"=",
"GPS_ENTER_HOME",
".",
"copy",
"(",
")",
"del",
"copy",
"[",
"attribute",
"]",
"req",
"=",
"await",
"geofency_client",
".",
"post",
"(",
"url",
",",
"data",
"=",
"copy",
")",
"assert",
"req",
".",
"status",
"==",
"HTTP_UNPROCESSABLE_ENTITY"
] | [
169,
0
] | [
184,
54
] | python | en | ['fr', 'ja', 'en'] | False |
test_gps_enter_and_exit_home | (hass, geofency_client, webhook_id) | Test GPS based zone enter and exit. | Test GPS based zone enter and exit. | async def test_gps_enter_and_exit_home(hass, geofency_client, webhook_id):
"""Test GPS based zone enter and exit."""
url = f"/api/webhook/{webhook_id}"
# Enter the Home zone
req = await geofency_client.post(url, data=GPS_ENTER_HOME)
await hass.async_block_till_done()
assert req.status == HTTP_OK
device_name = slugify(GPS_ENTER_HOME["device"])
state_name = hass.states.get(f"device_tracker.{device_name}").state
assert STATE_HOME == state_name
# Exit the Home zone
req = await geofency_client.post(url, data=GPS_EXIT_HOME)
await hass.async_block_till_done()
assert req.status == HTTP_OK
device_name = slugify(GPS_EXIT_HOME["device"])
state_name = hass.states.get(f"device_tracker.{device_name}").state
assert STATE_NOT_HOME == state_name
# Exit the Home zone with "Send Current Position" enabled
data = GPS_EXIT_HOME.copy()
data["currentLatitude"] = NOT_HOME_LATITUDE
data["currentLongitude"] = NOT_HOME_LONGITUDE
req = await geofency_client.post(url, data=data)
await hass.async_block_till_done()
assert req.status == HTTP_OK
device_name = slugify(GPS_EXIT_HOME["device"])
current_latitude = hass.states.get(f"device_tracker.{device_name}").attributes[
"latitude"
]
assert NOT_HOME_LATITUDE == current_latitude
current_longitude = hass.states.get(f"device_tracker.{device_name}").attributes[
"longitude"
]
assert NOT_HOME_LONGITUDE == current_longitude
dev_reg = await hass.helpers.device_registry.async_get_registry()
assert len(dev_reg.devices) == 1
ent_reg = await hass.helpers.entity_registry.async_get_registry()
assert len(ent_reg.entities) == 1 | [
"async",
"def",
"test_gps_enter_and_exit_home",
"(",
"hass",
",",
"geofency_client",
",",
"webhook_id",
")",
":",
"url",
"=",
"f\"/api/webhook/{webhook_id}\"",
"# Enter the Home zone",
"req",
"=",
"await",
"geofency_client",
".",
"post",
"(",
"url",
",",
"data",
"=",
"GPS_ENTER_HOME",
")",
"await",
"hass",
".",
"async_block_till_done",
"(",
")",
"assert",
"req",
".",
"status",
"==",
"HTTP_OK",
"device_name",
"=",
"slugify",
"(",
"GPS_ENTER_HOME",
"[",
"\"device\"",
"]",
")",
"state_name",
"=",
"hass",
".",
"states",
".",
"get",
"(",
"f\"device_tracker.{device_name}\"",
")",
".",
"state",
"assert",
"STATE_HOME",
"==",
"state_name",
"# Exit the Home zone",
"req",
"=",
"await",
"geofency_client",
".",
"post",
"(",
"url",
",",
"data",
"=",
"GPS_EXIT_HOME",
")",
"await",
"hass",
".",
"async_block_till_done",
"(",
")",
"assert",
"req",
".",
"status",
"==",
"HTTP_OK",
"device_name",
"=",
"slugify",
"(",
"GPS_EXIT_HOME",
"[",
"\"device\"",
"]",
")",
"state_name",
"=",
"hass",
".",
"states",
".",
"get",
"(",
"f\"device_tracker.{device_name}\"",
")",
".",
"state",
"assert",
"STATE_NOT_HOME",
"==",
"state_name",
"# Exit the Home zone with \"Send Current Position\" enabled",
"data",
"=",
"GPS_EXIT_HOME",
".",
"copy",
"(",
")",
"data",
"[",
"\"currentLatitude\"",
"]",
"=",
"NOT_HOME_LATITUDE",
"data",
"[",
"\"currentLongitude\"",
"]",
"=",
"NOT_HOME_LONGITUDE",
"req",
"=",
"await",
"geofency_client",
".",
"post",
"(",
"url",
",",
"data",
"=",
"data",
")",
"await",
"hass",
".",
"async_block_till_done",
"(",
")",
"assert",
"req",
".",
"status",
"==",
"HTTP_OK",
"device_name",
"=",
"slugify",
"(",
"GPS_EXIT_HOME",
"[",
"\"device\"",
"]",
")",
"current_latitude",
"=",
"hass",
".",
"states",
".",
"get",
"(",
"f\"device_tracker.{device_name}\"",
")",
".",
"attributes",
"[",
"\"latitude\"",
"]",
"assert",
"NOT_HOME_LATITUDE",
"==",
"current_latitude",
"current_longitude",
"=",
"hass",
".",
"states",
".",
"get",
"(",
"f\"device_tracker.{device_name}\"",
")",
".",
"attributes",
"[",
"\"longitude\"",
"]",
"assert",
"NOT_HOME_LONGITUDE",
"==",
"current_longitude",
"dev_reg",
"=",
"await",
"hass",
".",
"helpers",
".",
"device_registry",
".",
"async_get_registry",
"(",
")",
"assert",
"len",
"(",
"dev_reg",
".",
"devices",
")",
"==",
"1",
"ent_reg",
"=",
"await",
"hass",
".",
"helpers",
".",
"entity_registry",
".",
"async_get_registry",
"(",
")",
"assert",
"len",
"(",
"ent_reg",
".",
"entities",
")",
"==",
"1"
] | [
187,
0
] | [
229,
37
] | python | en | ['en', 'en', 'en'] | True |
test_beacon_enter_and_exit_home | (hass, geofency_client, webhook_id) | Test iBeacon based zone enter and exit - a.k.a stationary iBeacon. | Test iBeacon based zone enter and exit - a.k.a stationary iBeacon. | async def test_beacon_enter_and_exit_home(hass, geofency_client, webhook_id):
"""Test iBeacon based zone enter and exit - a.k.a stationary iBeacon."""
url = f"/api/webhook/{webhook_id}"
# Enter the Home zone
req = await geofency_client.post(url, data=BEACON_ENTER_HOME)
await hass.async_block_till_done()
assert req.status == HTTP_OK
device_name = slugify(f"beacon_{BEACON_ENTER_HOME['name']}")
state_name = hass.states.get(f"device_tracker.{device_name}").state
assert STATE_HOME == state_name
# Exit the Home zone
req = await geofency_client.post(url, data=BEACON_EXIT_HOME)
await hass.async_block_till_done()
assert req.status == HTTP_OK
device_name = slugify(f"beacon_{BEACON_ENTER_HOME['name']}")
state_name = hass.states.get(f"device_tracker.{device_name}").state
assert STATE_NOT_HOME == state_name | [
"async",
"def",
"test_beacon_enter_and_exit_home",
"(",
"hass",
",",
"geofency_client",
",",
"webhook_id",
")",
":",
"url",
"=",
"f\"/api/webhook/{webhook_id}\"",
"# Enter the Home zone",
"req",
"=",
"await",
"geofency_client",
".",
"post",
"(",
"url",
",",
"data",
"=",
"BEACON_ENTER_HOME",
")",
"await",
"hass",
".",
"async_block_till_done",
"(",
")",
"assert",
"req",
".",
"status",
"==",
"HTTP_OK",
"device_name",
"=",
"slugify",
"(",
"f\"beacon_{BEACON_ENTER_HOME['name']}\"",
")",
"state_name",
"=",
"hass",
".",
"states",
".",
"get",
"(",
"f\"device_tracker.{device_name}\"",
")",
".",
"state",
"assert",
"STATE_HOME",
"==",
"state_name",
"# Exit the Home zone",
"req",
"=",
"await",
"geofency_client",
".",
"post",
"(",
"url",
",",
"data",
"=",
"BEACON_EXIT_HOME",
")",
"await",
"hass",
".",
"async_block_till_done",
"(",
")",
"assert",
"req",
".",
"status",
"==",
"HTTP_OK",
"device_name",
"=",
"slugify",
"(",
"f\"beacon_{BEACON_ENTER_HOME['name']}\"",
")",
"state_name",
"=",
"hass",
".",
"states",
".",
"get",
"(",
"f\"device_tracker.{device_name}\"",
")",
".",
"state",
"assert",
"STATE_NOT_HOME",
"==",
"state_name"
] | [
232,
0
] | [
250,
39
] | python | en | ['en', 'en', 'en'] | True |
test_beacon_enter_and_exit_car | (hass, geofency_client, webhook_id) | Test use of mobile iBeacon. | Test use of mobile iBeacon. | async def test_beacon_enter_and_exit_car(hass, geofency_client, webhook_id):
"""Test use of mobile iBeacon."""
url = f"/api/webhook/{webhook_id}"
# Enter the Car away from Home zone
req = await geofency_client.post(url, data=BEACON_ENTER_CAR)
await hass.async_block_till_done()
assert req.status == HTTP_OK
device_name = slugify(f"beacon_{BEACON_ENTER_CAR['name']}")
state_name = hass.states.get(f"device_tracker.{device_name}").state
assert STATE_NOT_HOME == state_name
# Exit the Car away from Home zone
req = await geofency_client.post(url, data=BEACON_EXIT_CAR)
await hass.async_block_till_done()
assert req.status == HTTP_OK
device_name = slugify(f"beacon_{BEACON_ENTER_CAR['name']}")
state_name = hass.states.get(f"device_tracker.{device_name}").state
assert STATE_NOT_HOME == state_name
# Enter the Car in the Home zone
data = BEACON_ENTER_CAR.copy()
data["latitude"] = HOME_LATITUDE
data["longitude"] = HOME_LONGITUDE
req = await geofency_client.post(url, data=data)
await hass.async_block_till_done()
assert req.status == HTTP_OK
device_name = slugify(f"beacon_{data['name']}")
state_name = hass.states.get(f"device_tracker.{device_name}").state
assert STATE_HOME == state_name
# Exit the Car in the Home zone
req = await geofency_client.post(url, data=data)
await hass.async_block_till_done()
assert req.status == HTTP_OK
device_name = slugify(f"beacon_{data['name']}")
state_name = hass.states.get(f"device_tracker.{device_name}").state
assert STATE_HOME == state_name | [
"async",
"def",
"test_beacon_enter_and_exit_car",
"(",
"hass",
",",
"geofency_client",
",",
"webhook_id",
")",
":",
"url",
"=",
"f\"/api/webhook/{webhook_id}\"",
"# Enter the Car away from Home zone",
"req",
"=",
"await",
"geofency_client",
".",
"post",
"(",
"url",
",",
"data",
"=",
"BEACON_ENTER_CAR",
")",
"await",
"hass",
".",
"async_block_till_done",
"(",
")",
"assert",
"req",
".",
"status",
"==",
"HTTP_OK",
"device_name",
"=",
"slugify",
"(",
"f\"beacon_{BEACON_ENTER_CAR['name']}\"",
")",
"state_name",
"=",
"hass",
".",
"states",
".",
"get",
"(",
"f\"device_tracker.{device_name}\"",
")",
".",
"state",
"assert",
"STATE_NOT_HOME",
"==",
"state_name",
"# Exit the Car away from Home zone",
"req",
"=",
"await",
"geofency_client",
".",
"post",
"(",
"url",
",",
"data",
"=",
"BEACON_EXIT_CAR",
")",
"await",
"hass",
".",
"async_block_till_done",
"(",
")",
"assert",
"req",
".",
"status",
"==",
"HTTP_OK",
"device_name",
"=",
"slugify",
"(",
"f\"beacon_{BEACON_ENTER_CAR['name']}\"",
")",
"state_name",
"=",
"hass",
".",
"states",
".",
"get",
"(",
"f\"device_tracker.{device_name}\"",
")",
".",
"state",
"assert",
"STATE_NOT_HOME",
"==",
"state_name",
"# Enter the Car in the Home zone",
"data",
"=",
"BEACON_ENTER_CAR",
".",
"copy",
"(",
")",
"data",
"[",
"\"latitude\"",
"]",
"=",
"HOME_LATITUDE",
"data",
"[",
"\"longitude\"",
"]",
"=",
"HOME_LONGITUDE",
"req",
"=",
"await",
"geofency_client",
".",
"post",
"(",
"url",
",",
"data",
"=",
"data",
")",
"await",
"hass",
".",
"async_block_till_done",
"(",
")",
"assert",
"req",
".",
"status",
"==",
"HTTP_OK",
"device_name",
"=",
"slugify",
"(",
"f\"beacon_{data['name']}\"",
")",
"state_name",
"=",
"hass",
".",
"states",
".",
"get",
"(",
"f\"device_tracker.{device_name}\"",
")",
".",
"state",
"assert",
"STATE_HOME",
"==",
"state_name",
"# Exit the Car in the Home zone",
"req",
"=",
"await",
"geofency_client",
".",
"post",
"(",
"url",
",",
"data",
"=",
"data",
")",
"await",
"hass",
".",
"async_block_till_done",
"(",
")",
"assert",
"req",
".",
"status",
"==",
"HTTP_OK",
"device_name",
"=",
"slugify",
"(",
"f\"beacon_{data['name']}\"",
")",
"state_name",
"=",
"hass",
".",
"states",
".",
"get",
"(",
"f\"device_tracker.{device_name}\"",
")",
".",
"state",
"assert",
"STATE_HOME",
"==",
"state_name"
] | [
253,
0
] | [
290,
35
] | python | en | ['en', 'en', 'en'] | True |
test_load_unload_entry | (hass, geofency_client, webhook_id) | Test that the appropriate dispatch signals are added and removed. | Test that the appropriate dispatch signals are added and removed. | async def test_load_unload_entry(hass, geofency_client, webhook_id):
"""Test that the appropriate dispatch signals are added and removed."""
url = f"/api/webhook/{webhook_id}"
# Enter the Home zone
req = await geofency_client.post(url, data=GPS_ENTER_HOME)
await hass.async_block_till_done()
assert req.status == HTTP_OK
device_name = slugify(GPS_ENTER_HOME["device"])
state_1 = hass.states.get(f"device_tracker.{device_name}")
assert STATE_HOME == state_1.state
assert len(hass.data[DOMAIN]["devices"]) == 1
entry = hass.config_entries.async_entries(DOMAIN)[0]
assert await hass.config_entries.async_unload(entry.entry_id)
await hass.async_block_till_done()
assert len(hass.data[DOMAIN]["devices"]) == 0
assert await hass.config_entries.async_setup(entry.entry_id)
await hass.async_block_till_done()
state_2 = hass.states.get(f"device_tracker.{device_name}")
assert state_2 is not None
assert state_1 is not state_2
assert STATE_HOME == state_2.state
assert state_2.attributes[ATTR_LATITUDE] == HOME_LATITUDE
assert state_2.attributes[ATTR_LONGITUDE] == HOME_LONGITUDE | [
"async",
"def",
"test_load_unload_entry",
"(",
"hass",
",",
"geofency_client",
",",
"webhook_id",
")",
":",
"url",
"=",
"f\"/api/webhook/{webhook_id}\"",
"# Enter the Home zone",
"req",
"=",
"await",
"geofency_client",
".",
"post",
"(",
"url",
",",
"data",
"=",
"GPS_ENTER_HOME",
")",
"await",
"hass",
".",
"async_block_till_done",
"(",
")",
"assert",
"req",
".",
"status",
"==",
"HTTP_OK",
"device_name",
"=",
"slugify",
"(",
"GPS_ENTER_HOME",
"[",
"\"device\"",
"]",
")",
"state_1",
"=",
"hass",
".",
"states",
".",
"get",
"(",
"f\"device_tracker.{device_name}\"",
")",
"assert",
"STATE_HOME",
"==",
"state_1",
".",
"state",
"assert",
"len",
"(",
"hass",
".",
"data",
"[",
"DOMAIN",
"]",
"[",
"\"devices\"",
"]",
")",
"==",
"1",
"entry",
"=",
"hass",
".",
"config_entries",
".",
"async_entries",
"(",
"DOMAIN",
")",
"[",
"0",
"]",
"assert",
"await",
"hass",
".",
"config_entries",
".",
"async_unload",
"(",
"entry",
".",
"entry_id",
")",
"await",
"hass",
".",
"async_block_till_done",
"(",
")",
"assert",
"len",
"(",
"hass",
".",
"data",
"[",
"DOMAIN",
"]",
"[",
"\"devices\"",
"]",
")",
"==",
"0",
"assert",
"await",
"hass",
".",
"config_entries",
".",
"async_setup",
"(",
"entry",
".",
"entry_id",
")",
"await",
"hass",
".",
"async_block_till_done",
"(",
")",
"state_2",
"=",
"hass",
".",
"states",
".",
"get",
"(",
"f\"device_tracker.{device_name}\"",
")",
"assert",
"state_2",
"is",
"not",
"None",
"assert",
"state_1",
"is",
"not",
"state_2",
"assert",
"STATE_HOME",
"==",
"state_2",
".",
"state",
"assert",
"state_2",
".",
"attributes",
"[",
"ATTR_LATITUDE",
"]",
"==",
"HOME_LATITUDE",
"assert",
"state_2",
".",
"attributes",
"[",
"ATTR_LONGITUDE",
"]",
"==",
"HOME_LONGITUDE"
] | [
293,
0
] | [
321,
63
] | python | en | ['en', 'en', 'en'] | True |
OptionsFlowHandler.__init__ | (self, config_entry: config_entries.ConfigEntry) | Init object. | Init object. | def __init__(self, config_entry: config_entries.ConfigEntry):
"""Init object."""
self.config_entry = config_entry | [
"def",
"__init__",
"(",
"self",
",",
"config_entry",
":",
"config_entries",
".",
"ConfigEntry",
")",
":",
"self",
".",
"config_entry",
"=",
"config_entry"
] | [
43,
4
] | [
45,
40
] | python | en | ['en', 'en', 'en'] | False |
OptionsFlowHandler.async_step_init | (self, user_input=None) | Manage the options. | Manage the options. | async def async_step_init(self, user_input=None):
"""Manage the options."""
if user_input is not None:
return self.async_create_entry(title="", data=user_input)
settings_schema = vol.Schema(
{
vol.Optional(
CONF_SHOW_ALL_SOURCES,
default=self.config_entry.options.get(
CONF_SHOW_ALL_SOURCES, DEFAULT_SHOW_SOURCES
),
): bool,
vol.Optional(
CONF_ZONE2,
default=self.config_entry.options.get(CONF_ZONE2, DEFAULT_ZONE2),
): bool,
vol.Optional(
CONF_ZONE3,
default=self.config_entry.options.get(CONF_ZONE3, DEFAULT_ZONE3),
): bool,
}
)
return self.async_show_form(step_id="init", data_schema=settings_schema) | [
"async",
"def",
"async_step_init",
"(",
"self",
",",
"user_input",
"=",
"None",
")",
":",
"if",
"user_input",
"is",
"not",
"None",
":",
"return",
"self",
".",
"async_create_entry",
"(",
"title",
"=",
"\"\"",
",",
"data",
"=",
"user_input",
")",
"settings_schema",
"=",
"vol",
".",
"Schema",
"(",
"{",
"vol",
".",
"Optional",
"(",
"CONF_SHOW_ALL_SOURCES",
",",
"default",
"=",
"self",
".",
"config_entry",
".",
"options",
".",
"get",
"(",
"CONF_SHOW_ALL_SOURCES",
",",
"DEFAULT_SHOW_SOURCES",
")",
",",
")",
":",
"bool",
",",
"vol",
".",
"Optional",
"(",
"CONF_ZONE2",
",",
"default",
"=",
"self",
".",
"config_entry",
".",
"options",
".",
"get",
"(",
"CONF_ZONE2",
",",
"DEFAULT_ZONE2",
")",
",",
")",
":",
"bool",
",",
"vol",
".",
"Optional",
"(",
"CONF_ZONE3",
",",
"default",
"=",
"self",
".",
"config_entry",
".",
"options",
".",
"get",
"(",
"CONF_ZONE3",
",",
"DEFAULT_ZONE3",
")",
",",
")",
":",
"bool",
",",
"}",
")",
"return",
"self",
".",
"async_show_form",
"(",
"step_id",
"=",
"\"init\"",
",",
"data_schema",
"=",
"settings_schema",
")"
] | [
47,
4
] | [
71,
80
] | python | en | ['en', 'en', 'en'] | True |
DenonAvrFlowHandler.__init__ | (self) | Initialize the Denon AVR flow. | Initialize the Denon AVR flow. | def __init__(self):
"""Initialize the Denon AVR flow."""
self.host = None
self.serial_number = None
self.model_name = None
self.timeout = DEFAULT_TIMEOUT
self.show_all_sources = DEFAULT_SHOW_SOURCES
self.zone2 = DEFAULT_ZONE2
self.zone3 = DEFAULT_ZONE3
self.d_receivers = [] | [
"def",
"__init__",
"(",
"self",
")",
":",
"self",
".",
"host",
"=",
"None",
"self",
".",
"serial_number",
"=",
"None",
"self",
".",
"model_name",
"=",
"None",
"self",
".",
"timeout",
"=",
"DEFAULT_TIMEOUT",
"self",
".",
"show_all_sources",
"=",
"DEFAULT_SHOW_SOURCES",
"self",
".",
"zone2",
"=",
"DEFAULT_ZONE2",
"self",
".",
"zone3",
"=",
"DEFAULT_ZONE3",
"self",
".",
"d_receivers",
"=",
"[",
"]"
] | [
80,
4
] | [
89,
29
] | python | en | ['en', 'en', 'en'] | True |
DenonAvrFlowHandler.async_get_options_flow | (config_entry) | Get the options flow. | Get the options flow. | def async_get_options_flow(config_entry) -> OptionsFlowHandler:
"""Get the options flow."""
return OptionsFlowHandler(config_entry) | [
"def",
"async_get_options_flow",
"(",
"config_entry",
")",
"->",
"OptionsFlowHandler",
":",
"return",
"OptionsFlowHandler",
"(",
"config_entry",
")"
] | [
93,
4
] | [
95,
47
] | python | en | ['en', 'en', 'en'] | True |
DenonAvrFlowHandler.async_step_user | (self, user_input=None) | Handle a flow initialized by the user. | Handle a flow initialized by the user. | async def async_step_user(self, user_input=None):
"""Handle a flow initialized by the user."""
errors = {}
if user_input is not None:
# check if IP address is set manually
host = user_input.get(CONF_HOST)
if host:
self.host = host
return await self.async_step_connect()
# discovery using denonavr library
self.d_receivers = await self.hass.async_add_executor_job(denonavr.discover)
# More than one receiver could be discovered by that method
if len(self.d_receivers) == 1:
self.host = self.d_receivers[0]["host"]
return await self.async_step_connect()
if len(self.d_receivers) > 1:
# show selection form
return await self.async_step_select()
errors["base"] = "discovery_error"
return self.async_show_form(
step_id="user", data_schema=CONFIG_SCHEMA, errors=errors
) | [
"async",
"def",
"async_step_user",
"(",
"self",
",",
"user_input",
"=",
"None",
")",
":",
"errors",
"=",
"{",
"}",
"if",
"user_input",
"is",
"not",
"None",
":",
"# check if IP address is set manually",
"host",
"=",
"user_input",
".",
"get",
"(",
"CONF_HOST",
")",
"if",
"host",
":",
"self",
".",
"host",
"=",
"host",
"return",
"await",
"self",
".",
"async_step_connect",
"(",
")",
"# discovery using denonavr library",
"self",
".",
"d_receivers",
"=",
"await",
"self",
".",
"hass",
".",
"async_add_executor_job",
"(",
"denonavr",
".",
"discover",
")",
"# More than one receiver could be discovered by that method",
"if",
"len",
"(",
"self",
".",
"d_receivers",
")",
"==",
"1",
":",
"self",
".",
"host",
"=",
"self",
".",
"d_receivers",
"[",
"0",
"]",
"[",
"\"host\"",
"]",
"return",
"await",
"self",
".",
"async_step_connect",
"(",
")",
"if",
"len",
"(",
"self",
".",
"d_receivers",
")",
">",
"1",
":",
"# show selection form",
"return",
"await",
"self",
".",
"async_step_select",
"(",
")",
"errors",
"[",
"\"base\"",
"]",
"=",
"\"discovery_error\"",
"return",
"self",
".",
"async_show_form",
"(",
"step_id",
"=",
"\"user\"",
",",
"data_schema",
"=",
"CONFIG_SCHEMA",
",",
"errors",
"=",
"errors",
")"
] | [
97,
4
] | [
121,
9
] | python | en | ['en', 'en', 'en'] | True |
DenonAvrFlowHandler.async_step_select | (self, user_input=None) | Handle multiple receivers found. | Handle multiple receivers found. | async def async_step_select(self, user_input=None):
"""Handle multiple receivers found."""
errors = {}
if user_input is not None:
self.host = user_input["select_host"]
return await self.async_step_connect()
select_scheme = vol.Schema(
{
vol.Required("select_host"): vol.In(
[d_receiver["host"] for d_receiver in self.d_receivers]
)
}
)
return self.async_show_form(
step_id="select", data_schema=select_scheme, errors=errors
) | [
"async",
"def",
"async_step_select",
"(",
"self",
",",
"user_input",
"=",
"None",
")",
":",
"errors",
"=",
"{",
"}",
"if",
"user_input",
"is",
"not",
"None",
":",
"self",
".",
"host",
"=",
"user_input",
"[",
"\"select_host\"",
"]",
"return",
"await",
"self",
".",
"async_step_connect",
"(",
")",
"select_scheme",
"=",
"vol",
".",
"Schema",
"(",
"{",
"vol",
".",
"Required",
"(",
"\"select_host\"",
")",
":",
"vol",
".",
"In",
"(",
"[",
"d_receiver",
"[",
"\"host\"",
"]",
"for",
"d_receiver",
"in",
"self",
".",
"d_receivers",
"]",
")",
"}",
")",
"return",
"self",
".",
"async_show_form",
"(",
"step_id",
"=",
"\"select\"",
",",
"data_schema",
"=",
"select_scheme",
",",
"errors",
"=",
"errors",
")"
] | [
123,
4
] | [
140,
9
] | python | en | ['fr', 'en', 'en'] | True |
DenonAvrFlowHandler.async_step_confirm | (self, user_input=None) | Allow the user to confirm adding the device. | Allow the user to confirm adding the device. | async def async_step_confirm(self, user_input=None):
"""Allow the user to confirm adding the device."""
if user_input is not None:
return await self.async_step_connect()
return self.async_show_form(step_id="confirm") | [
"async",
"def",
"async_step_confirm",
"(",
"self",
",",
"user_input",
"=",
"None",
")",
":",
"if",
"user_input",
"is",
"not",
"None",
":",
"return",
"await",
"self",
".",
"async_step_connect",
"(",
")",
"return",
"self",
".",
"async_show_form",
"(",
"step_id",
"=",
"\"confirm\"",
")"
] | [
142,
4
] | [
147,
54
] | python | en | ['en', 'en', 'en'] | True |
DenonAvrFlowHandler.async_step_connect | (self, user_input=None) | Connect to the receiver. | Connect to the receiver. | async def async_step_connect(self, user_input=None):
"""Connect to the receiver."""
connect_denonavr = ConnectDenonAVR(
self.hass,
self.host,
self.timeout,
self.show_all_sources,
self.zone2,
self.zone3,
)
if not await connect_denonavr.async_connect_receiver():
return self.async_abort(reason="cannot_connect")
receiver = connect_denonavr.receiver
mac_address = await self.async_get_mac(self.host)
if not self.serial_number:
self.serial_number = receiver.serial_number
if not self.model_name:
self.model_name = (receiver.model_name).replace("*", "")
if self.serial_number is not None:
unique_id = self.construct_unique_id(self.model_name, self.serial_number)
await self.async_set_unique_id(unique_id)
self._abort_if_unique_id_configured()
else:
_LOGGER.error(
"Could not get serial number of host %s, "
"unique_id's will not be available",
self.host,
)
for entry in self._async_current_entries():
if entry.data[CONF_HOST] == self.host:
return self.async_abort(reason="already_configured")
return self.async_create_entry(
title=receiver.name,
data={
CONF_HOST: self.host,
CONF_MAC: mac_address,
CONF_TYPE: receiver.receiver_type,
CONF_MODEL: self.model_name,
CONF_MANUFACTURER: receiver.manufacturer,
CONF_SERIAL_NUMBER: self.serial_number,
},
) | [
"async",
"def",
"async_step_connect",
"(",
"self",
",",
"user_input",
"=",
"None",
")",
":",
"connect_denonavr",
"=",
"ConnectDenonAVR",
"(",
"self",
".",
"hass",
",",
"self",
".",
"host",
",",
"self",
".",
"timeout",
",",
"self",
".",
"show_all_sources",
",",
"self",
".",
"zone2",
",",
"self",
".",
"zone3",
",",
")",
"if",
"not",
"await",
"connect_denonavr",
".",
"async_connect_receiver",
"(",
")",
":",
"return",
"self",
".",
"async_abort",
"(",
"reason",
"=",
"\"cannot_connect\"",
")",
"receiver",
"=",
"connect_denonavr",
".",
"receiver",
"mac_address",
"=",
"await",
"self",
".",
"async_get_mac",
"(",
"self",
".",
"host",
")",
"if",
"not",
"self",
".",
"serial_number",
":",
"self",
".",
"serial_number",
"=",
"receiver",
".",
"serial_number",
"if",
"not",
"self",
".",
"model_name",
":",
"self",
".",
"model_name",
"=",
"(",
"receiver",
".",
"model_name",
")",
".",
"replace",
"(",
"\"*\"",
",",
"\"\"",
")",
"if",
"self",
".",
"serial_number",
"is",
"not",
"None",
":",
"unique_id",
"=",
"self",
".",
"construct_unique_id",
"(",
"self",
".",
"model_name",
",",
"self",
".",
"serial_number",
")",
"await",
"self",
".",
"async_set_unique_id",
"(",
"unique_id",
")",
"self",
".",
"_abort_if_unique_id_configured",
"(",
")",
"else",
":",
"_LOGGER",
".",
"error",
"(",
"\"Could not get serial number of host %s, \"",
"\"unique_id's will not be available\"",
",",
"self",
".",
"host",
",",
")",
"for",
"entry",
"in",
"self",
".",
"_async_current_entries",
"(",
")",
":",
"if",
"entry",
".",
"data",
"[",
"CONF_HOST",
"]",
"==",
"self",
".",
"host",
":",
"return",
"self",
".",
"async_abort",
"(",
"reason",
"=",
"\"already_configured\"",
")",
"return",
"self",
".",
"async_create_entry",
"(",
"title",
"=",
"receiver",
".",
"name",
",",
"data",
"=",
"{",
"CONF_HOST",
":",
"self",
".",
"host",
",",
"CONF_MAC",
":",
"mac_address",
",",
"CONF_TYPE",
":",
"receiver",
".",
"receiver_type",
",",
"CONF_MODEL",
":",
"self",
".",
"model_name",
",",
"CONF_MANUFACTURER",
":",
"receiver",
".",
"manufacturer",
",",
"CONF_SERIAL_NUMBER",
":",
"self",
".",
"serial_number",
",",
"}",
",",
")"
] | [
149,
4
] | [
194,
9
] | python | en | ['en', 'en', 'en'] | True |
DenonAvrFlowHandler.async_step_ssdp | (self, discovery_info) | Handle a discovered Denon AVR.
This flow is triggered by the SSDP component. It will check if the
host is already configured and delegate to the import step if not.
| Handle a discovered Denon AVR. | async def async_step_ssdp(self, discovery_info):
"""Handle a discovered Denon AVR.
This flow is triggered by the SSDP component. It will check if the
host is already configured and delegate to the import step if not.
"""
# Filter out non-Denon AVRs#1
if (
discovery_info.get(ssdp.ATTR_UPNP_MANUFACTURER)
not in SUPPORTED_MANUFACTURERS
):
return self.async_abort(reason="not_denonavr_manufacturer")
# Check if required information is present to set the unique_id
if (
ssdp.ATTR_UPNP_MODEL_NAME not in discovery_info
or ssdp.ATTR_UPNP_SERIAL not in discovery_info
):
return self.async_abort(reason="not_denonavr_missing")
self.model_name = discovery_info[ssdp.ATTR_UPNP_MODEL_NAME].replace("*", "")
self.serial_number = discovery_info[ssdp.ATTR_UPNP_SERIAL]
self.host = urlparse(discovery_info[ssdp.ATTR_SSDP_LOCATION]).hostname
if self.model_name in IGNORED_MODELS:
return self.async_abort(reason="not_denonavr_manufacturer")
unique_id = self.construct_unique_id(self.model_name, self.serial_number)
await self.async_set_unique_id(unique_id)
self._abort_if_unique_id_configured({CONF_HOST: self.host})
# pylint: disable=no-member # https://github.com/PyCQA/pylint/issues/3167
self.context.update(
{
"title_placeholders": {
"name": discovery_info.get(ssdp.ATTR_UPNP_FRIENDLY_NAME, self.host)
}
}
)
return await self.async_step_confirm() | [
"async",
"def",
"async_step_ssdp",
"(",
"self",
",",
"discovery_info",
")",
":",
"# Filter out non-Denon AVRs#1",
"if",
"(",
"discovery_info",
".",
"get",
"(",
"ssdp",
".",
"ATTR_UPNP_MANUFACTURER",
")",
"not",
"in",
"SUPPORTED_MANUFACTURERS",
")",
":",
"return",
"self",
".",
"async_abort",
"(",
"reason",
"=",
"\"not_denonavr_manufacturer\"",
")",
"# Check if required information is present to set the unique_id",
"if",
"(",
"ssdp",
".",
"ATTR_UPNP_MODEL_NAME",
"not",
"in",
"discovery_info",
"or",
"ssdp",
".",
"ATTR_UPNP_SERIAL",
"not",
"in",
"discovery_info",
")",
":",
"return",
"self",
".",
"async_abort",
"(",
"reason",
"=",
"\"not_denonavr_missing\"",
")",
"self",
".",
"model_name",
"=",
"discovery_info",
"[",
"ssdp",
".",
"ATTR_UPNP_MODEL_NAME",
"]",
".",
"replace",
"(",
"\"*\"",
",",
"\"\"",
")",
"self",
".",
"serial_number",
"=",
"discovery_info",
"[",
"ssdp",
".",
"ATTR_UPNP_SERIAL",
"]",
"self",
".",
"host",
"=",
"urlparse",
"(",
"discovery_info",
"[",
"ssdp",
".",
"ATTR_SSDP_LOCATION",
"]",
")",
".",
"hostname",
"if",
"self",
".",
"model_name",
"in",
"IGNORED_MODELS",
":",
"return",
"self",
".",
"async_abort",
"(",
"reason",
"=",
"\"not_denonavr_manufacturer\"",
")",
"unique_id",
"=",
"self",
".",
"construct_unique_id",
"(",
"self",
".",
"model_name",
",",
"self",
".",
"serial_number",
")",
"await",
"self",
".",
"async_set_unique_id",
"(",
"unique_id",
")",
"self",
".",
"_abort_if_unique_id_configured",
"(",
"{",
"CONF_HOST",
":",
"self",
".",
"host",
"}",
")",
"# pylint: disable=no-member # https://github.com/PyCQA/pylint/issues/3167",
"self",
".",
"context",
".",
"update",
"(",
"{",
"\"title_placeholders\"",
":",
"{",
"\"name\"",
":",
"discovery_info",
".",
"get",
"(",
"ssdp",
".",
"ATTR_UPNP_FRIENDLY_NAME",
",",
"self",
".",
"host",
")",
"}",
"}",
")",
"return",
"await",
"self",
".",
"async_step_confirm",
"(",
")"
] | [
196,
4
] | [
236,
46
] | python | en | ['en', 'en', 'en'] | True |
DenonAvrFlowHandler.construct_unique_id | (model_name, serial_number) | Construct the unique id from the ssdp discovery or user_step. | Construct the unique id from the ssdp discovery or user_step. | def construct_unique_id(model_name, serial_number):
"""Construct the unique id from the ssdp discovery or user_step."""
return f"{model_name}-{serial_number}" | [
"def",
"construct_unique_id",
"(",
"model_name",
",",
"serial_number",
")",
":",
"return",
"f\"{model_name}-{serial_number}\""
] | [
239,
4
] | [
241,
46
] | python | en | ['en', 'en', 'en'] | True |
DenonAvrFlowHandler.async_get_mac | (self, host) | Get the mac address of the DenonAVR receiver. | Get the mac address of the DenonAVR receiver. | async def async_get_mac(self, host):
"""Get the mac address of the DenonAVR receiver."""
try:
mac_address = await self.hass.async_add_executor_job(
partial(get_mac_address, **{"ip": host})
)
if not mac_address:
mac_address = await self.hass.async_add_executor_job(
partial(get_mac_address, **{"hostname": host})
)
except Exception as err: # pylint: disable=broad-except
_LOGGER.error("Unable to get mac address: %s", err)
mac_address = None
if mac_address is not None:
mac_address = format_mac(mac_address)
return mac_address | [
"async",
"def",
"async_get_mac",
"(",
"self",
",",
"host",
")",
":",
"try",
":",
"mac_address",
"=",
"await",
"self",
".",
"hass",
".",
"async_add_executor_job",
"(",
"partial",
"(",
"get_mac_address",
",",
"*",
"*",
"{",
"\"ip\"",
":",
"host",
"}",
")",
")",
"if",
"not",
"mac_address",
":",
"mac_address",
"=",
"await",
"self",
".",
"hass",
".",
"async_add_executor_job",
"(",
"partial",
"(",
"get_mac_address",
",",
"*",
"*",
"{",
"\"hostname\"",
":",
"host",
"}",
")",
")",
"except",
"Exception",
"as",
"err",
":",
"# pylint: disable=broad-except",
"_LOGGER",
".",
"error",
"(",
"\"Unable to get mac address: %s\"",
",",
"err",
")",
"mac_address",
"=",
"None",
"if",
"mac_address",
"is",
"not",
"None",
":",
"mac_address",
"=",
"format_mac",
"(",
"mac_address",
")",
"return",
"mac_address"
] | [
243,
4
] | [
259,
26
] | python | en | ['en', 'en', 'en'] | True |
Filter.find_key_value | (key, dataset) |
Function for getting the value of a the key passed in (provided it exists)
Returns True and the value if the key is found or False and 0 when it isn't
Arguments:
key : dictionary key to be searched for
|
Function for getting the value of a the key passed in (provided it exists)
Returns True and the value if the key is found or False and 0 when it isn't | def find_key_value(key, dataset):
'''
Function for getting the value of a the key passed in (provided it exists)
Returns True and the value if the key is found or False and 0 when it isn't
Arguments:
key : dictionary key to be searched for
'''
dicts = []
if not isinstance(dataset, dict):
raise TypeError("dataset argument should be a dictionary")
for item in dataset:
if isinstance(dataset[item], dict):
dicts.append(dataset[item])
continue
if item == key:
return (True, dataset[item])
for dataset in dicts:
return Filter.find_key_value(key, dataset)
return (False, 0) | [
"def",
"find_key_value",
"(",
"key",
",",
"dataset",
")",
":",
"dicts",
"=",
"[",
"]",
"if",
"not",
"isinstance",
"(",
"dataset",
",",
"dict",
")",
":",
"raise",
"TypeError",
"(",
"\"dataset argument should be a dictionary\"",
")",
"for",
"item",
"in",
"dataset",
":",
"if",
"isinstance",
"(",
"dataset",
"[",
"item",
"]",
",",
"dict",
")",
":",
"dicts",
".",
"append",
"(",
"dataset",
"[",
"item",
"]",
")",
"continue",
"if",
"item",
"==",
"key",
":",
"return",
"(",
"True",
",",
"dataset",
"[",
"item",
"]",
")",
"for",
"dataset",
"in",
"dicts",
":",
"return",
"Filter",
".",
"find_key_value",
"(",
"key",
",",
"dataset",
")",
"return",
"(",
"False",
",",
"0",
")"
] | [
6,
4
] | [
31,
25
] | python | en | ['en', 'error', 'th'] | False |
Filter.filter_amount | (amount_range: range, dataset, amount_key='amount') |
Checks if there is an amount in the amount_range given in the dataset
|
Checks if there is an amount in the amount_range given in the dataset
| def filter_amount(amount_range: range, dataset, amount_key='amount'):
'''
Checks if there is an amount in the amount_range given in the dataset
'''
if not isinstance(dataset, dict):
raise TypeError("dataset argument should be a dictionary")
if not isinstance(amount_range, range):
raise TypeError("amount_range should be of type 'range' ")
status, value = Filter.find_key_value(amount_key, dataset)
if status:
if value in amount_range:
return True
else:
raise AttributeError("'amount_key' key not found in dataset")
return False | [
"def",
"filter_amount",
"(",
"amount_range",
":",
"range",
",",
"dataset",
",",
"amount_key",
"=",
"'amount'",
")",
":",
"if",
"not",
"isinstance",
"(",
"dataset",
",",
"dict",
")",
":",
"raise",
"TypeError",
"(",
"\"dataset argument should be a dictionary\"",
")",
"if",
"not",
"isinstance",
"(",
"amount_range",
",",
"range",
")",
":",
"raise",
"TypeError",
"(",
"\"amount_range should be of type 'range' \"",
")",
"status",
",",
"value",
"=",
"Filter",
".",
"find_key_value",
"(",
"amount_key",
",",
"dataset",
")",
"if",
"status",
":",
"if",
"value",
"in",
"amount_range",
":",
"return",
"True",
"else",
":",
"raise",
"AttributeError",
"(",
"\"'amount_key' key not found in dataset\"",
")",
"return",
"False"
] | [
35,
4
] | [
53,
20
] | python | en | ['en', 'error', 'th'] | False |
test_duplicate_error | (hass, config_entry) | Test that errors are shown when duplicates are added. | Test that errors are shown when duplicates are added. | async def test_duplicate_error(hass, config_entry):
"""Test that errors are shown when duplicates are added."""
conf = {CONF_LATITUDE: -41.2, CONF_LONGITUDE: 174.7, CONF_RADIUS: 25}
config_entry.add_to_hass(hass)
flow = config_flow.GeonetnzVolcanoFlowHandler()
flow.hass = hass
result = await flow.async_step_user(user_input=conf)
assert result["errors"] == {"base": "already_configured"} | [
"async",
"def",
"test_duplicate_error",
"(",
"hass",
",",
"config_entry",
")",
":",
"conf",
"=",
"{",
"CONF_LATITUDE",
":",
"-",
"41.2",
",",
"CONF_LONGITUDE",
":",
"174.7",
",",
"CONF_RADIUS",
":",
"25",
"}",
"config_entry",
".",
"add_to_hass",
"(",
"hass",
")",
"flow",
"=",
"config_flow",
".",
"GeonetnzVolcanoFlowHandler",
"(",
")",
"flow",
".",
"hass",
"=",
"hass",
"result",
"=",
"await",
"flow",
".",
"async_step_user",
"(",
"user_input",
"=",
"conf",
")",
"assert",
"result",
"[",
"\"errors\"",
"]",
"==",
"{",
"\"base\"",
":",
"\"already_configured\"",
"}"
] | [
16,
0
] | [
25,
61
] | python | en | ['en', 'en', 'en'] | True |
test_show_form | (hass) | Test that the form is served with no input. | Test that the form is served with no input. | async def test_show_form(hass):
"""Test that the form is served with no input."""
flow = config_flow.GeonetnzVolcanoFlowHandler()
flow.hass = hass
result = await flow.async_step_user(user_input=None)
assert result["type"] == data_entry_flow.RESULT_TYPE_FORM
assert result["step_id"] == "user" | [
"async",
"def",
"test_show_form",
"(",
"hass",
")",
":",
"flow",
"=",
"config_flow",
".",
"GeonetnzVolcanoFlowHandler",
"(",
")",
"flow",
".",
"hass",
"=",
"hass",
"result",
"=",
"await",
"flow",
".",
"async_step_user",
"(",
"user_input",
"=",
"None",
")",
"assert",
"result",
"[",
"\"type\"",
"]",
"==",
"data_entry_flow",
".",
"RESULT_TYPE_FORM",
"assert",
"result",
"[",
"\"step_id\"",
"]",
"==",
"\"user\""
] | [
28,
0
] | [
36,
38
] | python | en | ['en', 'en', 'en'] | True |
test_step_import | (hass) | Test that the import step works. | Test that the import step works. | async def test_step_import(hass):
"""Test that the import step works."""
conf = {
CONF_LATITUDE: -41.2,
CONF_LONGITUDE: 174.7,
CONF_RADIUS: 25,
CONF_UNIT_SYSTEM: "metric",
CONF_SCAN_INTERVAL: timedelta(minutes=4),
}
flow = config_flow.GeonetnzVolcanoFlowHandler()
flow.hass = hass
with patch(
"homeassistant.components.geonetnz_volcano.async_setup_entry", return_value=True
), patch(
"homeassistant.components.geonetnz_volcano.async_setup", return_value=True
):
result = await flow.async_step_import(import_config=conf)
assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY
assert result["title"] == "-41.2, 174.7"
assert result["data"] == {
CONF_LATITUDE: -41.2,
CONF_LONGITUDE: 174.7,
CONF_RADIUS: 25,
CONF_UNIT_SYSTEM: "metric",
CONF_SCAN_INTERVAL: 240.0,
} | [
"async",
"def",
"test_step_import",
"(",
"hass",
")",
":",
"conf",
"=",
"{",
"CONF_LATITUDE",
":",
"-",
"41.2",
",",
"CONF_LONGITUDE",
":",
"174.7",
",",
"CONF_RADIUS",
":",
"25",
",",
"CONF_UNIT_SYSTEM",
":",
"\"metric\"",
",",
"CONF_SCAN_INTERVAL",
":",
"timedelta",
"(",
"minutes",
"=",
"4",
")",
",",
"}",
"flow",
"=",
"config_flow",
".",
"GeonetnzVolcanoFlowHandler",
"(",
")",
"flow",
".",
"hass",
"=",
"hass",
"with",
"patch",
"(",
"\"homeassistant.components.geonetnz_volcano.async_setup_entry\"",
",",
"return_value",
"=",
"True",
")",
",",
"patch",
"(",
"\"homeassistant.components.geonetnz_volcano.async_setup\"",
",",
"return_value",
"=",
"True",
")",
":",
"result",
"=",
"await",
"flow",
".",
"async_step_import",
"(",
"import_config",
"=",
"conf",
")",
"assert",
"result",
"[",
"\"type\"",
"]",
"==",
"data_entry_flow",
".",
"RESULT_TYPE_CREATE_ENTRY",
"assert",
"result",
"[",
"\"title\"",
"]",
"==",
"\"-41.2, 174.7\"",
"assert",
"result",
"[",
"\"data\"",
"]",
"==",
"{",
"CONF_LATITUDE",
":",
"-",
"41.2",
",",
"CONF_LONGITUDE",
":",
"174.7",
",",
"CONF_RADIUS",
":",
"25",
",",
"CONF_UNIT_SYSTEM",
":",
"\"metric\"",
",",
"CONF_SCAN_INTERVAL",
":",
"240.0",
",",
"}"
] | [
39,
0
] | [
66,
5
] | python | en | ['en', 'en', 'en'] | True |
test_step_user | (hass) | Test that the user step works. | Test that the user step works. | async def test_step_user(hass):
"""Test that the user step works."""
hass.config.latitude = -41.2
hass.config.longitude = 174.7
conf = {CONF_RADIUS: 25}
flow = config_flow.GeonetnzVolcanoFlowHandler()
flow.hass = hass
with patch(
"homeassistant.components.geonetnz_volcano.async_setup_entry", return_value=True
), patch(
"homeassistant.components.geonetnz_volcano.async_setup", return_value=True
):
result = await flow.async_step_user(user_input=conf)
assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY
assert result["title"] == "-41.2, 174.7"
assert result["data"] == {
CONF_LATITUDE: -41.2,
CONF_LONGITUDE: 174.7,
CONF_RADIUS: 25,
CONF_UNIT_SYSTEM: "metric",
CONF_SCAN_INTERVAL: 300.0,
} | [
"async",
"def",
"test_step_user",
"(",
"hass",
")",
":",
"hass",
".",
"config",
".",
"latitude",
"=",
"-",
"41.2",
"hass",
".",
"config",
".",
"longitude",
"=",
"174.7",
"conf",
"=",
"{",
"CONF_RADIUS",
":",
"25",
"}",
"flow",
"=",
"config_flow",
".",
"GeonetnzVolcanoFlowHandler",
"(",
")",
"flow",
".",
"hass",
"=",
"hass",
"with",
"patch",
"(",
"\"homeassistant.components.geonetnz_volcano.async_setup_entry\"",
",",
"return_value",
"=",
"True",
")",
",",
"patch",
"(",
"\"homeassistant.components.geonetnz_volcano.async_setup\"",
",",
"return_value",
"=",
"True",
")",
":",
"result",
"=",
"await",
"flow",
".",
"async_step_user",
"(",
"user_input",
"=",
"conf",
")",
"assert",
"result",
"[",
"\"type\"",
"]",
"==",
"data_entry_flow",
".",
"RESULT_TYPE_CREATE_ENTRY",
"assert",
"result",
"[",
"\"title\"",
"]",
"==",
"\"-41.2, 174.7\"",
"assert",
"result",
"[",
"\"data\"",
"]",
"==",
"{",
"CONF_LATITUDE",
":",
"-",
"41.2",
",",
"CONF_LONGITUDE",
":",
"174.7",
",",
"CONF_RADIUS",
":",
"25",
",",
"CONF_UNIT_SYSTEM",
":",
"\"metric\"",
",",
"CONF_SCAN_INTERVAL",
":",
"300.0",
",",
"}"
] | [
69,
0
] | [
92,
5
] | python | en | ['en', 'en', 'en'] | True |
async_setup_platform | (hass, config, add_entities, discovery_info=None) | Set up a media player entity for a Sisyphus table. | Set up a media player entity for a Sisyphus table. | async def async_setup_platform(hass, config, add_entities, discovery_info=None):
"""Set up a media player entity for a Sisyphus table."""
host = discovery_info[CONF_HOST]
try:
table_holder = hass.data[DATA_SISYPHUS][host]
table = await table_holder.get_table()
except aiohttp.ClientError as err:
raise PlatformNotReady() from err
add_entities([SisyphusPlayer(table_holder.name, host, table)], True) | [
"async",
"def",
"async_setup_platform",
"(",
"hass",
",",
"config",
",",
"add_entities",
",",
"discovery_info",
"=",
"None",
")",
":",
"host",
"=",
"discovery_info",
"[",
"CONF_HOST",
"]",
"try",
":",
"table_holder",
"=",
"hass",
".",
"data",
"[",
"DATA_SISYPHUS",
"]",
"[",
"host",
"]",
"table",
"=",
"await",
"table_holder",
".",
"get_table",
"(",
")",
"except",
"aiohttp",
".",
"ClientError",
"as",
"err",
":",
"raise",
"PlatformNotReady",
"(",
")",
"from",
"err",
"add_entities",
"(",
"[",
"SisyphusPlayer",
"(",
"table_holder",
".",
"name",
",",
"host",
",",
"table",
")",
"]",
",",
"True",
")"
] | [
42,
0
] | [
51,
72
] | python | en | ['en', 'en', 'en'] | True |
SisyphusPlayer.__init__ | (self, name, host, table) | Initialize the Sisyphus media device. | Initialize the Sisyphus media device. | def __init__(self, name, host, table):
"""Initialize the Sisyphus media device."""
self._name = name
self._host = host
self._table = table | [
"def",
"__init__",
"(",
"self",
",",
"name",
",",
"host",
",",
"table",
")",
":",
"self",
".",
"_name",
"=",
"name",
"self",
".",
"_host",
"=",
"host",
"self",
".",
"_table",
"=",
"table"
] | [
57,
4
] | [
61,
27
] | python | en | ['en', 'zu', 'en'] | True |
SisyphusPlayer.async_added_to_hass | (self) | Add listeners after this object has been initialized. | Add listeners after this object has been initialized. | async def async_added_to_hass(self):
"""Add listeners after this object has been initialized."""
self._table.add_listener(self.async_write_ha_state) | [
"async",
"def",
"async_added_to_hass",
"(",
"self",
")",
":",
"self",
".",
"_table",
".",
"add_listener",
"(",
"self",
".",
"async_write_ha_state",
")"
] | [
63,
4
] | [
65,
59
] | python | en | ['en', 'en', 'en'] | True |
SisyphusPlayer.async_update | (self) | Force update table state. | Force update table state. | async def async_update(self):
"""Force update table state."""
await self._table.refresh() | [
"async",
"def",
"async_update",
"(",
"self",
")",
":",
"await",
"self",
".",
"_table",
".",
"refresh",
"(",
")"
] | [
67,
4
] | [
69,
35
] | python | en | ['en', 'en', 'en'] | True |
SisyphusPlayer.unique_id | (self) | Return the UUID of the table. | Return the UUID of the table. | def unique_id(self):
"""Return the UUID of the table."""
return self._table.id | [
"def",
"unique_id",
"(",
"self",
")",
":",
"return",
"self",
".",
"_table",
".",
"id"
] | [
72,
4
] | [
74,
29
] | python | en | ['en', 'en', 'en'] | True |
SisyphusPlayer.available | (self) | Return true if the table is responding to heartbeats. | Return true if the table is responding to heartbeats. | def available(self):
"""Return true if the table is responding to heartbeats."""
return self._table.is_connected | [
"def",
"available",
"(",
"self",
")",
":",
"return",
"self",
".",
"_table",
".",
"is_connected"
] | [
77,
4
] | [
79,
39
] | python | en | ['en', 'en', 'en'] | True |
SisyphusPlayer.name | (self) | Return the name of the table. | Return the name of the table. | def name(self):
"""Return the name of the table."""
return self._name | [
"def",
"name",
"(",
"self",
")",
":",
"return",
"self",
".",
"_name"
] | [
82,
4
] | [
84,
25
] | python | en | ['en', 'en', 'en'] | True |
SisyphusPlayer.state | (self) | Return the current state of the table; sleeping maps to off. | Return the current state of the table; sleeping maps to off. | def state(self):
"""Return the current state of the table; sleeping maps to off."""
if self._table.state in ["homing", "playing"]:
return STATE_PLAYING
if self._table.state == "paused":
if self._table.is_sleeping:
return STATE_OFF
return STATE_PAUSED
if self._table.state == "waiting":
return STATE_IDLE
return None | [
"def",
"state",
"(",
"self",
")",
":",
"if",
"self",
".",
"_table",
".",
"state",
"in",
"[",
"\"homing\"",
",",
"\"playing\"",
"]",
":",
"return",
"STATE_PLAYING",
"if",
"self",
".",
"_table",
".",
"state",
"==",
"\"paused\"",
":",
"if",
"self",
".",
"_table",
".",
"is_sleeping",
":",
"return",
"STATE_OFF",
"return",
"STATE_PAUSED",
"if",
"self",
".",
"_table",
".",
"state",
"==",
"\"waiting\"",
":",
"return",
"STATE_IDLE",
"return",
"None"
] | [
87,
4
] | [
99,
19
] | python | en | ['en', 'en', 'en'] | True |
SisyphusPlayer.volume_level | (self) | Return the current playback speed (0..1). | Return the current playback speed (0..1). | def volume_level(self):
"""Return the current playback speed (0..1)."""
return self._table.speed | [
"def",
"volume_level",
"(",
"self",
")",
":",
"return",
"self",
".",
"_table",
".",
"speed"
] | [
102,
4
] | [
104,
32
] | python | en | ['en', 'en', 'en'] | True |
SisyphusPlayer.shuffle | (self) | Return True if the current playlist is in shuffle mode. | Return True if the current playlist is in shuffle mode. | def shuffle(self):
"""Return True if the current playlist is in shuffle mode."""
return self._table.is_shuffle | [
"def",
"shuffle",
"(",
"self",
")",
":",
"return",
"self",
".",
"_table",
".",
"is_shuffle"
] | [
107,
4
] | [
109,
37
] | python | en | ['en', 'en', 'en'] | True |
SisyphusPlayer.async_set_shuffle | (self, shuffle) | Change the shuffle mode of the current playlist. | Change the shuffle mode of the current playlist. | async def async_set_shuffle(self, shuffle):
"""Change the shuffle mode of the current playlist."""
await self._table.set_shuffle(shuffle) | [
"async",
"def",
"async_set_shuffle",
"(",
"self",
",",
"shuffle",
")",
":",
"await",
"self",
".",
"_table",
".",
"set_shuffle",
"(",
"shuffle",
")"
] | [
111,
4
] | [
113,
46
] | python | en | ['en', 'en', 'en'] | True |
SisyphusPlayer.media_playlist | (self) | Return the name of the current playlist. | Return the name of the current playlist. | def media_playlist(self):
"""Return the name of the current playlist."""
return self._table.active_playlist.name if self._table.active_playlist else None | [
"def",
"media_playlist",
"(",
"self",
")",
":",
"return",
"self",
".",
"_table",
".",
"active_playlist",
".",
"name",
"if",
"self",
".",
"_table",
".",
"active_playlist",
"else",
"None"
] | [
116,
4
] | [
118,
88
] | python | en | ['en', 'en', 'en'] | True |
SisyphusPlayer.media_title | (self) | Return the title of the current track. | Return the title of the current track. | def media_title(self):
"""Return the title of the current track."""
return self._table.active_track.name if self._table.active_track else None | [
"def",
"media_title",
"(",
"self",
")",
":",
"return",
"self",
".",
"_table",
".",
"active_track",
".",
"name",
"if",
"self",
".",
"_table",
".",
"active_track",
"else",
"None"
] | [
121,
4
] | [
123,
82
] | python | en | ['en', 'en', 'en'] | True |
SisyphusPlayer.media_content_type | (self) | Return the content type currently playing; i.e. a Sisyphus track. | Return the content type currently playing; i.e. a Sisyphus track. | def media_content_type(self):
"""Return the content type currently playing; i.e. a Sisyphus track."""
return MEDIA_TYPE_TRACK | [
"def",
"media_content_type",
"(",
"self",
")",
":",
"return",
"MEDIA_TYPE_TRACK"
] | [
126,
4
] | [
128,
31
] | python | en | ['en', 'en', 'en'] | True |
SisyphusPlayer.media_content_id | (self) | Return the track ID of the current track. | Return the track ID of the current track. | def media_content_id(self):
"""Return the track ID of the current track."""
return self._table.active_track.id if self._table.active_track else None | [
"def",
"media_content_id",
"(",
"self",
")",
":",
"return",
"self",
".",
"_table",
".",
"active_track",
".",
"id",
"if",
"self",
".",
"_table",
".",
"active_track",
"else",
"None"
] | [
131,
4
] | [
133,
80
] | python | en | ['en', 'en', 'en'] | True |
SisyphusPlayer.media_duration | (self) | Return the total time it will take to run this track at the current speed. | Return the total time it will take to run this track at the current speed. | def media_duration(self):
"""Return the total time it will take to run this track at the current speed."""
return self._table.active_track_total_time.total_seconds() | [
"def",
"media_duration",
"(",
"self",
")",
":",
"return",
"self",
".",
"_table",
".",
"active_track_total_time",
".",
"total_seconds",
"(",
")"
] | [
136,
4
] | [
138,
66
] | python | en | ['en', 'en', 'en'] | True |
SisyphusPlayer.media_position | (self) | Return the current position within the track. | Return the current position within the track. | def media_position(self):
"""Return the current position within the track."""
return (
self._table.active_track_total_time
- self._table.active_track_remaining_time
).total_seconds() | [
"def",
"media_position",
"(",
"self",
")",
":",
"return",
"(",
"self",
".",
"_table",
".",
"active_track_total_time",
"-",
"self",
".",
"_table",
".",
"active_track_remaining_time",
")",
".",
"total_seconds",
"(",
")"
] | [
141,
4
] | [
146,
25
] | python | en | ['en', 'en', 'en'] | True |
SisyphusPlayer.media_position_updated_at | (self) | Return the last time we got a position update. | Return the last time we got a position update. | def media_position_updated_at(self):
"""Return the last time we got a position update."""
return self._table.active_track_remaining_time_as_of | [
"def",
"media_position_updated_at",
"(",
"self",
")",
":",
"return",
"self",
".",
"_table",
".",
"active_track_remaining_time_as_of"
] | [
149,
4
] | [
151,
60
] | python | en | ['en', 'en', 'en'] | True |
SisyphusPlayer.supported_features | (self) | Return the features supported by this table. | Return the features supported by this table. | def supported_features(self):
"""Return the features supported by this table."""
return SUPPORTED_FEATURES | [
"def",
"supported_features",
"(",
"self",
")",
":",
"return",
"SUPPORTED_FEATURES"
] | [
154,
4
] | [
156,
33
] | python | en | ['en', 'en', 'en'] | True |
SisyphusPlayer.media_image_url | (self) | Return the URL for a thumbnail image of the current track. | Return the URL for a thumbnail image of the current track. | def media_image_url(self):
"""Return the URL for a thumbnail image of the current track."""
if self._table.active_track:
return self._table.active_track.get_thumbnail_url(Track.ThumbnailSize.LARGE)
return super.media_image_url() | [
"def",
"media_image_url",
"(",
"self",
")",
":",
"if",
"self",
".",
"_table",
".",
"active_track",
":",
"return",
"self",
".",
"_table",
".",
"active_track",
".",
"get_thumbnail_url",
"(",
"Track",
".",
"ThumbnailSize",
".",
"LARGE",
")",
"return",
"super",
".",
"media_image_url",
"(",
")"
] | [
159,
4
] | [
165,
38
] | python | en | ['en', 'en', 'en'] | True |
SisyphusPlayer.async_turn_on | (self) | Wake up a sleeping table. | Wake up a sleeping table. | async def async_turn_on(self):
"""Wake up a sleeping table."""
await self._table.wakeup() | [
"async",
"def",
"async_turn_on",
"(",
"self",
")",
":",
"await",
"self",
".",
"_table",
".",
"wakeup",
"(",
")"
] | [
167,
4
] | [
169,
34
] | python | en | ['en', 'tg', 'en'] | True |
SisyphusPlayer.async_turn_off | (self) | Put the table to sleep. | Put the table to sleep. | async def async_turn_off(self):
"""Put the table to sleep."""
await self._table.sleep() | [
"async",
"def",
"async_turn_off",
"(",
"self",
")",
":",
"await",
"self",
".",
"_table",
".",
"sleep",
"(",
")"
] | [
171,
4
] | [
173,
33
] | python | en | ['en', 'ceb', 'en'] | True |
SisyphusPlayer.async_volume_down | (self) | Slow down playback. | Slow down playback. | async def async_volume_down(self):
"""Slow down playback."""
await self._table.set_speed(max(0, self._table.speed - 0.1)) | [
"async",
"def",
"async_volume_down",
"(",
"self",
")",
":",
"await",
"self",
".",
"_table",
".",
"set_speed",
"(",
"max",
"(",
"0",
",",
"self",
".",
"_table",
".",
"speed",
"-",
"0.1",
")",
")"
] | [
175,
4
] | [
177,
68
] | python | en | ['en', 'en', 'en'] | True |
SisyphusPlayer.async_volume_up | (self) | Speed up playback. | Speed up playback. | async def async_volume_up(self):
"""Speed up playback."""
await self._table.set_speed(min(1.0, self._table.speed + 0.1)) | [
"async",
"def",
"async_volume_up",
"(",
"self",
")",
":",
"await",
"self",
".",
"_table",
".",
"set_speed",
"(",
"min",
"(",
"1.0",
",",
"self",
".",
"_table",
".",
"speed",
"+",
"0.1",
")",
")"
] | [
179,
4
] | [
181,
70
] | python | en | ['en', 'en', 'en'] | True |
SisyphusPlayer.async_set_volume_level | (self, volume) | Set playback speed (0..1). | Set playback speed (0..1). | async def async_set_volume_level(self, volume):
"""Set playback speed (0..1)."""
await self._table.set_speed(volume) | [
"async",
"def",
"async_set_volume_level",
"(",
"self",
",",
"volume",
")",
":",
"await",
"self",
".",
"_table",
".",
"set_speed",
"(",
"volume",
")"
] | [
183,
4
] | [
185,
43
] | python | en | ['en', 'ky', 'en'] | True |
SisyphusPlayer.async_media_play | (self) | Start playing. | Start playing. | async def async_media_play(self):
"""Start playing."""
await self._table.play() | [
"async",
"def",
"async_media_play",
"(",
"self",
")",
":",
"await",
"self",
".",
"_table",
".",
"play",
"(",
")"
] | [
187,
4
] | [
189,
32
] | python | en | ['en', 'jv', 'en'] | False |
SisyphusPlayer.async_media_next_track | (self) | Skip to next track. | Skip to next track. | async def async_media_next_track(self):
"""Skip to next track."""
cur_track_index = self._get_current_track_index()
await self._table.active_playlist.play(
self._table.active_playlist.tracks[cur_track_index + 1]
) | [
"async",
"def",
"async_media_next_track",
"(",
"self",
")",
":",
"cur_track_index",
"=",
"self",
".",
"_get_current_track_index",
"(",
")",
"await",
"self",
".",
"_table",
".",
"active_playlist",
".",
"play",
"(",
"self",
".",
"_table",
".",
"active_playlist",
".",
"tracks",
"[",
"cur_track_index",
"+",
"1",
"]",
")"
] | [
195,
4
] | [
201,
9
] | python | en | ['en', 'bg-Latn', 'en'] | True |
SisyphusPlayer.async_media_previous_track | (self) | Skip to previous track. | Skip to previous track. | async def async_media_previous_track(self):
"""Skip to previous track."""
cur_track_index = self._get_current_track_index()
await self._table.active_playlist.play(
self._table.active_playlist.tracks[cur_track_index - 1]
) | [
"async",
"def",
"async_media_previous_track",
"(",
"self",
")",
":",
"cur_track_index",
"=",
"self",
".",
"_get_current_track_index",
"(",
")",
"await",
"self",
".",
"_table",
".",
"active_playlist",
".",
"play",
"(",
"self",
".",
"_table",
".",
"active_playlist",
".",
"tracks",
"[",
"cur_track_index",
"-",
"1",
"]",
")"
] | [
203,
4
] | [
209,
9
] | python | en | ['en', 'en', 'en'] | True |
get_system_unique_id | (entity: RegistryEntry) | Determine the system wide unique_id for an entity. | Determine the system wide unique_id for an entity. | def get_system_unique_id(entity: RegistryEntry):
"""Determine the system wide unique_id for an entity."""
return f"{entity.platform}.{entity.domain}.{entity.unique_id}" | [
"def",
"get_system_unique_id",
"(",
"entity",
":",
"RegistryEntry",
")",
":",
"return",
"f\"{entity.platform}.{entity.domain}.{entity.unique_id}\""
] | [
34,
0
] | [
36,
66
] | python | en | ['en', 'en', 'en'] | True |
_generate_aids | (unique_id: str, entity_id: str) | Generate accessory aid. | Generate accessory aid. | def _generate_aids(unique_id: str, entity_id: str) -> int:
"""Generate accessory aid."""
if unique_id:
# Use fnv1a_32 of the unique id as
# fnv1a_32 has less collisions than
# adler32
yield fnv1a_32(unique_id.encode("utf-8"))
# If there is no unique id we use
# fnv1a_32 as it is unlikely to collide
yield fnv1a_32(entity_id.encode("utf-8"))
# If called again resort to random allocations.
# Given the size of the range its unlikely we'll encounter duplicates
# But try a few times regardless
for _ in range(5):
yield random.randrange(AID_MIN, AID_MAX) | [
"def",
"_generate_aids",
"(",
"unique_id",
":",
"str",
",",
"entity_id",
":",
"str",
")",
"->",
"int",
":",
"if",
"unique_id",
":",
"# Use fnv1a_32 of the unique id as",
"# fnv1a_32 has less collisions than",
"# adler32",
"yield",
"fnv1a_32",
"(",
"unique_id",
".",
"encode",
"(",
"\"utf-8\"",
")",
")",
"# If there is no unique id we use",
"# fnv1a_32 as it is unlikely to collide",
"yield",
"fnv1a_32",
"(",
"entity_id",
".",
"encode",
"(",
"\"utf-8\"",
")",
")",
"# If called again resort to random allocations.",
"# Given the size of the range its unlikely we'll encounter duplicates",
"# But try a few times regardless",
"for",
"_",
"in",
"range",
"(",
"5",
")",
":",
"yield",
"random",
".",
"randrange",
"(",
"AID_MIN",
",",
"AID_MAX",
")"
] | [
39,
0
] | [
56,
48
] | python | co | ['en', 'co', 'it'] | False |
AccessoryAidStorage.__init__ | (self, hass: HomeAssistant, entry: ConfigEntry) | Create a new entity map store. | Create a new entity map store. | def __init__(self, hass: HomeAssistant, entry: ConfigEntry):
"""Create a new entity map store."""
self.hass = hass
self.allocations = {}
self.allocated_aids = set()
self._entry = entry
self.store = None
self._entity_registry = None | [
"def",
"__init__",
"(",
"self",
",",
"hass",
":",
"HomeAssistant",
",",
"entry",
":",
"ConfigEntry",
")",
":",
"self",
".",
"hass",
"=",
"hass",
"self",
".",
"allocations",
"=",
"{",
"}",
"self",
".",
"allocated_aids",
"=",
"set",
"(",
")",
"self",
".",
"_entry",
"=",
"entry",
"self",
".",
"store",
"=",
"None",
"self",
".",
"_entity_registry",
"=",
"None"
] | [
67,
4
] | [
74,
36
] | python | en | ['en', 'en', 'en'] | True |
AccessoryAidStorage.async_initialize | (self) | Load the latest AID data. | Load the latest AID data. | async def async_initialize(self):
"""Load the latest AID data."""
self._entity_registry = (
await self.hass.helpers.entity_registry.async_get_registry()
)
aidstore = get_aid_storage_filename_for_entry_id(self._entry)
self.store = Store(self.hass, AID_MANAGER_STORAGE_VERSION, aidstore)
raw_storage = await self.store.async_load()
if not raw_storage:
# There is no data about aid allocations yet
return
self.allocations = raw_storage.get(ALLOCATIONS_KEY, {})
self.allocated_aids = set(self.allocations.values()) | [
"async",
"def",
"async_initialize",
"(",
"self",
")",
":",
"self",
".",
"_entity_registry",
"=",
"(",
"await",
"self",
".",
"hass",
".",
"helpers",
".",
"entity_registry",
".",
"async_get_registry",
"(",
")",
")",
"aidstore",
"=",
"get_aid_storage_filename_for_entry_id",
"(",
"self",
".",
"_entry",
")",
"self",
".",
"store",
"=",
"Store",
"(",
"self",
".",
"hass",
",",
"AID_MANAGER_STORAGE_VERSION",
",",
"aidstore",
")",
"raw_storage",
"=",
"await",
"self",
".",
"store",
".",
"async_load",
"(",
")",
"if",
"not",
"raw_storage",
":",
"# There is no data about aid allocations yet",
"return",
"self",
".",
"allocations",
"=",
"raw_storage",
".",
"get",
"(",
"ALLOCATIONS_KEY",
",",
"{",
"}",
")",
"self",
".",
"allocated_aids",
"=",
"set",
"(",
"self",
".",
"allocations",
".",
"values",
"(",
")",
")"
] | [
76,
4
] | [
90,
60
] | python | en | ['en', 'sm', 'en'] | True |
AccessoryAidStorage.get_or_allocate_aid_for_entity_id | (self, entity_id: str) | Generate a stable aid for an entity id. | Generate a stable aid for an entity id. | def get_or_allocate_aid_for_entity_id(self, entity_id: str):
"""Generate a stable aid for an entity id."""
entity = self._entity_registry.async_get(entity_id)
if not entity:
return self._get_or_allocate_aid(None, entity_id)
sys_unique_id = get_system_unique_id(entity)
return self._get_or_allocate_aid(sys_unique_id, entity_id) | [
"def",
"get_or_allocate_aid_for_entity_id",
"(",
"self",
",",
"entity_id",
":",
"str",
")",
":",
"entity",
"=",
"self",
".",
"_entity_registry",
".",
"async_get",
"(",
"entity_id",
")",
"if",
"not",
"entity",
":",
"return",
"self",
".",
"_get_or_allocate_aid",
"(",
"None",
",",
"entity_id",
")",
"sys_unique_id",
"=",
"get_system_unique_id",
"(",
"entity",
")",
"return",
"self",
".",
"_get_or_allocate_aid",
"(",
"sys_unique_id",
",",
"entity_id",
")"
] | [
92,
4
] | [
99,
66
] | python | en | ['en', 'en', 'en'] | True |
AccessoryAidStorage._get_or_allocate_aid | (self, unique_id: str, entity_id: str) | Allocate (and return) a new aid for an accessory. | Allocate (and return) a new aid for an accessory. | def _get_or_allocate_aid(self, unique_id: str, entity_id: str):
"""Allocate (and return) a new aid for an accessory."""
if unique_id and unique_id in self.allocations:
return self.allocations[unique_id]
if entity_id in self.allocations:
return self.allocations[entity_id]
for aid in _generate_aids(unique_id, entity_id):
if aid in INVALID_AIDS:
continue
if aid not in self.allocated_aids:
# Prefer the unique_id over the entitiy_id
storage_key = unique_id or entity_id
self.allocations[storage_key] = aid
self.allocated_aids.add(aid)
self.async_schedule_save()
return aid
raise ValueError(
f"Unable to generate unique aid allocation for {entity_id} [{unique_id}]"
) | [
"def",
"_get_or_allocate_aid",
"(",
"self",
",",
"unique_id",
":",
"str",
",",
"entity_id",
":",
"str",
")",
":",
"if",
"unique_id",
"and",
"unique_id",
"in",
"self",
".",
"allocations",
":",
"return",
"self",
".",
"allocations",
"[",
"unique_id",
"]",
"if",
"entity_id",
"in",
"self",
".",
"allocations",
":",
"return",
"self",
".",
"allocations",
"[",
"entity_id",
"]",
"for",
"aid",
"in",
"_generate_aids",
"(",
"unique_id",
",",
"entity_id",
")",
":",
"if",
"aid",
"in",
"INVALID_AIDS",
":",
"continue",
"if",
"aid",
"not",
"in",
"self",
".",
"allocated_aids",
":",
"# Prefer the unique_id over the entitiy_id",
"storage_key",
"=",
"unique_id",
"or",
"entity_id",
"self",
".",
"allocations",
"[",
"storage_key",
"]",
"=",
"aid",
"self",
".",
"allocated_aids",
".",
"add",
"(",
"aid",
")",
"self",
".",
"async_schedule_save",
"(",
")",
"return",
"aid",
"raise",
"ValueError",
"(",
"f\"Unable to generate unique aid allocation for {entity_id} [{unique_id}]\"",
")"
] | [
101,
4
] | [
121,
9
] | python | en | ['en', 'en', 'en'] | True |
AccessoryAidStorage.delete_aid | (self, storage_key: str) | Delete an aid allocation. | Delete an aid allocation. | def delete_aid(self, storage_key: str):
"""Delete an aid allocation."""
if storage_key not in self.allocations:
return
aid = self.allocations.pop(storage_key)
self.allocated_aids.discard(aid)
self.async_schedule_save() | [
"def",
"delete_aid",
"(",
"self",
",",
"storage_key",
":",
"str",
")",
":",
"if",
"storage_key",
"not",
"in",
"self",
".",
"allocations",
":",
"return",
"aid",
"=",
"self",
".",
"allocations",
".",
"pop",
"(",
"storage_key",
")",
"self",
".",
"allocated_aids",
".",
"discard",
"(",
"aid",
")",
"self",
".",
"async_schedule_save",
"(",
")"
] | [
123,
4
] | [
130,
34
] | python | it | ['en', 'it', 'it'] | True |
AccessoryAidStorage.async_schedule_save | (self) | Schedule saving the entity map cache. | Schedule saving the entity map cache. | def async_schedule_save(self):
"""Schedule saving the entity map cache."""
self.store.async_delay_save(self._data_to_save, AID_MANAGER_SAVE_DELAY) | [
"def",
"async_schedule_save",
"(",
"self",
")",
":",
"self",
".",
"store",
".",
"async_delay_save",
"(",
"self",
".",
"_data_to_save",
",",
"AID_MANAGER_SAVE_DELAY",
")"
] | [
133,
4
] | [
135,
79
] | python | en | ['en', 'en', 'en'] | True |
AccessoryAidStorage.async_save | (self) | Save the entity map cache. | Save the entity map cache. | async def async_save(self):
"""Save the entity map cache."""
return await self.store.async_save(self._data_to_save()) | [
"async",
"def",
"async_save",
"(",
"self",
")",
":",
"return",
"await",
"self",
".",
"store",
".",
"async_save",
"(",
"self",
".",
"_data_to_save",
"(",
")",
")"
] | [
137,
4
] | [
139,
64
] | python | en | ['en', 'en', 'en'] | True |
AccessoryAidStorage._data_to_save | (self) | Return data of entity map to store in a file. | Return data of entity map to store in a file. | def _data_to_save(self):
"""Return data of entity map to store in a file."""
return {ALLOCATIONS_KEY: self.allocations} | [
"def",
"_data_to_save",
"(",
"self",
")",
":",
"return",
"{",
"ALLOCATIONS_KEY",
":",
"self",
".",
"allocations",
"}"
] | [
142,
4
] | [
144,
50
] | python | en | ['en', 'en', 'en'] | True |
build_flux_graph | (soln, raw, traced_element, path_save=None, overwrite=False, i0=0, i1='eq', constV=False) |
:param mechanism: type = dict, keys include "species", "reaction", "element", etc
:param raw: type = dict, keys include "mole_fraction", "net_reaction_rate", etc
:param traced_element: type = str
:param i0: type = int, specifying the starting point of the considered interval of the raw data
:param i1: type = int or str, specifying the ending point of the considered interval of the raw data
:return flux graph: type = networkx object, will be also saved as a .json file,
|
:param mechanism: type = dict, keys include "species", "reaction", "element", etc
:param raw: type = dict, keys include "mole_fraction", "net_reaction_rate", etc
:param traced_element: type = str
:param i0: type = int, specifying the starting point of the considered interval of the raw data
:param i1: type = int or str, specifying the ending point of the considered interval of the raw data
:return flux graph: type = networkx object, will be also saved as a .json file,
| def build_flux_graph(soln, raw, traced_element, path_save=None, overwrite=False, i0=0, i1='eq', constV=False):
"""
:param mechanism: type = dict, keys include "species", "reaction", "element", etc
:param raw: type = dict, keys include "mole_fraction", "net_reaction_rate", etc
:param traced_element: type = str
:param i0: type = int, specifying the starting point of the considered interval of the raw data
:param i1: type = int or str, specifying the ending point of the considered interval of the raw data
:return flux graph: type = networkx object, will be also saved as a .json file,
"""
element = soln.element_names
species = soln.species
reaction = soln.reaction
n_rxn = soln.n_reactions
""" --------------------------------
check if results already exist, if so, load
-------------------------------- """
if path_save is not None:
if overwrite is False:
try:
data = json.load(open(path_save, 'r'))
flux_graph = json_graph.node_link_graph(data)
return flux_graph
except IOError:
pass
""" --------------------------------
if not, then compute, and save
-------------------------------- """
# ---------------------------------------------
# check if traced_element is legal
if traced_element not in element:
raise('traced element ' + traced_element + ' is not listed in mechanism')
# ---------------------------------------------
# find the reaction rate during the considered interval
# unit will be converted to mole/sec
rr = np.reshape(raw['net_reaction_rate'][i0,:],[n_rxn,1])
flux_graph = DiGraph()
# -------------------------------------
# adding edge from reactions
# one edge may contribute from multiple reactions, the list of the contributors will be stored in edge['member']
# note though in .cti id_rxn starts from 1, in soln.reaction, id_rxn starts from 0
for id_rxn in range(n_rxn):
# sp_mu is a dict, where key is species, val is net stoichiometric coefficient
sp_mu = reaction(id_rxn).products
for sp in reaction(id_rxn).reactants.keys():
mu = reaction(id_rxn).reactants[sp]
if sp in sp_mu.keys():
sp_mu[sp] -= mu
else:
sp_mu[sp] = -mu
# -----------------------
# produced is a dict, where key is sp, val is number of traced atoms
# being transferred when this sp is produced
produced = {}
consumed = {}
for sp in sp_mu.keys():
atoms = species(sp).composition
if traced_element in atoms.keys():
n = int(sp_mu[sp] * atoms[traced_element] * np.sign(rr[id_rxn]))
if n > 0:
produced[sp] = abs(n)
elif n < 0:
consumed[sp] = abs(n)
# -----------------------
# consider this reaction only when traced element is transferred
# note "if bool(consumed)" works the same way
if bool(produced):
n_sum = sum(produced.values())
for target in produced.keys():
for source in consumed.keys():
n_i2j = 1.0 * produced[target] * consumed[source] / n_sum
# note that the direction (source-->target) is already assured
# therefore we use abs(RR) here
dw = float(n_i2j * abs(rr[id_rxn]))
try:
flux_graph[source][target]['flux'] += dw
except KeyError:
# if this edge doesn't exist, create it
flux_graph.add_edge(source, target)
flux_graph[source][target]['flux'] = dw
flux_graph[source][target]['member'] = {}
flux_graph[source][target]['member'][str(id_rxn)] = dw
flux_graph[source][target]['1/flux'] = 1.0 / flux_graph[source][target]['flux']
# -------------------------------------
# save the graph using json, which is fast, and human-readable
data = json_graph.node_link_data(flux_graph)
json.dump(data, open(path_save, 'w'))
#print 'graph saved as',path_save
return flux_graph | [
"def",
"build_flux_graph",
"(",
"soln",
",",
"raw",
",",
"traced_element",
",",
"path_save",
"=",
"None",
",",
"overwrite",
"=",
"False",
",",
"i0",
"=",
"0",
",",
"i1",
"=",
"'eq'",
",",
"constV",
"=",
"False",
")",
":",
"element",
"=",
"soln",
".",
"element_names",
"species",
"=",
"soln",
".",
"species",
"reaction",
"=",
"soln",
".",
"reaction",
"n_rxn",
"=",
"soln",
".",
"n_reactions",
"\"\"\" --------------------------------\n\tcheck if results already exist, if so, load\n\t-------------------------------- \"\"\"",
"if",
"path_save",
"is",
"not",
"None",
":",
"if",
"overwrite",
"is",
"False",
":",
"try",
":",
"data",
"=",
"json",
".",
"load",
"(",
"open",
"(",
"path_save",
",",
"'r'",
")",
")",
"flux_graph",
"=",
"json_graph",
".",
"node_link_graph",
"(",
"data",
")",
"return",
"flux_graph",
"except",
"IOError",
":",
"pass",
"\"\"\" --------------------------------\n\tif not, then compute, and save\n\t-------------------------------- \"\"\"",
"# ---------------------------------------------",
"# check if traced_element is legal",
"if",
"traced_element",
"not",
"in",
"element",
":",
"raise",
"(",
"'traced element '",
"+",
"traced_element",
"+",
"' is not listed in mechanism'",
")",
"# ---------------------------------------------",
"# find the reaction rate during the considered interval",
"# unit will be converted to mole/sec",
"rr",
"=",
"np",
".",
"reshape",
"(",
"raw",
"[",
"'net_reaction_rate'",
"]",
"[",
"i0",
",",
":",
"]",
",",
"[",
"n_rxn",
",",
"1",
"]",
")",
"flux_graph",
"=",
"DiGraph",
"(",
")",
"# -------------------------------------",
"# adding edge from reactions",
"# one edge may contribute from multiple reactions, the list of the contributors will be stored in edge['member']",
"# note though in .cti id_rxn starts from 1, in soln.reaction, id_rxn starts from 0",
"for",
"id_rxn",
"in",
"range",
"(",
"n_rxn",
")",
":",
"# sp_mu is a dict, where key is species, val is net stoichiometric coefficient",
"sp_mu",
"=",
"reaction",
"(",
"id_rxn",
")",
".",
"products",
"for",
"sp",
"in",
"reaction",
"(",
"id_rxn",
")",
".",
"reactants",
".",
"keys",
"(",
")",
":",
"mu",
"=",
"reaction",
"(",
"id_rxn",
")",
".",
"reactants",
"[",
"sp",
"]",
"if",
"sp",
"in",
"sp_mu",
".",
"keys",
"(",
")",
":",
"sp_mu",
"[",
"sp",
"]",
"-=",
"mu",
"else",
":",
"sp_mu",
"[",
"sp",
"]",
"=",
"-",
"mu",
"# -----------------------",
"# produced is a dict, where key is sp, val is number of traced atoms",
"# being transferred when this sp is produced",
"produced",
"=",
"{",
"}",
"consumed",
"=",
"{",
"}",
"for",
"sp",
"in",
"sp_mu",
".",
"keys",
"(",
")",
":",
"atoms",
"=",
"species",
"(",
"sp",
")",
".",
"composition",
"if",
"traced_element",
"in",
"atoms",
".",
"keys",
"(",
")",
":",
"n",
"=",
"int",
"(",
"sp_mu",
"[",
"sp",
"]",
"*",
"atoms",
"[",
"traced_element",
"]",
"*",
"np",
".",
"sign",
"(",
"rr",
"[",
"id_rxn",
"]",
")",
")",
"if",
"n",
">",
"0",
":",
"produced",
"[",
"sp",
"]",
"=",
"abs",
"(",
"n",
")",
"elif",
"n",
"<",
"0",
":",
"consumed",
"[",
"sp",
"]",
"=",
"abs",
"(",
"n",
")",
"# -----------------------",
"# consider this reaction only when traced element is transferred",
"# note \"if bool(consumed)\" works the same way",
"if",
"bool",
"(",
"produced",
")",
":",
"n_sum",
"=",
"sum",
"(",
"produced",
".",
"values",
"(",
")",
")",
"for",
"target",
"in",
"produced",
".",
"keys",
"(",
")",
":",
"for",
"source",
"in",
"consumed",
".",
"keys",
"(",
")",
":",
"n_i2j",
"=",
"1.0",
"*",
"produced",
"[",
"target",
"]",
"*",
"consumed",
"[",
"source",
"]",
"/",
"n_sum",
"# note that the direction (source-->target) is already assured",
"# therefore we use abs(RR) here",
"dw",
"=",
"float",
"(",
"n_i2j",
"*",
"abs",
"(",
"rr",
"[",
"id_rxn",
"]",
")",
")",
"try",
":",
"flux_graph",
"[",
"source",
"]",
"[",
"target",
"]",
"[",
"'flux'",
"]",
"+=",
"dw",
"except",
"KeyError",
":",
"# if this edge doesn't exist, create it",
"flux_graph",
".",
"add_edge",
"(",
"source",
",",
"target",
")",
"flux_graph",
"[",
"source",
"]",
"[",
"target",
"]",
"[",
"'flux'",
"]",
"=",
"dw",
"flux_graph",
"[",
"source",
"]",
"[",
"target",
"]",
"[",
"'member'",
"]",
"=",
"{",
"}",
"flux_graph",
"[",
"source",
"]",
"[",
"target",
"]",
"[",
"'member'",
"]",
"[",
"str",
"(",
"id_rxn",
")",
"]",
"=",
"dw",
"flux_graph",
"[",
"source",
"]",
"[",
"target",
"]",
"[",
"'1/flux'",
"]",
"=",
"1.0",
"/",
"flux_graph",
"[",
"source",
"]",
"[",
"target",
"]",
"[",
"'flux'",
"]",
"# -------------------------------------",
"# save the graph using json, which is fast, and human-readable",
"data",
"=",
"json_graph",
".",
"node_link_data",
"(",
"flux_graph",
")",
"json",
".",
"dump",
"(",
"data",
",",
"open",
"(",
"path_save",
",",
"'w'",
")",
")",
"#print 'graph saved as',path_save",
"return",
"flux_graph"
] | [
16,
0
] | [
128,
18
] | python | en | ['en', 'error', 'th'] | False |
async_setup | (hass, config) | Set up the Mailgun component. | Set up the Mailgun component. | async def async_setup(hass, config):
"""Set up the Mailgun component."""
if DOMAIN not in config:
return True
hass.data[DOMAIN] = config[DOMAIN]
return True | [
"async",
"def",
"async_setup",
"(",
"hass",
",",
"config",
")",
":",
"if",
"DOMAIN",
"not",
"in",
"config",
":",
"return",
"True",
"hass",
".",
"data",
"[",
"DOMAIN",
"]",
"=",
"config",
"[",
"DOMAIN",
"]",
"return",
"True"
] | [
36,
0
] | [
42,
15
] | python | en | ['en', 'fr', 'en'] | True |
handle_webhook | (hass, webhook_id, request) | Handle incoming webhook with Mailgun inbound messages. | Handle incoming webhook with Mailgun inbound messages. | async def handle_webhook(hass, webhook_id, request):
"""Handle incoming webhook with Mailgun inbound messages."""
body = await request.text()
try:
data = json.loads(body) if body else {}
except ValueError:
return None
if isinstance(data, dict) and "signature" in data:
if await verify_webhook(hass, **data["signature"]):
data["webhook_id"] = webhook_id
hass.bus.async_fire(MESSAGE_RECEIVED, data)
return
_LOGGER.warning(
"Mailgun webhook received an unauthenticated message - webhook_id: %s",
webhook_id,
) | [
"async",
"def",
"handle_webhook",
"(",
"hass",
",",
"webhook_id",
",",
"request",
")",
":",
"body",
"=",
"await",
"request",
".",
"text",
"(",
")",
"try",
":",
"data",
"=",
"json",
".",
"loads",
"(",
"body",
")",
"if",
"body",
"else",
"{",
"}",
"except",
"ValueError",
":",
"return",
"None",
"if",
"isinstance",
"(",
"data",
",",
"dict",
")",
"and",
"\"signature\"",
"in",
"data",
":",
"if",
"await",
"verify_webhook",
"(",
"hass",
",",
"*",
"*",
"data",
"[",
"\"signature\"",
"]",
")",
":",
"data",
"[",
"\"webhook_id\"",
"]",
"=",
"webhook_id",
"hass",
".",
"bus",
".",
"async_fire",
"(",
"MESSAGE_RECEIVED",
",",
"data",
")",
"return",
"_LOGGER",
".",
"warning",
"(",
"\"Mailgun webhook received an unauthenticated message - webhook_id: %s\"",
",",
"webhook_id",
",",
")"
] | [
45,
0
] | [
62,
5
] | python | en | ['en', 'nl', 'en'] | True |
verify_webhook | (hass, token=None, timestamp=None, signature=None) | Verify webhook was signed by Mailgun. | Verify webhook was signed by Mailgun. | async def verify_webhook(hass, token=None, timestamp=None, signature=None):
"""Verify webhook was signed by Mailgun."""
if DOMAIN not in hass.data:
_LOGGER.warning("Cannot validate Mailgun webhook, missing API Key")
return True
if not (token and timestamp and signature):
return False
hmac_digest = hmac.new(
key=bytes(hass.data[DOMAIN][CONF_API_KEY], "utf-8"),
msg=bytes(f"{timestamp}{token}", "utf-8"),
digestmod=hashlib.sha256,
).hexdigest()
return hmac.compare_digest(signature, hmac_digest) | [
"async",
"def",
"verify_webhook",
"(",
"hass",
",",
"token",
"=",
"None",
",",
"timestamp",
"=",
"None",
",",
"signature",
"=",
"None",
")",
":",
"if",
"DOMAIN",
"not",
"in",
"hass",
".",
"data",
":",
"_LOGGER",
".",
"warning",
"(",
"\"Cannot validate Mailgun webhook, missing API Key\"",
")",
"return",
"True",
"if",
"not",
"(",
"token",
"and",
"timestamp",
"and",
"signature",
")",
":",
"return",
"False",
"hmac_digest",
"=",
"hmac",
".",
"new",
"(",
"key",
"=",
"bytes",
"(",
"hass",
".",
"data",
"[",
"DOMAIN",
"]",
"[",
"CONF_API_KEY",
"]",
",",
"\"utf-8\"",
")",
",",
"msg",
"=",
"bytes",
"(",
"f\"{timestamp}{token}\"",
",",
"\"utf-8\"",
")",
",",
"digestmod",
"=",
"hashlib",
".",
"sha256",
",",
")",
".",
"hexdigest",
"(",
")",
"return",
"hmac",
".",
"compare_digest",
"(",
"signature",
",",
"hmac_digest",
")"
] | [
65,
0
] | [
80,
54
] | python | en | ['en', 'en', 'en'] | True |
async_setup_entry | (hass, entry) | Configure based on config entry. | Configure based on config entry. | async def async_setup_entry(hass, entry):
"""Configure based on config entry."""
hass.components.webhook.async_register(
DOMAIN, "Mailgun", entry.data[CONF_WEBHOOK_ID], handle_webhook
)
return True | [
"async",
"def",
"async_setup_entry",
"(",
"hass",
",",
"entry",
")",
":",
"hass",
".",
"components",
".",
"webhook",
".",
"async_register",
"(",
"DOMAIN",
",",
"\"Mailgun\"",
",",
"entry",
".",
"data",
"[",
"CONF_WEBHOOK_ID",
"]",
",",
"handle_webhook",
")",
"return",
"True"
] | [
83,
0
] | [
88,
15
] | 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."""
hass.components.webhook.async_unregister(entry.data[CONF_WEBHOOK_ID])
return True | [
"async",
"def",
"async_unload_entry",
"(",
"hass",
",",
"entry",
")",
":",
"hass",
".",
"components",
".",
"webhook",
".",
"async_unregister",
"(",
"entry",
".",
"data",
"[",
"CONF_WEBHOOK_ID",
"]",
")",
"return",
"True"
] | [
91,
0
] | [
94,
15
] | python | en | ['en', 'es', 'en'] | True |
calls | (hass, fixture) | Return a list of Dialogflow calls triggered. | Return a list of Dialogflow calls triggered. | async def calls(hass, fixture):
"""Return a list of Dialogflow calls triggered."""
calls = []
@callback
def mock_service(call):
"""Mock action call."""
calls.append(call)
hass.services.async_register("test", "dialogflow", mock_service)
return calls | [
"async",
"def",
"calls",
"(",
"hass",
",",
"fixture",
")",
":",
"calls",
"=",
"[",
"]",
"@",
"callback",
"def",
"mock_service",
"(",
"call",
")",
":",
"\"\"\"Mock action call.\"\"\"",
"calls",
".",
"append",
"(",
"call",
")",
"hass",
".",
"services",
".",
"async_register",
"(",
"\"test\"",
",",
"\"dialogflow\"",
",",
"mock_service",
")",
"return",
"calls"
] | [
21,
0
] | [
32,
16
] | python | en | ['en', 'ca', 'en'] | True |
fixture | (hass, aiohttp_client) | Initialize a Home Assistant server for testing this module. | Initialize a Home Assistant server for testing this module. | async def fixture(hass, aiohttp_client):
"""Initialize a Home Assistant server for testing this module."""
await async_setup_component(hass, dialogflow.DOMAIN, {"dialogflow": {}})
await async_setup_component(
hass,
intent_script.DOMAIN,
{
"intent_script": {
"WhereAreWeIntent": {
"speech": {
"type": "plain",
"text": """
{%- if is_state("device_tracker.paulus", "home")
and is_state("device_tracker.anne_therese",
"home") -%}
You are both home, you silly
{%- else -%}
Anne Therese is at {{
states("device_tracker.anne_therese")
}} and Paulus is at {{
states("device_tracker.paulus")
}}
{% endif %}
""",
}
},
"GetZodiacHoroscopeIntent": {
"speech": {
"type": "plain",
"text": "You told us your sign is {{ ZodiacSign }}.",
}
},
"CallServiceIntent": {
"speech": {"type": "plain", "text": "Service called"},
"action": {
"service": "test.dialogflow",
"data_template": {"hello": "{{ ZodiacSign }}"},
"entity_id": "switch.test",
},
},
}
},
)
await async_process_ha_core_config(
hass,
{"internal_url": "http://example.local:8123"},
)
result = await hass.config_entries.flow.async_init(
"dialogflow", context={"source": "user"}
)
assert result["type"] == data_entry_flow.RESULT_TYPE_FORM, result
result = await hass.config_entries.flow.async_configure(result["flow_id"], {})
assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY
webhook_id = result["result"].data["webhook_id"]
return await aiohttp_client(hass.http.app), webhook_id | [
"async",
"def",
"fixture",
"(",
"hass",
",",
"aiohttp_client",
")",
":",
"await",
"async_setup_component",
"(",
"hass",
",",
"dialogflow",
".",
"DOMAIN",
",",
"{",
"\"dialogflow\"",
":",
"{",
"}",
"}",
")",
"await",
"async_setup_component",
"(",
"hass",
",",
"intent_script",
".",
"DOMAIN",
",",
"{",
"\"intent_script\"",
":",
"{",
"\"WhereAreWeIntent\"",
":",
"{",
"\"speech\"",
":",
"{",
"\"type\"",
":",
"\"plain\"",
",",
"\"text\"",
":",
"\"\"\"\n {%- if is_state(\"device_tracker.paulus\", \"home\")\n and is_state(\"device_tracker.anne_therese\",\n \"home\") -%}\n You are both home, you silly\n {%- else -%}\n Anne Therese is at {{\n states(\"device_tracker.anne_therese\")\n }} and Paulus is at {{\n states(\"device_tracker.paulus\")\n }}\n {% endif %}\n \"\"\"",
",",
"}",
"}",
",",
"\"GetZodiacHoroscopeIntent\"",
":",
"{",
"\"speech\"",
":",
"{",
"\"type\"",
":",
"\"plain\"",
",",
"\"text\"",
":",
"\"You told us your sign is {{ ZodiacSign }}.\"",
",",
"}",
"}",
",",
"\"CallServiceIntent\"",
":",
"{",
"\"speech\"",
":",
"{",
"\"type\"",
":",
"\"plain\"",
",",
"\"text\"",
":",
"\"Service called\"",
"}",
",",
"\"action\"",
":",
"{",
"\"service\"",
":",
"\"test.dialogflow\"",
",",
"\"data_template\"",
":",
"{",
"\"hello\"",
":",
"\"{{ ZodiacSign }}\"",
"}",
",",
"\"entity_id\"",
":",
"\"switch.test\"",
",",
"}",
",",
"}",
",",
"}",
"}",
",",
")",
"await",
"async_process_ha_core_config",
"(",
"hass",
",",
"{",
"\"internal_url\"",
":",
"\"http://example.local:8123\"",
"}",
",",
")",
"result",
"=",
"await",
"hass",
".",
"config_entries",
".",
"flow",
".",
"async_init",
"(",
"\"dialogflow\"",
",",
"context",
"=",
"{",
"\"source\"",
":",
"\"user\"",
"}",
")",
"assert",
"result",
"[",
"\"type\"",
"]",
"==",
"data_entry_flow",
".",
"RESULT_TYPE_FORM",
",",
"result",
"result",
"=",
"await",
"hass",
".",
"config_entries",
".",
"flow",
".",
"async_configure",
"(",
"result",
"[",
"\"flow_id\"",
"]",
",",
"{",
"}",
")",
"assert",
"result",
"[",
"\"type\"",
"]",
"==",
"data_entry_flow",
".",
"RESULT_TYPE_CREATE_ENTRY",
"webhook_id",
"=",
"result",
"[",
"\"result\"",
"]",
".",
"data",
"[",
"\"webhook_id\"",
"]",
"return",
"await",
"aiohttp_client",
"(",
"hass",
".",
"http",
".",
"app",
")",
",",
"webhook_id"
] | [
36,
0
] | [
94,
58
] | python | en | ['en', 'en', 'en'] | True |
test_v1_data | () | Test for version 1 api based on message. | Test for version 1 api based on message. | async def test_v1_data():
"""Test for version 1 api based on message."""
assert dialogflow.get_api_version(Data.v1) == 1 | [
"async",
"def",
"test_v1_data",
"(",
")",
":",
"assert",
"dialogflow",
".",
"get_api_version",
"(",
"Data",
".",
"v1",
")",
"==",
"1"
] | [
154,
0
] | [
156,
51
] | python | en | ['en', 'da', 'en'] | True |
test_v2_data | () | Test for version 2 api based on message. | Test for version 2 api based on message. | async def test_v2_data():
"""Test for version 2 api based on message."""
assert dialogflow.get_api_version(Data.v2) == 2 | [
"async",
"def",
"test_v2_data",
"(",
")",
":",
"assert",
"dialogflow",
".",
"get_api_version",
"(",
"Data",
".",
"v2",
")",
"==",
"2"
] | [
159,
0
] | [
161,
51
] | python | en | ['en', 'da', 'en'] | True |
test_intent_action_incomplete_v1 | (fixture) | Test when action is not completed. | Test when action is not completed. | async def test_intent_action_incomplete_v1(fixture):
"""Test when action is not completed."""
mock_client, webhook_id = fixture
data = Data.v1
data["result"]["actionIncomplete"] = True
response = await mock_client.post(
f"/api/webhook/{webhook_id}", data=json.dumps(data)
)
assert response.status == 200
assert await response.text() == "" | [
"async",
"def",
"test_intent_action_incomplete_v1",
"(",
"fixture",
")",
":",
"mock_client",
",",
"webhook_id",
"=",
"fixture",
"data",
"=",
"Data",
".",
"v1",
"data",
"[",
"\"result\"",
"]",
"[",
"\"actionIncomplete\"",
"]",
"=",
"True",
"response",
"=",
"await",
"mock_client",
".",
"post",
"(",
"f\"/api/webhook/{webhook_id}\"",
",",
"data",
"=",
"json",
".",
"dumps",
"(",
"data",
")",
")",
"assert",
"response",
".",
"status",
"==",
"200",
"assert",
"await",
"response",
".",
"text",
"(",
")",
"==",
"\"\""
] | [
164,
0
] | [
174,
38
] | python | en | ['en', 'en', 'en'] | True |
test_intent_action_incomplete_v2 | (fixture) | Test when action is not completed. | Test when action is not completed. | async def test_intent_action_incomplete_v2(fixture):
"""Test when action is not completed."""
mock_client, webhook_id = fixture
data = Data.v2
data["queryResult"]["allRequiredParamsPresent"] = False
response = await mock_client.post(
f"/api/webhook/{webhook_id}", data=json.dumps(data)
)
assert response.status == 200
assert await response.text() == "" | [
"async",
"def",
"test_intent_action_incomplete_v2",
"(",
"fixture",
")",
":",
"mock_client",
",",
"webhook_id",
"=",
"fixture",
"data",
"=",
"Data",
".",
"v2",
"data",
"[",
"\"queryResult\"",
"]",
"[",
"\"allRequiredParamsPresent\"",
"]",
"=",
"False",
"response",
"=",
"await",
"mock_client",
".",
"post",
"(",
"f\"/api/webhook/{webhook_id}\"",
",",
"data",
"=",
"json",
".",
"dumps",
"(",
"data",
")",
")",
"assert",
"response",
".",
"status",
"==",
"200",
"assert",
"await",
"response",
".",
"text",
"(",
")",
"==",
"\"\""
] | [
177,
0
] | [
187,
38
] | python | en | ['en', 'en', 'en'] | True |
test_intent_slot_filling_v1 | (fixture) | Test when Dialogflow asks for slot-filling return none. | Test when Dialogflow asks for slot-filling return none. | async def test_intent_slot_filling_v1(fixture):
"""Test when Dialogflow asks for slot-filling return none."""
mock_client, webhook_id = fixture
data = Data.v1
data["result"].update(
resolvedQuery="my zodiac sign is",
speech="",
actionIncomplete=True,
parameters={"ZodiacSign": ""},
contexts=[
{
"name": CONTEXT_NAME,
"parameters": {"ZodiacSign.original": "", "ZodiacSign": ""},
"lifespan": 2,
},
{
"name": "tests_ha_dialog_context",
"parameters": {"ZodiacSign.original": "", "ZodiacSign": ""},
"lifespan": 2,
},
{
"name": "tests_ha_dialog_params_zodiacsign",
"parameters": {"ZodiacSign.original": "", "ZodiacSign": ""},
"lifespan": 1,
},
],
fulfillment={
"speech": "What is the ZodiacSign?",
"messages": [{"type": 0, "speech": "What is the ZodiacSign?"}],
},
score=0.77,
)
data["result"]["metadata"].update(webhookForSlotFillingUsed="true")
response = await mock_client.post(
f"/api/webhook/{webhook_id}", data=json.dumps(data)
)
assert response.status == 200
assert await response.text() == "" | [
"async",
"def",
"test_intent_slot_filling_v1",
"(",
"fixture",
")",
":",
"mock_client",
",",
"webhook_id",
"=",
"fixture",
"data",
"=",
"Data",
".",
"v1",
"data",
"[",
"\"result\"",
"]",
".",
"update",
"(",
"resolvedQuery",
"=",
"\"my zodiac sign is\"",
",",
"speech",
"=",
"\"\"",
",",
"actionIncomplete",
"=",
"True",
",",
"parameters",
"=",
"{",
"\"ZodiacSign\"",
":",
"\"\"",
"}",
",",
"contexts",
"=",
"[",
"{",
"\"name\"",
":",
"CONTEXT_NAME",
",",
"\"parameters\"",
":",
"{",
"\"ZodiacSign.original\"",
":",
"\"\"",
",",
"\"ZodiacSign\"",
":",
"\"\"",
"}",
",",
"\"lifespan\"",
":",
"2",
",",
"}",
",",
"{",
"\"name\"",
":",
"\"tests_ha_dialog_context\"",
",",
"\"parameters\"",
":",
"{",
"\"ZodiacSign.original\"",
":",
"\"\"",
",",
"\"ZodiacSign\"",
":",
"\"\"",
"}",
",",
"\"lifespan\"",
":",
"2",
",",
"}",
",",
"{",
"\"name\"",
":",
"\"tests_ha_dialog_params_zodiacsign\"",
",",
"\"parameters\"",
":",
"{",
"\"ZodiacSign.original\"",
":",
"\"\"",
",",
"\"ZodiacSign\"",
":",
"\"\"",
"}",
",",
"\"lifespan\"",
":",
"1",
",",
"}",
",",
"]",
",",
"fulfillment",
"=",
"{",
"\"speech\"",
":",
"\"What is the ZodiacSign?\"",
",",
"\"messages\"",
":",
"[",
"{",
"\"type\"",
":",
"0",
",",
"\"speech\"",
":",
"\"What is the ZodiacSign?\"",
"}",
"]",
",",
"}",
",",
"score",
"=",
"0.77",
",",
")",
"data",
"[",
"\"result\"",
"]",
"[",
"\"metadata\"",
"]",
".",
"update",
"(",
"webhookForSlotFillingUsed",
"=",
"\"true\"",
")",
"response",
"=",
"await",
"mock_client",
".",
"post",
"(",
"f\"/api/webhook/{webhook_id}\"",
",",
"data",
"=",
"json",
".",
"dumps",
"(",
"data",
")",
")",
"assert",
"response",
".",
"status",
"==",
"200",
"assert",
"await",
"response",
".",
"text",
"(",
")",
"==",
"\"\""
] | [
190,
0
] | [
229,
38
] | python | en | ['en', 'fr', 'en'] | True |
test_intent_request_with_parameters_v1 | (fixture) | Test a request with parameters. | Test a request with parameters. | async def test_intent_request_with_parameters_v1(fixture):
"""Test a request with parameters."""
mock_client, webhook_id = fixture
data = Data.v1
response = await mock_client.post(
f"/api/webhook/{webhook_id}", data=json.dumps(data)
)
assert response.status == 200
text = (await response.json()).get("speech")
assert text == "You told us your sign is virgo." | [
"async",
"def",
"test_intent_request_with_parameters_v1",
"(",
"fixture",
")",
":",
"mock_client",
",",
"webhook_id",
"=",
"fixture",
"data",
"=",
"Data",
".",
"v1",
"response",
"=",
"await",
"mock_client",
".",
"post",
"(",
"f\"/api/webhook/{webhook_id}\"",
",",
"data",
"=",
"json",
".",
"dumps",
"(",
"data",
")",
")",
"assert",
"response",
".",
"status",
"==",
"200",
"text",
"=",
"(",
"await",
"response",
".",
"json",
"(",
")",
")",
".",
"get",
"(",
"\"speech\"",
")",
"assert",
"text",
"==",
"\"You told us your sign is virgo.\""
] | [
232,
0
] | [
241,
52
] | python | en | ['en', 'en', 'en'] | True |
test_intent_request_with_parameters_v2 | (fixture) | Test a request with parameters. | Test a request with parameters. | async def test_intent_request_with_parameters_v2(fixture):
"""Test a request with parameters."""
mock_client, webhook_id = fixture
data = Data.v2
response = await mock_client.post(
f"/api/webhook/{webhook_id}", data=json.dumps(data)
)
assert response.status == 200
text = (await response.json()).get("fulfillmentText")
assert text == "You told us your sign is virgo." | [
"async",
"def",
"test_intent_request_with_parameters_v2",
"(",
"fixture",
")",
":",
"mock_client",
",",
"webhook_id",
"=",
"fixture",
"data",
"=",
"Data",
".",
"v2",
"response",
"=",
"await",
"mock_client",
".",
"post",
"(",
"f\"/api/webhook/{webhook_id}\"",
",",
"data",
"=",
"json",
".",
"dumps",
"(",
"data",
")",
")",
"assert",
"response",
".",
"status",
"==",
"200",
"text",
"=",
"(",
"await",
"response",
".",
"json",
"(",
")",
")",
".",
"get",
"(",
"\"fulfillmentText\"",
")",
"assert",
"text",
"==",
"\"You told us your sign is virgo.\""
] | [
244,
0
] | [
253,
52
] | python | en | ['en', 'en', 'en'] | True |
test_intent_request_with_parameters_but_empty_v1 | (fixture) | Test a request with parameters but empty value. | Test a request with parameters but empty value. | async def test_intent_request_with_parameters_but_empty_v1(fixture):
"""Test a request with parameters but empty value."""
mock_client, webhook_id = fixture
data = Data.v1
data["result"].update(parameters={"ZodiacSign": ""})
response = await mock_client.post(
f"/api/webhook/{webhook_id}", data=json.dumps(data)
)
assert response.status == 200
text = (await response.json()).get("speech")
assert text == "You told us your sign is ." | [
"async",
"def",
"test_intent_request_with_parameters_but_empty_v1",
"(",
"fixture",
")",
":",
"mock_client",
",",
"webhook_id",
"=",
"fixture",
"data",
"=",
"Data",
".",
"v1",
"data",
"[",
"\"result\"",
"]",
".",
"update",
"(",
"parameters",
"=",
"{",
"\"ZodiacSign\"",
":",
"\"\"",
"}",
")",
"response",
"=",
"await",
"mock_client",
".",
"post",
"(",
"f\"/api/webhook/{webhook_id}\"",
",",
"data",
"=",
"json",
".",
"dumps",
"(",
"data",
")",
")",
"assert",
"response",
".",
"status",
"==",
"200",
"text",
"=",
"(",
"await",
"response",
".",
"json",
"(",
")",
")",
".",
"get",
"(",
"\"speech\"",
")",
"assert",
"text",
"==",
"\"You told us your sign is .\""
] | [
256,
0
] | [
266,
47
] | python | en | ['en', 'en', 'en'] | True |
test_intent_request_with_parameters_but_empty_v2 | (fixture) | Test a request with parameters but empty value. | Test a request with parameters but empty value. | async def test_intent_request_with_parameters_but_empty_v2(fixture):
"""Test a request with parameters but empty value."""
mock_client, webhook_id = fixture
data = Data.v2
data["queryResult"].update(parameters={"ZodiacSign": ""})
response = await mock_client.post(
f"/api/webhook/{webhook_id}", data=json.dumps(data)
)
assert response.status == 200
text = (await response.json()).get("fulfillmentText")
assert text == "You told us your sign is ." | [
"async",
"def",
"test_intent_request_with_parameters_but_empty_v2",
"(",
"fixture",
")",
":",
"mock_client",
",",
"webhook_id",
"=",
"fixture",
"data",
"=",
"Data",
".",
"v2",
"data",
"[",
"\"queryResult\"",
"]",
".",
"update",
"(",
"parameters",
"=",
"{",
"\"ZodiacSign\"",
":",
"\"\"",
"}",
")",
"response",
"=",
"await",
"mock_client",
".",
"post",
"(",
"f\"/api/webhook/{webhook_id}\"",
",",
"data",
"=",
"json",
".",
"dumps",
"(",
"data",
")",
")",
"assert",
"response",
".",
"status",
"==",
"200",
"text",
"=",
"(",
"await",
"response",
".",
"json",
"(",
")",
")",
".",
"get",
"(",
"\"fulfillmentText\"",
")",
"assert",
"text",
"==",
"\"You told us your sign is .\""
] | [
269,
0
] | [
279,
47
] | python | en | ['en', 'en', 'en'] | True |
test_intent_request_without_slots_v1 | (hass, fixture) | Test a request without slots. | Test a request without slots. | async def test_intent_request_without_slots_v1(hass, fixture):
"""Test a request without slots."""
mock_client, webhook_id = fixture
data = Data.v1
data["result"].update(
resolvedQuery="where are we",
action="WhereAreWeIntent",
parameters={},
contexts=[],
)
response = await mock_client.post(
f"/api/webhook/{webhook_id}", data=json.dumps(data)
)
assert response.status == 200
text = (await response.json()).get("speech")
assert text == "Anne Therese is at unknown and Paulus is at unknown"
hass.states.async_set("device_tracker.paulus", "home")
hass.states.async_set("device_tracker.anne_therese", "home")
response = await mock_client.post(
f"/api/webhook/{webhook_id}", data=json.dumps(data)
)
assert response.status == 200
text = (await response.json()).get("speech")
assert text == "You are both home, you silly" | [
"async",
"def",
"test_intent_request_without_slots_v1",
"(",
"hass",
",",
"fixture",
")",
":",
"mock_client",
",",
"webhook_id",
"=",
"fixture",
"data",
"=",
"Data",
".",
"v1",
"data",
"[",
"\"result\"",
"]",
".",
"update",
"(",
"resolvedQuery",
"=",
"\"where are we\"",
",",
"action",
"=",
"\"WhereAreWeIntent\"",
",",
"parameters",
"=",
"{",
"}",
",",
"contexts",
"=",
"[",
"]",
",",
")",
"response",
"=",
"await",
"mock_client",
".",
"post",
"(",
"f\"/api/webhook/{webhook_id}\"",
",",
"data",
"=",
"json",
".",
"dumps",
"(",
"data",
")",
")",
"assert",
"response",
".",
"status",
"==",
"200",
"text",
"=",
"(",
"await",
"response",
".",
"json",
"(",
")",
")",
".",
"get",
"(",
"\"speech\"",
")",
"assert",
"text",
"==",
"\"Anne Therese is at unknown and Paulus is at unknown\"",
"hass",
".",
"states",
".",
"async_set",
"(",
"\"device_tracker.paulus\"",
",",
"\"home\"",
")",
"hass",
".",
"states",
".",
"async_set",
"(",
"\"device_tracker.anne_therese\"",
",",
"\"home\"",
")",
"response",
"=",
"await",
"mock_client",
".",
"post",
"(",
"f\"/api/webhook/{webhook_id}\"",
",",
"data",
"=",
"json",
".",
"dumps",
"(",
"data",
")",
")",
"assert",
"response",
".",
"status",
"==",
"200",
"text",
"=",
"(",
"await",
"response",
".",
"json",
"(",
")",
")",
".",
"get",
"(",
"\"speech\"",
")",
"assert",
"text",
"==",
"\"You are both home, you silly\""
] | [
282,
0
] | [
309,
49
] | python | en | ['en', 'en', 'en'] | True |
test_intent_request_without_slots_v2 | (hass, fixture) | Test a request without slots. | Test a request without slots. | async def test_intent_request_without_slots_v2(hass, fixture):
"""Test a request without slots."""
mock_client, webhook_id = fixture
data = Data.v2
data["queryResult"].update(
queryText="where are we",
action="WhereAreWeIntent",
parameters={},
outputContexts=[],
)
response = await mock_client.post(
f"/api/webhook/{webhook_id}", data=json.dumps(data)
)
assert response.status == 200
text = (await response.json()).get("fulfillmentText")
assert text == "Anne Therese is at unknown and Paulus is at unknown"
hass.states.async_set("device_tracker.paulus", "home")
hass.states.async_set("device_tracker.anne_therese", "home")
response = await mock_client.post(
f"/api/webhook/{webhook_id}", data=json.dumps(data)
)
assert response.status == 200
text = (await response.json()).get("fulfillmentText")
assert text == "You are both home, you silly" | [
"async",
"def",
"test_intent_request_without_slots_v2",
"(",
"hass",
",",
"fixture",
")",
":",
"mock_client",
",",
"webhook_id",
"=",
"fixture",
"data",
"=",
"Data",
".",
"v2",
"data",
"[",
"\"queryResult\"",
"]",
".",
"update",
"(",
"queryText",
"=",
"\"where are we\"",
",",
"action",
"=",
"\"WhereAreWeIntent\"",
",",
"parameters",
"=",
"{",
"}",
",",
"outputContexts",
"=",
"[",
"]",
",",
")",
"response",
"=",
"await",
"mock_client",
".",
"post",
"(",
"f\"/api/webhook/{webhook_id}\"",
",",
"data",
"=",
"json",
".",
"dumps",
"(",
"data",
")",
")",
"assert",
"response",
".",
"status",
"==",
"200",
"text",
"=",
"(",
"await",
"response",
".",
"json",
"(",
")",
")",
".",
"get",
"(",
"\"fulfillmentText\"",
")",
"assert",
"text",
"==",
"\"Anne Therese is at unknown and Paulus is at unknown\"",
"hass",
".",
"states",
".",
"async_set",
"(",
"\"device_tracker.paulus\"",
",",
"\"home\"",
")",
"hass",
".",
"states",
".",
"async_set",
"(",
"\"device_tracker.anne_therese\"",
",",
"\"home\"",
")",
"response",
"=",
"await",
"mock_client",
".",
"post",
"(",
"f\"/api/webhook/{webhook_id}\"",
",",
"data",
"=",
"json",
".",
"dumps",
"(",
"data",
")",
")",
"assert",
"response",
".",
"status",
"==",
"200",
"text",
"=",
"(",
"await",
"response",
".",
"json",
"(",
")",
")",
".",
"get",
"(",
"\"fulfillmentText\"",
")",
"assert",
"text",
"==",
"\"You are both home, you silly\""
] | [
312,
0
] | [
339,
49
] | python | en | ['en', 'en', 'en'] | True |
test_intent_request_calling_service_v1 | (fixture, calls) | Test a request for calling a service.
If this request is done async the test could finish before the action
has been executed. Hard to test because it will be a race condition.
| Test a request for calling a service. | async def test_intent_request_calling_service_v1(fixture, calls):
"""Test a request for calling a service.
If this request is done async the test could finish before the action
has been executed. Hard to test because it will be a race condition.
"""
mock_client, webhook_id = fixture
data = Data.v1
data["result"]["action"] = "CallServiceIntent"
call_count = len(calls)
response = await mock_client.post(
f"/api/webhook/{webhook_id}", data=json.dumps(data)
)
assert response.status == 200
assert len(calls) == call_count + 1
call = calls[-1]
assert call.domain == "test"
assert call.service == "dialogflow"
assert call.data.get("entity_id") == ["switch.test"]
assert call.data.get("hello") == "virgo" | [
"async",
"def",
"test_intent_request_calling_service_v1",
"(",
"fixture",
",",
"calls",
")",
":",
"mock_client",
",",
"webhook_id",
"=",
"fixture",
"data",
"=",
"Data",
".",
"v1",
"data",
"[",
"\"result\"",
"]",
"[",
"\"action\"",
"]",
"=",
"\"CallServiceIntent\"",
"call_count",
"=",
"len",
"(",
"calls",
")",
"response",
"=",
"await",
"mock_client",
".",
"post",
"(",
"f\"/api/webhook/{webhook_id}\"",
",",
"data",
"=",
"json",
".",
"dumps",
"(",
"data",
")",
")",
"assert",
"response",
".",
"status",
"==",
"200",
"assert",
"len",
"(",
"calls",
")",
"==",
"call_count",
"+",
"1",
"call",
"=",
"calls",
"[",
"-",
"1",
"]",
"assert",
"call",
".",
"domain",
"==",
"\"test\"",
"assert",
"call",
".",
"service",
"==",
"\"dialogflow\"",
"assert",
"call",
".",
"data",
".",
"get",
"(",
"\"entity_id\"",
")",
"==",
"[",
"\"switch.test\"",
"]",
"assert",
"call",
".",
"data",
".",
"get",
"(",
"\"hello\"",
")",
"==",
"\"virgo\""
] | [
342,
0
] | [
361,
44
] | python | en | ['en', 'en', 'en'] | True |
test_intent_request_calling_service_v2 | (fixture, calls) | Test a request for calling a service.
If this request is done async the test could finish before the action
has been executed. Hard to test because it will be a race condition.
| Test a request for calling a service. | async def test_intent_request_calling_service_v2(fixture, calls):
"""Test a request for calling a service.
If this request is done async the test could finish before the action
has been executed. Hard to test because it will be a race condition.
"""
mock_client, webhook_id = fixture
data = Data.v2
data["queryResult"]["action"] = "CallServiceIntent"
call_count = len(calls)
response = await mock_client.post(
f"/api/webhook/{webhook_id}", data=json.dumps(data)
)
assert response.status == 200
assert len(calls) == call_count + 1
call = calls[-1]
assert call.domain == "test"
assert call.service == "dialogflow"
assert call.data.get("entity_id") == ["switch.test"]
assert call.data.get("hello") == "virgo" | [
"async",
"def",
"test_intent_request_calling_service_v2",
"(",
"fixture",
",",
"calls",
")",
":",
"mock_client",
",",
"webhook_id",
"=",
"fixture",
"data",
"=",
"Data",
".",
"v2",
"data",
"[",
"\"queryResult\"",
"]",
"[",
"\"action\"",
"]",
"=",
"\"CallServiceIntent\"",
"call_count",
"=",
"len",
"(",
"calls",
")",
"response",
"=",
"await",
"mock_client",
".",
"post",
"(",
"f\"/api/webhook/{webhook_id}\"",
",",
"data",
"=",
"json",
".",
"dumps",
"(",
"data",
")",
")",
"assert",
"response",
".",
"status",
"==",
"200",
"assert",
"len",
"(",
"calls",
")",
"==",
"call_count",
"+",
"1",
"call",
"=",
"calls",
"[",
"-",
"1",
"]",
"assert",
"call",
".",
"domain",
"==",
"\"test\"",
"assert",
"call",
".",
"service",
"==",
"\"dialogflow\"",
"assert",
"call",
".",
"data",
".",
"get",
"(",
"\"entity_id\"",
")",
"==",
"[",
"\"switch.test\"",
"]",
"assert",
"call",
".",
"data",
".",
"get",
"(",
"\"hello\"",
")",
"==",
"\"virgo\""
] | [
364,
0
] | [
383,
44
] | python | en | ['en', 'en', 'en'] | True |
test_intent_with_no_action_v1 | (fixture) | Test an intent with no defined action. | Test an intent with no defined action. | async def test_intent_with_no_action_v1(fixture):
"""Test an intent with no defined action."""
mock_client, webhook_id = fixture
data = Data.v1
del data["result"]["action"]
assert "action" not in data["result"]
response = await mock_client.post(
f"/api/webhook/{webhook_id}", data=json.dumps(data)
)
assert response.status == 200
text = (await response.json()).get("speech")
assert text == "You have not defined an action in your Dialogflow intent." | [
"async",
"def",
"test_intent_with_no_action_v1",
"(",
"fixture",
")",
":",
"mock_client",
",",
"webhook_id",
"=",
"fixture",
"data",
"=",
"Data",
".",
"v1",
"del",
"data",
"[",
"\"result\"",
"]",
"[",
"\"action\"",
"]",
"assert",
"\"action\"",
"not",
"in",
"data",
"[",
"\"result\"",
"]",
"response",
"=",
"await",
"mock_client",
".",
"post",
"(",
"f\"/api/webhook/{webhook_id}\"",
",",
"data",
"=",
"json",
".",
"dumps",
"(",
"data",
")",
")",
"assert",
"response",
".",
"status",
"==",
"200",
"text",
"=",
"(",
"await",
"response",
".",
"json",
"(",
")",
")",
".",
"get",
"(",
"\"speech\"",
")",
"assert",
"text",
"==",
"\"You have not defined an action in your Dialogflow intent.\""
] | [
386,
0
] | [
397,
78
] | python | en | ['en', 'en', 'en'] | True |
test_intent_with_no_action_v2 | (fixture) | Test an intent with no defined action. | Test an intent with no defined action. | async def test_intent_with_no_action_v2(fixture):
"""Test an intent with no defined action."""
mock_client, webhook_id = fixture
data = Data.v2
del data["queryResult"]["action"]
assert "action" not in data["queryResult"]
response = await mock_client.post(
f"/api/webhook/{webhook_id}", data=json.dumps(data)
)
assert response.status == 200
text = (await response.json()).get("fulfillmentText")
assert text == "You have not defined an action in your Dialogflow intent." | [
"async",
"def",
"test_intent_with_no_action_v2",
"(",
"fixture",
")",
":",
"mock_client",
",",
"webhook_id",
"=",
"fixture",
"data",
"=",
"Data",
".",
"v2",
"del",
"data",
"[",
"\"queryResult\"",
"]",
"[",
"\"action\"",
"]",
"assert",
"\"action\"",
"not",
"in",
"data",
"[",
"\"queryResult\"",
"]",
"response",
"=",
"await",
"mock_client",
".",
"post",
"(",
"f\"/api/webhook/{webhook_id}\"",
",",
"data",
"=",
"json",
".",
"dumps",
"(",
"data",
")",
")",
"assert",
"response",
".",
"status",
"==",
"200",
"text",
"=",
"(",
"await",
"response",
".",
"json",
"(",
")",
")",
".",
"get",
"(",
"\"fulfillmentText\"",
")",
"assert",
"text",
"==",
"\"You have not defined an action in your Dialogflow intent.\""
] | [
400,
0
] | [
411,
78
] | python | en | ['en', 'en', 'en'] | True |
test_intent_with_unknown_action_v1 | (fixture) | Test an intent with an action not defined in the conf. | Test an intent with an action not defined in the conf. | async def test_intent_with_unknown_action_v1(fixture):
"""Test an intent with an action not defined in the conf."""
mock_client, webhook_id = fixture
data = Data.v1
data["result"]["action"] = "unknown"
response = await mock_client.post(
f"/api/webhook/{webhook_id}", data=json.dumps(data)
)
assert response.status == 200
text = (await response.json()).get("speech")
assert text == "This intent is not yet configured within Home Assistant." | [
"async",
"def",
"test_intent_with_unknown_action_v1",
"(",
"fixture",
")",
":",
"mock_client",
",",
"webhook_id",
"=",
"fixture",
"data",
"=",
"Data",
".",
"v1",
"data",
"[",
"\"result\"",
"]",
"[",
"\"action\"",
"]",
"=",
"\"unknown\"",
"response",
"=",
"await",
"mock_client",
".",
"post",
"(",
"f\"/api/webhook/{webhook_id}\"",
",",
"data",
"=",
"json",
".",
"dumps",
"(",
"data",
")",
")",
"assert",
"response",
".",
"status",
"==",
"200",
"text",
"=",
"(",
"await",
"response",
".",
"json",
"(",
")",
")",
".",
"get",
"(",
"\"speech\"",
")",
"assert",
"text",
"==",
"\"This intent is not yet configured within Home Assistant.\""
] | [
414,
0
] | [
424,
77
] | python | en | ['en', 'en', 'en'] | True |
test_intent_with_unknown_action_v2 | (fixture) | Test an intent with an action not defined in the conf. | Test an intent with an action not defined in the conf. | async def test_intent_with_unknown_action_v2(fixture):
"""Test an intent with an action not defined in the conf."""
mock_client, webhook_id = fixture
data = Data.v2
data["queryResult"]["action"] = "unknown"
response = await mock_client.post(
f"/api/webhook/{webhook_id}", data=json.dumps(data)
)
assert response.status == 200
text = (await response.json()).get("fulfillmentText")
assert text == "This intent is not yet configured within Home Assistant." | [
"async",
"def",
"test_intent_with_unknown_action_v2",
"(",
"fixture",
")",
":",
"mock_client",
",",
"webhook_id",
"=",
"fixture",
"data",
"=",
"Data",
".",
"v2",
"data",
"[",
"\"queryResult\"",
"]",
"[",
"\"action\"",
"]",
"=",
"\"unknown\"",
"response",
"=",
"await",
"mock_client",
".",
"post",
"(",
"f\"/api/webhook/{webhook_id}\"",
",",
"data",
"=",
"json",
".",
"dumps",
"(",
"data",
")",
")",
"assert",
"response",
".",
"status",
"==",
"200",
"text",
"=",
"(",
"await",
"response",
".",
"json",
"(",
")",
")",
".",
"get",
"(",
"\"fulfillmentText\"",
")",
"assert",
"text",
"==",
"\"This intent is not yet configured within Home Assistant.\""
] | [
427,
0
] | [
437,
77
] | python | en | ['en', 'en', 'en'] | True |
test_setup | (hass, legacy_patchable_time) | Test the general setup of the integration. | Test the general setup of the integration. | async def test_setup(hass, legacy_patchable_time):
"""Test the general setup of the integration."""
# Set up some mock feed entries for this test.
mock_entry_1 = _generate_mock_feed_entry(
"1234",
"Title 1",
1,
15.5,
(38.0, -3.0),
attribution="Attribution 1",
activity="Activity 1",
hazards="Hazards 1",
)
mock_entry_2 = _generate_mock_feed_entry("2345", "Title 2", 0, 20.5, (38.1, -3.1))
mock_entry_3 = _generate_mock_feed_entry("3456", "Title 3", 2, 25.5, (38.2, -3.2))
mock_entry_4 = _generate_mock_feed_entry("4567", "Title 4", 1, 12.5, (38.3, -3.3))
# Patching 'utcnow' to gain more control over the timed update.
utcnow = dt_util.utcnow()
with patch("homeassistant.util.dt.utcnow", return_value=utcnow), patch(
"aio_geojson_client.feed.GeoJsonFeed.update", new_callable=AsyncMock
) as mock_feed_update:
mock_feed_update.return_value = "OK", [mock_entry_1, mock_entry_2, mock_entry_3]
assert await async_setup_component(hass, geonetnz_volcano.DOMAIN, CONFIG)
# Artificially trigger update and collect events.
hass.bus.async_fire(EVENT_HOMEASSISTANT_START)
await hass.async_block_till_done()
all_states = hass.states.async_all()
# 3 sensor entities
assert len(all_states) == 3
state = hass.states.get("sensor.volcano_title_1")
assert state is not None
assert state.name == "Volcano Title 1"
assert int(state.state) == 1
assert state.attributes[ATTR_EXTERNAL_ID] == "1234"
assert state.attributes[ATTR_LATITUDE] == 38.0
assert state.attributes[ATTR_LONGITUDE] == -3.0
assert state.attributes[ATTR_DISTANCE] == 15.5
assert state.attributes[ATTR_FRIENDLY_NAME] == "Volcano Title 1"
assert state.attributes[ATTR_ATTRIBUTION] == "Attribution 1"
assert state.attributes[ATTR_ACTIVITY] == "Activity 1"
assert state.attributes[ATTR_HAZARDS] == "Hazards 1"
assert state.attributes[ATTR_UNIT_OF_MEASUREMENT] == "alert level"
assert state.attributes[ATTR_ICON] == "mdi:image-filter-hdr"
state = hass.states.get("sensor.volcano_title_2")
assert state is not None
assert state.name == "Volcano Title 2"
assert int(state.state) == 0
assert state.attributes[ATTR_EXTERNAL_ID] == "2345"
assert state.attributes[ATTR_LATITUDE] == 38.1
assert state.attributes[ATTR_LONGITUDE] == -3.1
assert state.attributes[ATTR_DISTANCE] == 20.5
assert state.attributes[ATTR_FRIENDLY_NAME] == "Volcano Title 2"
state = hass.states.get("sensor.volcano_title_3")
assert state is not None
assert state.name == "Volcano Title 3"
assert int(state.state) == 2
assert state.attributes[ATTR_EXTERNAL_ID] == "3456"
assert state.attributes[ATTR_LATITUDE] == 38.2
assert state.attributes[ATTR_LONGITUDE] == -3.2
assert state.attributes[ATTR_DISTANCE] == 25.5
assert state.attributes[ATTR_FRIENDLY_NAME] == "Volcano Title 3"
# Simulate an update - two existing, one new entry, one outdated entry
mock_feed_update.return_value = "OK", [mock_entry_1, mock_entry_4, mock_entry_3]
async_fire_time_changed(hass, utcnow + DEFAULT_SCAN_INTERVAL)
await hass.async_block_till_done()
all_states = hass.states.async_all()
assert len(all_states) == 4
# Simulate an update - empty data, but successful update,
# so no changes to entities.
mock_feed_update.return_value = "OK_NO_DATA", None
async_fire_time_changed(hass, utcnow + 2 * DEFAULT_SCAN_INTERVAL)
await hass.async_block_till_done()
all_states = hass.states.async_all()
assert len(all_states) == 4
# Simulate an update - empty data, keep all entities
mock_feed_update.return_value = "ERROR", None
async_fire_time_changed(hass, utcnow + 3 * DEFAULT_SCAN_INTERVAL)
await hass.async_block_till_done()
all_states = hass.states.async_all()
assert len(all_states) == 4
# Simulate an update - regular data for 3 entries
mock_feed_update.return_value = "OK", [mock_entry_1, mock_entry_2, mock_entry_3]
async_fire_time_changed(hass, utcnow + 4 * DEFAULT_SCAN_INTERVAL)
await hass.async_block_till_done()
all_states = hass.states.async_all()
assert len(all_states) == 4 | [
"async",
"def",
"test_setup",
"(",
"hass",
",",
"legacy_patchable_time",
")",
":",
"# Set up some mock feed entries for this test.",
"mock_entry_1",
"=",
"_generate_mock_feed_entry",
"(",
"\"1234\"",
",",
"\"Title 1\"",
",",
"1",
",",
"15.5",
",",
"(",
"38.0",
",",
"-",
"3.0",
")",
",",
"attribution",
"=",
"\"Attribution 1\"",
",",
"activity",
"=",
"\"Activity 1\"",
",",
"hazards",
"=",
"\"Hazards 1\"",
",",
")",
"mock_entry_2",
"=",
"_generate_mock_feed_entry",
"(",
"\"2345\"",
",",
"\"Title 2\"",
",",
"0",
",",
"20.5",
",",
"(",
"38.1",
",",
"-",
"3.1",
")",
")",
"mock_entry_3",
"=",
"_generate_mock_feed_entry",
"(",
"\"3456\"",
",",
"\"Title 3\"",
",",
"2",
",",
"25.5",
",",
"(",
"38.2",
",",
"-",
"3.2",
")",
")",
"mock_entry_4",
"=",
"_generate_mock_feed_entry",
"(",
"\"4567\"",
",",
"\"Title 4\"",
",",
"1",
",",
"12.5",
",",
"(",
"38.3",
",",
"-",
"3.3",
")",
")",
"# Patching 'utcnow' to gain more control over the timed update.",
"utcnow",
"=",
"dt_util",
".",
"utcnow",
"(",
")",
"with",
"patch",
"(",
"\"homeassistant.util.dt.utcnow\"",
",",
"return_value",
"=",
"utcnow",
")",
",",
"patch",
"(",
"\"aio_geojson_client.feed.GeoJsonFeed.update\"",
",",
"new_callable",
"=",
"AsyncMock",
")",
"as",
"mock_feed_update",
":",
"mock_feed_update",
".",
"return_value",
"=",
"\"OK\"",
",",
"[",
"mock_entry_1",
",",
"mock_entry_2",
",",
"mock_entry_3",
"]",
"assert",
"await",
"async_setup_component",
"(",
"hass",
",",
"geonetnz_volcano",
".",
"DOMAIN",
",",
"CONFIG",
")",
"# Artificially trigger update and collect events.",
"hass",
".",
"bus",
".",
"async_fire",
"(",
"EVENT_HOMEASSISTANT_START",
")",
"await",
"hass",
".",
"async_block_till_done",
"(",
")",
"all_states",
"=",
"hass",
".",
"states",
".",
"async_all",
"(",
")",
"# 3 sensor entities",
"assert",
"len",
"(",
"all_states",
")",
"==",
"3",
"state",
"=",
"hass",
".",
"states",
".",
"get",
"(",
"\"sensor.volcano_title_1\"",
")",
"assert",
"state",
"is",
"not",
"None",
"assert",
"state",
".",
"name",
"==",
"\"Volcano Title 1\"",
"assert",
"int",
"(",
"state",
".",
"state",
")",
"==",
"1",
"assert",
"state",
".",
"attributes",
"[",
"ATTR_EXTERNAL_ID",
"]",
"==",
"\"1234\"",
"assert",
"state",
".",
"attributes",
"[",
"ATTR_LATITUDE",
"]",
"==",
"38.0",
"assert",
"state",
".",
"attributes",
"[",
"ATTR_LONGITUDE",
"]",
"==",
"-",
"3.0",
"assert",
"state",
".",
"attributes",
"[",
"ATTR_DISTANCE",
"]",
"==",
"15.5",
"assert",
"state",
".",
"attributes",
"[",
"ATTR_FRIENDLY_NAME",
"]",
"==",
"\"Volcano Title 1\"",
"assert",
"state",
".",
"attributes",
"[",
"ATTR_ATTRIBUTION",
"]",
"==",
"\"Attribution 1\"",
"assert",
"state",
".",
"attributes",
"[",
"ATTR_ACTIVITY",
"]",
"==",
"\"Activity 1\"",
"assert",
"state",
".",
"attributes",
"[",
"ATTR_HAZARDS",
"]",
"==",
"\"Hazards 1\"",
"assert",
"state",
".",
"attributes",
"[",
"ATTR_UNIT_OF_MEASUREMENT",
"]",
"==",
"\"alert level\"",
"assert",
"state",
".",
"attributes",
"[",
"ATTR_ICON",
"]",
"==",
"\"mdi:image-filter-hdr\"",
"state",
"=",
"hass",
".",
"states",
".",
"get",
"(",
"\"sensor.volcano_title_2\"",
")",
"assert",
"state",
"is",
"not",
"None",
"assert",
"state",
".",
"name",
"==",
"\"Volcano Title 2\"",
"assert",
"int",
"(",
"state",
".",
"state",
")",
"==",
"0",
"assert",
"state",
".",
"attributes",
"[",
"ATTR_EXTERNAL_ID",
"]",
"==",
"\"2345\"",
"assert",
"state",
".",
"attributes",
"[",
"ATTR_LATITUDE",
"]",
"==",
"38.1",
"assert",
"state",
".",
"attributes",
"[",
"ATTR_LONGITUDE",
"]",
"==",
"-",
"3.1",
"assert",
"state",
".",
"attributes",
"[",
"ATTR_DISTANCE",
"]",
"==",
"20.5",
"assert",
"state",
".",
"attributes",
"[",
"ATTR_FRIENDLY_NAME",
"]",
"==",
"\"Volcano Title 2\"",
"state",
"=",
"hass",
".",
"states",
".",
"get",
"(",
"\"sensor.volcano_title_3\"",
")",
"assert",
"state",
"is",
"not",
"None",
"assert",
"state",
".",
"name",
"==",
"\"Volcano Title 3\"",
"assert",
"int",
"(",
"state",
".",
"state",
")",
"==",
"2",
"assert",
"state",
".",
"attributes",
"[",
"ATTR_EXTERNAL_ID",
"]",
"==",
"\"3456\"",
"assert",
"state",
".",
"attributes",
"[",
"ATTR_LATITUDE",
"]",
"==",
"38.2",
"assert",
"state",
".",
"attributes",
"[",
"ATTR_LONGITUDE",
"]",
"==",
"-",
"3.2",
"assert",
"state",
".",
"attributes",
"[",
"ATTR_DISTANCE",
"]",
"==",
"25.5",
"assert",
"state",
".",
"attributes",
"[",
"ATTR_FRIENDLY_NAME",
"]",
"==",
"\"Volcano Title 3\"",
"# Simulate an update - two existing, one new entry, one outdated entry",
"mock_feed_update",
".",
"return_value",
"=",
"\"OK\"",
",",
"[",
"mock_entry_1",
",",
"mock_entry_4",
",",
"mock_entry_3",
"]",
"async_fire_time_changed",
"(",
"hass",
",",
"utcnow",
"+",
"DEFAULT_SCAN_INTERVAL",
")",
"await",
"hass",
".",
"async_block_till_done",
"(",
")",
"all_states",
"=",
"hass",
".",
"states",
".",
"async_all",
"(",
")",
"assert",
"len",
"(",
"all_states",
")",
"==",
"4",
"# Simulate an update - empty data, but successful update,",
"# so no changes to entities.",
"mock_feed_update",
".",
"return_value",
"=",
"\"OK_NO_DATA\"",
",",
"None",
"async_fire_time_changed",
"(",
"hass",
",",
"utcnow",
"+",
"2",
"*",
"DEFAULT_SCAN_INTERVAL",
")",
"await",
"hass",
".",
"async_block_till_done",
"(",
")",
"all_states",
"=",
"hass",
".",
"states",
".",
"async_all",
"(",
")",
"assert",
"len",
"(",
"all_states",
")",
"==",
"4",
"# Simulate an update - empty data, keep all entities",
"mock_feed_update",
".",
"return_value",
"=",
"\"ERROR\"",
",",
"None",
"async_fire_time_changed",
"(",
"hass",
",",
"utcnow",
"+",
"3",
"*",
"DEFAULT_SCAN_INTERVAL",
")",
"await",
"hass",
".",
"async_block_till_done",
"(",
")",
"all_states",
"=",
"hass",
".",
"states",
".",
"async_all",
"(",
")",
"assert",
"len",
"(",
"all_states",
")",
"==",
"4",
"# Simulate an update - regular data for 3 entries",
"mock_feed_update",
".",
"return_value",
"=",
"\"OK\"",
",",
"[",
"mock_entry_1",
",",
"mock_entry_2",
",",
"mock_entry_3",
"]",
"async_fire_time_changed",
"(",
"hass",
",",
"utcnow",
"+",
"4",
"*",
"DEFAULT_SCAN_INTERVAL",
")",
"await",
"hass",
".",
"async_block_till_done",
"(",
")",
"all_states",
"=",
"hass",
".",
"states",
".",
"async_all",
"(",
")",
"assert",
"len",
"(",
"all_states",
")",
"==",
"4"
] | [
30,
0
] | [
128,
35
] | python | en | ['en', 'en', 'en'] | True |
test_setup_imperial | (hass) | Test the setup of the integration using imperial unit system. | Test the setup of the integration using imperial unit system. | async def test_setup_imperial(hass):
"""Test the setup of the integration using imperial unit system."""
hass.config.units = IMPERIAL_SYSTEM
# Set up some mock feed entries for this test.
mock_entry_1 = _generate_mock_feed_entry("1234", "Title 1", 1, 15.5, (38.0, -3.0))
# Patching 'utcnow' to gain more control over the timed update.
utcnow = dt_util.utcnow()
with patch("homeassistant.util.dt.utcnow", return_value=utcnow), patch(
"aio_geojson_client.feed.GeoJsonFeed.update", new_callable=AsyncMock
) as mock_feed_update, patch(
"aio_geojson_client.feed.GeoJsonFeed.__init__"
) as mock_feed_init:
mock_feed_update.return_value = "OK", [mock_entry_1]
assert await async_setup_component(hass, geonetnz_volcano.DOMAIN, CONFIG)
# Artificially trigger update and collect events.
hass.bus.async_fire(EVENT_HOMEASSISTANT_START)
await hass.async_block_till_done()
all_states = hass.states.async_all()
assert len(all_states) == 1
# Test conversion of 200 miles to kilometers.
assert mock_feed_init.call_args[1].get("filter_radius") == 321.8688
state = hass.states.get("sensor.volcano_title_1")
assert state is not None
assert state.name == "Volcano Title 1"
assert int(state.state) == 1
assert state.attributes[ATTR_EXTERNAL_ID] == "1234"
assert state.attributes[ATTR_LATITUDE] == 38.0
assert state.attributes[ATTR_LONGITUDE] == -3.0
assert state.attributes[ATTR_DISTANCE] == 9.6
assert state.attributes[ATTR_FRIENDLY_NAME] == "Volcano Title 1"
assert state.attributes[ATTR_UNIT_OF_MEASUREMENT] == "alert level"
assert state.attributes[ATTR_ICON] == "mdi:image-filter-hdr" | [
"async",
"def",
"test_setup_imperial",
"(",
"hass",
")",
":",
"hass",
".",
"config",
".",
"units",
"=",
"IMPERIAL_SYSTEM",
"# Set up some mock feed entries for this test.",
"mock_entry_1",
"=",
"_generate_mock_feed_entry",
"(",
"\"1234\"",
",",
"\"Title 1\"",
",",
"1",
",",
"15.5",
",",
"(",
"38.0",
",",
"-",
"3.0",
")",
")",
"# Patching 'utcnow' to gain more control over the timed update.",
"utcnow",
"=",
"dt_util",
".",
"utcnow",
"(",
")",
"with",
"patch",
"(",
"\"homeassistant.util.dt.utcnow\"",
",",
"return_value",
"=",
"utcnow",
")",
",",
"patch",
"(",
"\"aio_geojson_client.feed.GeoJsonFeed.update\"",
",",
"new_callable",
"=",
"AsyncMock",
")",
"as",
"mock_feed_update",
",",
"patch",
"(",
"\"aio_geojson_client.feed.GeoJsonFeed.__init__\"",
")",
"as",
"mock_feed_init",
":",
"mock_feed_update",
".",
"return_value",
"=",
"\"OK\"",
",",
"[",
"mock_entry_1",
"]",
"assert",
"await",
"async_setup_component",
"(",
"hass",
",",
"geonetnz_volcano",
".",
"DOMAIN",
",",
"CONFIG",
")",
"# Artificially trigger update and collect events.",
"hass",
".",
"bus",
".",
"async_fire",
"(",
"EVENT_HOMEASSISTANT_START",
")",
"await",
"hass",
".",
"async_block_till_done",
"(",
")",
"all_states",
"=",
"hass",
".",
"states",
".",
"async_all",
"(",
")",
"assert",
"len",
"(",
"all_states",
")",
"==",
"1",
"# Test conversion of 200 miles to kilometers.",
"assert",
"mock_feed_init",
".",
"call_args",
"[",
"1",
"]",
".",
"get",
"(",
"\"filter_radius\"",
")",
"==",
"321.8688",
"state",
"=",
"hass",
".",
"states",
".",
"get",
"(",
"\"sensor.volcano_title_1\"",
")",
"assert",
"state",
"is",
"not",
"None",
"assert",
"state",
".",
"name",
"==",
"\"Volcano Title 1\"",
"assert",
"int",
"(",
"state",
".",
"state",
")",
"==",
"1",
"assert",
"state",
".",
"attributes",
"[",
"ATTR_EXTERNAL_ID",
"]",
"==",
"\"1234\"",
"assert",
"state",
".",
"attributes",
"[",
"ATTR_LATITUDE",
"]",
"==",
"38.0",
"assert",
"state",
".",
"attributes",
"[",
"ATTR_LONGITUDE",
"]",
"==",
"-",
"3.0",
"assert",
"state",
".",
"attributes",
"[",
"ATTR_DISTANCE",
"]",
"==",
"9.6",
"assert",
"state",
".",
"attributes",
"[",
"ATTR_FRIENDLY_NAME",
"]",
"==",
"\"Volcano Title 1\"",
"assert",
"state",
".",
"attributes",
"[",
"ATTR_UNIT_OF_MEASUREMENT",
"]",
"==",
"\"alert level\"",
"assert",
"state",
".",
"attributes",
"[",
"ATTR_ICON",
"]",
"==",
"\"mdi:image-filter-hdr\""
] | [
131,
0
] | [
166,
68
] | python | en | ['en', 'en', 'en'] | True |
static_datetime | () | Build a datetime object for testing in the correct timezone. | Build a datetime object for testing in the correct timezone. | def static_datetime():
"""Build a datetime object for testing in the correct timezone."""
return dt.as_utc(datetime(2020, 6, 12, 8, 0, 0)) | [
"def",
"static_datetime",
"(",
")",
":",
"return",
"dt",
".",
"as_utc",
"(",
"datetime",
"(",
"2020",
",",
"6",
",",
"12",
",",
"8",
",",
"0",
",",
"0",
")",
")"
] | [
6,
0
] | [
8,
52
] | python | en | ['en', 'en', 'en'] | True |
future_timestamp | (days) | Create timestamp object for requested days in future. | Create timestamp object for requested days in future. | def future_timestamp(days):
"""Create timestamp object for requested days in future."""
delta = timedelta(days=days, minutes=1)
return static_datetime() + delta | [
"def",
"future_timestamp",
"(",
"days",
")",
":",
"delta",
"=",
"timedelta",
"(",
"days",
"=",
"days",
",",
"minutes",
"=",
"1",
")",
"return",
"static_datetime",
"(",
")",
"+",
"delta"
] | [
11,
0
] | [
14,
36
] | python | en | ['en', 'en', 'en'] | True |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.