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_create_doorbell | (hass) | Test creation of a doorbell. | Test creation of a doorbell. | async def test_create_doorbell(hass):
"""Test creation of a doorbell."""
doorbell_one = await _mock_doorbell_from_fixture(hass, "get_doorbell.json")
await _create_august_with_devices(hass, [doorbell_one])
binary_sensor_k98gidt45gul_name_motion = hass.states.get(
"binary_sensor.k98gidt45gul_name_motion"
)
assert binary_sensor_k98gidt45gul_name_motion.state == STATE_OFF
binary_sensor_k98gidt45gul_name_online = hass.states.get(
"binary_sensor.k98gidt45gul_name_online"
)
assert binary_sensor_k98gidt45gul_name_online.state == STATE_ON
binary_sensor_k98gidt45gul_name_ding = hass.states.get(
"binary_sensor.k98gidt45gul_name_ding"
)
assert binary_sensor_k98gidt45gul_name_ding.state == STATE_OFF
binary_sensor_k98gidt45gul_name_motion = hass.states.get(
"binary_sensor.k98gidt45gul_name_motion"
)
assert binary_sensor_k98gidt45gul_name_motion.state == STATE_OFF | [
"async",
"def",
"test_create_doorbell",
"(",
"hass",
")",
":",
"doorbell_one",
"=",
"await",
"_mock_doorbell_from_fixture",
"(",
"hass",
",",
"\"get_doorbell.json\"",
")",
"await",
"_create_august_with_devices",
"(",
"hass",
",",
"[",
"doorbell_one",
"]",
")",
"binary_sensor_k98gidt45gul_name_motion",
"=",
"hass",
".",
"states",
".",
"get",
"(",
"\"binary_sensor.k98gidt45gul_name_motion\"",
")",
"assert",
"binary_sensor_k98gidt45gul_name_motion",
".",
"state",
"==",
"STATE_OFF",
"binary_sensor_k98gidt45gul_name_online",
"=",
"hass",
".",
"states",
".",
"get",
"(",
"\"binary_sensor.k98gidt45gul_name_online\"",
")",
"assert",
"binary_sensor_k98gidt45gul_name_online",
".",
"state",
"==",
"STATE_ON",
"binary_sensor_k98gidt45gul_name_ding",
"=",
"hass",
".",
"states",
".",
"get",
"(",
"\"binary_sensor.k98gidt45gul_name_ding\"",
")",
"assert",
"binary_sensor_k98gidt45gul_name_ding",
".",
"state",
"==",
"STATE_OFF",
"binary_sensor_k98gidt45gul_name_motion",
"=",
"hass",
".",
"states",
".",
"get",
"(",
"\"binary_sensor.k98gidt45gul_name_motion\"",
")",
"assert",
"binary_sensor_k98gidt45gul_name_motion",
".",
"state",
"==",
"STATE_OFF"
] | [
54,
0
] | [
74,
68
] | python | en | ['en', 'lb', 'en'] | True |
test_create_doorbell_offline | (hass) | Test creation of a doorbell that is offline. | Test creation of a doorbell that is offline. | async def test_create_doorbell_offline(hass):
"""Test creation of a doorbell that is offline."""
doorbell_one = await _mock_doorbell_from_fixture(hass, "get_doorbell.offline.json")
await _create_august_with_devices(hass, [doorbell_one])
binary_sensor_tmt100_name_motion = hass.states.get(
"binary_sensor.tmt100_name_motion"
)
assert binary_sensor_tmt100_name_motion.state == STATE_UNAVAILABLE
binary_sensor_tmt100_name_online = hass.states.get(
"binary_sensor.tmt100_name_online"
)
assert binary_sensor_tmt100_name_online.state == STATE_OFF
binary_sensor_tmt100_name_ding = hass.states.get("binary_sensor.tmt100_name_ding")
assert binary_sensor_tmt100_name_ding.state == STATE_UNAVAILABLE | [
"async",
"def",
"test_create_doorbell_offline",
"(",
"hass",
")",
":",
"doorbell_one",
"=",
"await",
"_mock_doorbell_from_fixture",
"(",
"hass",
",",
"\"get_doorbell.offline.json\"",
")",
"await",
"_create_august_with_devices",
"(",
"hass",
",",
"[",
"doorbell_one",
"]",
")",
"binary_sensor_tmt100_name_motion",
"=",
"hass",
".",
"states",
".",
"get",
"(",
"\"binary_sensor.tmt100_name_motion\"",
")",
"assert",
"binary_sensor_tmt100_name_motion",
".",
"state",
"==",
"STATE_UNAVAILABLE",
"binary_sensor_tmt100_name_online",
"=",
"hass",
".",
"states",
".",
"get",
"(",
"\"binary_sensor.tmt100_name_online\"",
")",
"assert",
"binary_sensor_tmt100_name_online",
".",
"state",
"==",
"STATE_OFF",
"binary_sensor_tmt100_name_ding",
"=",
"hass",
".",
"states",
".",
"get",
"(",
"\"binary_sensor.tmt100_name_ding\"",
")",
"assert",
"binary_sensor_tmt100_name_ding",
".",
"state",
"==",
"STATE_UNAVAILABLE"
] | [
77,
0
] | [
91,
68
] | python | en | ['en', 'nl', 'en'] | True |
test_create_doorbell_with_motion | (hass) | Test creation of a doorbell. | Test creation of a doorbell. | async def test_create_doorbell_with_motion(hass):
"""Test creation of a doorbell."""
doorbell_one = await _mock_doorbell_from_fixture(hass, "get_doorbell.json")
activities = await _mock_activities_from_fixture(
hass, "get_activity.doorbell_motion.json"
)
await _create_august_with_devices(hass, [doorbell_one], activities=activities)
binary_sensor_k98gidt45gul_name_motion = hass.states.get(
"binary_sensor.k98gidt45gul_name_motion"
)
assert binary_sensor_k98gidt45gul_name_motion.state == STATE_ON
binary_sensor_k98gidt45gul_name_online = hass.states.get(
"binary_sensor.k98gidt45gul_name_online"
)
assert binary_sensor_k98gidt45gul_name_online.state == STATE_ON
binary_sensor_k98gidt45gul_name_ding = hass.states.get(
"binary_sensor.k98gidt45gul_name_ding"
)
assert binary_sensor_k98gidt45gul_name_ding.state == STATE_OFF | [
"async",
"def",
"test_create_doorbell_with_motion",
"(",
"hass",
")",
":",
"doorbell_one",
"=",
"await",
"_mock_doorbell_from_fixture",
"(",
"hass",
",",
"\"get_doorbell.json\"",
")",
"activities",
"=",
"await",
"_mock_activities_from_fixture",
"(",
"hass",
",",
"\"get_activity.doorbell_motion.json\"",
")",
"await",
"_create_august_with_devices",
"(",
"hass",
",",
"[",
"doorbell_one",
"]",
",",
"activities",
"=",
"activities",
")",
"binary_sensor_k98gidt45gul_name_motion",
"=",
"hass",
".",
"states",
".",
"get",
"(",
"\"binary_sensor.k98gidt45gul_name_motion\"",
")",
"assert",
"binary_sensor_k98gidt45gul_name_motion",
".",
"state",
"==",
"STATE_ON",
"binary_sensor_k98gidt45gul_name_online",
"=",
"hass",
".",
"states",
".",
"get",
"(",
"\"binary_sensor.k98gidt45gul_name_online\"",
")",
"assert",
"binary_sensor_k98gidt45gul_name_online",
".",
"state",
"==",
"STATE_ON",
"binary_sensor_k98gidt45gul_name_ding",
"=",
"hass",
".",
"states",
".",
"get",
"(",
"\"binary_sensor.k98gidt45gul_name_ding\"",
")",
"assert",
"binary_sensor_k98gidt45gul_name_ding",
".",
"state",
"==",
"STATE_OFF"
] | [
94,
0
] | [
113,
66
] | python | en | ['en', 'lb', 'en'] | True |
test_doorbell_device_registry | (hass) | Test creation of a lock with doorsense and bridge ands up in the registry. | Test creation of a lock with doorsense and bridge ands up in the registry. | async def test_doorbell_device_registry(hass):
"""Test creation of a lock with doorsense and bridge ands up in the registry."""
doorbell_one = await _mock_doorbell_from_fixture(hass, "get_doorbell.offline.json")
await _create_august_with_devices(hass, [doorbell_one])
device_registry = await hass.helpers.device_registry.async_get_registry()
reg_device = device_registry.async_get_device(
identifiers={("august", "tmt100")}, connections=set()
)
assert reg_device.model == "hydra1"
assert reg_device.name == "tmt100 Name"
assert reg_device.manufacturer == "August Home Inc."
assert reg_device.sw_version == "3.1.0-HYDRC75+201909251139" | [
"async",
"def",
"test_doorbell_device_registry",
"(",
"hass",
")",
":",
"doorbell_one",
"=",
"await",
"_mock_doorbell_from_fixture",
"(",
"hass",
",",
"\"get_doorbell.offline.json\"",
")",
"await",
"_create_august_with_devices",
"(",
"hass",
",",
"[",
"doorbell_one",
"]",
")",
"device_registry",
"=",
"await",
"hass",
".",
"helpers",
".",
"device_registry",
".",
"async_get_registry",
"(",
")",
"reg_device",
"=",
"device_registry",
".",
"async_get_device",
"(",
"identifiers",
"=",
"{",
"(",
"\"august\"",
",",
"\"tmt100\"",
")",
"}",
",",
"connections",
"=",
"set",
"(",
")",
")",
"assert",
"reg_device",
".",
"model",
"==",
"\"hydra1\"",
"assert",
"reg_device",
".",
"name",
"==",
"\"tmt100 Name\"",
"assert",
"reg_device",
".",
"manufacturer",
"==",
"\"August Home Inc.\"",
"assert",
"reg_device",
".",
"sw_version",
"==",
"\"3.1.0-HYDRC75+201909251139\""
] | [
116,
0
] | [
129,
64
] | python | en | ['en', 'en', 'en'] | True |
validate_input | (hass: core.HomeAssistant, data) | Validate the user input allows us to connect.
Data has the keys from DATA_SCHEMA with values provided by the user.
| Validate the user input allows us to connect. | async def validate_input(hass: core.HomeAssistant, data):
"""Validate the user input allows us to connect.
Data has the keys from DATA_SCHEMA with values provided by the user.
"""
client_session = aiohttp_client.async_get_clientsession(hass)
account = Account(data["username"], data["password"])
client = Client(client_session, account)
try:
await client.authenticate()
except (asyncio.TimeoutError, ClientError, SmartMeterTexasAPIError) as error:
raise CannotConnect from error
except SmartMeterTexasAuthError as error:
raise InvalidAuth(error) from error
# Return info that you want to store in the config entry.
return {"title": account.username} | [
"async",
"def",
"validate_input",
"(",
"hass",
":",
"core",
".",
"HomeAssistant",
",",
"data",
")",
":",
"client_session",
"=",
"aiohttp_client",
".",
"async_get_clientsession",
"(",
"hass",
")",
"account",
"=",
"Account",
"(",
"data",
"[",
"\"username\"",
"]",
",",
"data",
"[",
"\"password\"",
"]",
")",
"client",
"=",
"Client",
"(",
"client_session",
",",
"account",
")",
"try",
":",
"await",
"client",
".",
"authenticate",
"(",
")",
"except",
"(",
"asyncio",
".",
"TimeoutError",
",",
"ClientError",
",",
"SmartMeterTexasAPIError",
")",
"as",
"error",
":",
"raise",
"CannotConnect",
"from",
"error",
"except",
"SmartMeterTexasAuthError",
"as",
"error",
":",
"raise",
"InvalidAuth",
"(",
"error",
")",
"from",
"error",
"# Return info that you want to store in the config entry.",
"return",
"{",
"\"title\"",
":",
"account",
".",
"username",
"}"
] | [
25,
0
] | [
43,
38
] | python | en | ['en', 'en', 'en'] | True |
ConfigFlow.async_step_user | (self, user_input=None) | Handle the initial step. | Handle the initial step. | async def async_step_user(self, user_input=None):
"""Handle the initial step."""
errors = {}
if user_input is not None:
try:
info = await validate_input(self.hass, user_input)
except CannotConnect:
errors["base"] = "cannot_connect"
except InvalidAuth:
errors["base"] = "invalid_auth"
except Exception: # pylint: disable=broad-except
_LOGGER.exception("Unexpected exception")
errors["base"] = "unknown"
else:
if not errors:
# Ensure the same account cannot be setup more than once.
await self.async_set_unique_id(user_input[CONF_USERNAME])
self._abort_if_unique_id_configured()
return self.async_create_entry(title=info["title"], data=user_input)
return self.async_show_form(
step_id="user", data_schema=DATA_SCHEMA, errors=errors
) | [
"async",
"def",
"async_step_user",
"(",
"self",
",",
"user_input",
"=",
"None",
")",
":",
"errors",
"=",
"{",
"}",
"if",
"user_input",
"is",
"not",
"None",
":",
"try",
":",
"info",
"=",
"await",
"validate_input",
"(",
"self",
".",
"hass",
",",
"user_input",
")",
"except",
"CannotConnect",
":",
"errors",
"[",
"\"base\"",
"]",
"=",
"\"cannot_connect\"",
"except",
"InvalidAuth",
":",
"errors",
"[",
"\"base\"",
"]",
"=",
"\"invalid_auth\"",
"except",
"Exception",
":",
"# pylint: disable=broad-except",
"_LOGGER",
".",
"exception",
"(",
"\"Unexpected exception\"",
")",
"errors",
"[",
"\"base\"",
"]",
"=",
"\"unknown\"",
"else",
":",
"if",
"not",
"errors",
":",
"# Ensure the same account cannot be setup more than once.",
"await",
"self",
".",
"async_set_unique_id",
"(",
"user_input",
"[",
"CONF_USERNAME",
"]",
")",
"self",
".",
"_abort_if_unique_id_configured",
"(",
")",
"return",
"self",
".",
"async_create_entry",
"(",
"title",
"=",
"info",
"[",
"\"title\"",
"]",
",",
"data",
"=",
"user_input",
")",
"return",
"self",
".",
"async_show_form",
"(",
"step_id",
"=",
"\"user\"",
",",
"data_schema",
"=",
"DATA_SCHEMA",
",",
"errors",
"=",
"errors",
")"
] | [
52,
4
] | [
76,
9
] | python | en | ['en', 'en', 'en'] | True |
hello | () | prints hello, world | prints hello, world | def hello():
""" prints hello, world """
print("Hello, world!") | [
"def",
"hello",
"(",
")",
":",
"print",
"(",
"\"Hello, world!\"",
")"
] | [
41,
0
] | [
43,
26
] | python | en | ['en', 'sr', 'en'] | True |
areacircle | (radius) | Computes the area of a circle of the given radius | Computes the area of a circle of the given radius | def areacircle(radius):
""" Computes the area of a circle of the given radius """
area = 3.14*radius**2
print("The area of a circle of radius",radius,"is", area) | [
"def",
"areacircle",
"(",
"radius",
")",
":",
"area",
"=",
"3.14",
"*",
"radius",
"**",
"2",
"print",
"(",
"\"The area of a circle of radius\"",
",",
"radius",
",",
"\"is\"",
",",
"area",
")"
] | [
46,
0
] | [
49,
61
] | python | en | ['en', 'en', 'en'] | True |
fahrenheit_to_celsius | (temp) | Converts Fahrenheit temperature to Celsius.
Formula is 5/9 of temp minus 32 | Converts Fahrenheit temperature to Celsius.
Formula is 5/9 of temp minus 32 | def fahrenheit_to_celsius(temp):
""" Converts Fahrenheit temperature to Celsius.
Formula is 5/9 of temp minus 32 """
# Note that this line is not executed
# end='' keeps print from starting a new line.
newTemp = 5*(temp-32)/9
print("The Fahrenheit temperature",temp,"is equivalent to",newTemp,end='')
print(" degrees Celsius") | [
"def",
"fahrenheit_to_celsius",
"(",
"temp",
")",
":",
"# Note that this line is not executed",
"# end='' keeps print from starting a new line.",
"newTemp",
"=",
"5",
"*",
"(",
"temp",
"-",
"32",
")",
"/",
"9",
"print",
"(",
"\"The Fahrenheit temperature\"",
",",
"temp",
",",
"\"is equivalent to\"",
",",
"newTemp",
",",
"end",
"=",
"''",
")",
"print",
"(",
"\" degrees Celsius\"",
")"
] | [
99,
0
] | [
106,
29
] | python | de | ['de', 'la', 'it'] | False |
celsius_to_fahrenheit | (temp) |
End solution
|
End solution
| def celsius_to_fahrenheit(temp):
#%%
"""
End solution
""" | [
"def",
"celsius_to_fahrenheit",
"(",
"temp",
")",
":",
"#%%"
] | [
127,
0
] | [
136,
3
] | python | en | ['en', 'error', 'th'] | False |
name | () | Input first and last name, combine to one string and print | Input first and last name, combine to one string and print | def name():
""" Input first and last name, combine to one string and print """
fname = input("Enter your first name: ")
lname = input("Enter your last name: ")
fullname = fname + " " + lname
print("Your name is:", fullname) | [
"def",
"name",
"(",
")",
":",
"fname",
"=",
"input",
"(",
"\"Enter your first name: \"",
")",
"lname",
"=",
"input",
"(",
"\"Enter your last name: \"",
")",
"fullname",
"=",
"fname",
"+",
"\" \"",
"+",
"lname",
"print",
"(",
"\"Your name is:\"",
",",
"fullname",
")"
] | [
139,
0
] | [
145,
36
] | python | en | ['en', 'en', 'en'] | True |
name | () | Input first and last name, combine to one string and print
Also, input the city and state and print. | Input first and last name, combine to one string and print
Also, input the city and state and print. | def name():
""" Input first and last name, combine to one string and print
Also, input the city and state and print."""
fname = input("Enter your first name: ")
lname = input("Enter your last name: ")
fullname = fname + " " + lname
print("Your name is:", fullname) | [
"def",
"name",
"(",
")",
":",
"fname",
"=",
"input",
"(",
"\"Enter your first name: \"",
")",
"lname",
"=",
"input",
"(",
"\"Enter your last name: \"",
")",
"fullname",
"=",
"fname",
"+",
"\" \"",
"+",
"lname",
"print",
"(",
"\"Your name is:\"",
",",
"fullname",
")"
] | [
171,
0
] | [
182,
36
] | python | en | ['en', 'en', 'en'] | True |
if_statement | () | Three slightly difference versions of if: if, if-else, if-elif-else | Three slightly difference versions of if: if, if-else, if-elif-else | def if_statement():
""" Three slightly difference versions of if: if, if-else, if-elif-else"""
x = 5
y = 0
z = 0
if x > 0:
print("x is positive")
if y > 0:
print("y is positive")
else:
print("y is not positive")
# elif can be repeated as often as necessary
if z > 0:
print("z is positive")
elif z < 0:
print("z is negative")
else:
print("z must be 0") | [
"def",
"if_statement",
"(",
")",
":",
"x",
"=",
"5",
"y",
"=",
"0",
"z",
"=",
"0",
"if",
"x",
">",
"0",
":",
"print",
"(",
"\"x is positive\"",
")",
"if",
"y",
">",
"0",
":",
"print",
"(",
"\"y is positive\"",
")",
"else",
":",
"print",
"(",
"\"y is not positive\"",
")",
"# elif can be repeated as often as necessary ",
"if",
"z",
">",
"0",
":",
"print",
"(",
"\"z is positive\"",
")",
"elif",
"z",
"<",
"0",
":",
"print",
"(",
"\"z is negative\"",
")",
"else",
":",
"print",
"(",
"\"z must be 0\"",
")"
] | [
190,
0
] | [
209,
28
] | python | en | ['en', 'en', 'en'] | True |
area | (type_, x) | Computes the area of a square or circle.
type_ must be the string "circle or the string "square"
We use type_ here, because type is a Python keyword. | Computes the area of a square or circle.
type_ must be the string "circle or the string "square"
We use type_ here, because type is a Python keyword. | def area(type_, x):
""" Computes the area of a square or circle.
type_ must be the string "circle or the string "square"
We use type_ here, because type is a Python keyword. """
if type_ == "circle":
area = 3.14*x**2
print(area)
elif type_ == "square":
area = x**2
print(area)
else:
print("I don't know that one.") | [
"def",
"area",
"(",
"type_",
",",
"x",
")",
":",
"if",
"type_",
"==",
"\"circle\"",
":",
"area",
"=",
"3.14",
"*",
"x",
"**",
"2",
"print",
"(",
"area",
")",
"elif",
"type_",
"==",
"\"square\"",
":",
"area",
"=",
"x",
"**",
"2",
"print",
"(",
"area",
")",
"else",
":",
"print",
"(",
"\"I don't know that one.\"",
")"
] | [
233,
0
] | [
244,
39
] | python | en | ['en', 'en', 'en'] | True |
absolutevalue | (num) |
End solution
|
End solution
| def absolutevalue(num):
#%%
"""
End solution
""" | [
"def",
"absolutevalue",
"(",
"num",
")",
":",
"#%%"
] | [
265,
0
] | [
274,
3
] | python | en | ['en', 'error', 'th'] | False |
fahrenheit_to_celsius1 | () | BAD. Does not check input before using it.
Input from keyboard, which is always a string and must often be
converted to an int or float.
Converts Fahrenheit temp to Celsius.
| BAD. Does not check input before using it.
Input from keyboard, which is always a string and must often be
converted to an int or float.
Converts Fahrenheit temp to Celsius.
| def fahrenheit_to_celsius1():
""" BAD. Does not check input before using it.
Input from keyboard, which is always a string and must often be
converted to an int or float.
Converts Fahrenheit temp to Celsius.
"""
temp_str = input("Enter a Fahrentheit temperature: ")
temp = int(temp_str)
newTemp = 5*(temp-32)/9
print("The Fahrenheit temperature",temp,"is equivalent to ",end='')
print(newTemp,"degrees Celsius") | [
"def",
"fahrenheit_to_celsius1",
"(",
")",
":",
"temp_str",
"=",
"input",
"(",
"\"Enter a Fahrentheit temperature: \"",
")",
"temp",
"=",
"int",
"(",
"temp_str",
")",
"newTemp",
"=",
"5",
"*",
"(",
"temp",
"-",
"32",
")",
"/",
"9",
"print",
"(",
"\"The Fahrenheit temperature\"",
",",
"temp",
",",
"\"is equivalent to \"",
",",
"end",
"=",
"''",
")",
"print",
"(",
"newTemp",
",",
"\"degrees Celsius\"",
")"
] | [
282,
0
] | [
293,
36
] | python | en | ['en', 'en', 'en'] | True |
fahrenheit_to_celsius2 | () | IMPROVED. Does some checking of input before using it.
Input from keyboard, which is always a string and must often be
converted to an int or float.
Converts Fahrenheit temp to Celsius.
Uses 'if' to make sure an entry was made.
| IMPROVED. Does some checking of input before using it.
Input from keyboard, which is always a string and must often be
converted to an int or float.
Converts Fahrenheit temp to Celsius.
Uses 'if' to make sure an entry was made.
| def fahrenheit_to_celsius2():
""" IMPROVED. Does some checking of input before using it.
Input from keyboard, which is always a string and must often be
converted to an int or float.
Converts Fahrenheit temp to Celsius.
Uses 'if' to make sure an entry was made.
"""
temp_str = input("Enter a Fahrenheit temperature: ")
if temp_str:
temp = int(temp_str)
newTemp = 5*(temp-32)/9
print("The Fahrenheit temperature",temp,"is equivalent to ",end='')
print(newTemp,"degrees Celsius") | [
"def",
"fahrenheit_to_celsius2",
"(",
")",
":",
"temp_str",
"=",
"input",
"(",
"\"Enter a Fahrenheit temperature: \"",
")",
"if",
"temp_str",
":",
"temp",
"=",
"int",
"(",
"temp_str",
")",
"newTemp",
"=",
"5",
"*",
"(",
"temp",
"-",
"32",
")",
"/",
"9",
"print",
"(",
"\"The Fahrenheit temperature\"",
",",
"temp",
",",
"\"is equivalent to \"",
",",
"end",
"=",
"''",
")",
"print",
"(",
"newTemp",
",",
"\"degrees Celsius\"",
")"
] | [
301,
0
] | [
314,
40
] | python | en | ['en', 'en', 'en'] | True |
fahrenheit_to_celsius3 | () | MORE IMPROVED. Does even more checking of input before using it.
Input from keyboard, which is always a string and must often be
converted to an int or float.
Converts Fahrenheit temp to Celsius.
Uses if to check whether input is a number and then uses .isdigit() method
of strings to check whether input is made of of digits.
| MORE IMPROVED. Does even more checking of input before using it.
Input from keyboard, which is always a string and must often be
converted to an int or float.
Converts Fahrenheit temp to Celsius.
Uses if to check whether input is a number and then uses .isdigit() method
of strings to check whether input is made of of digits.
| def fahrenheit_to_celsius3():
""" MORE IMPROVED. Does even more checking of input before using it.
Input from keyboard, which is always a string and must often be
converted to an int or float.
Converts Fahrenheit temp to Celsius.
Uses if to check whether input is a number and then uses .isdigit() method
of strings to check whether input is made of of digits.
"""
temp_str = input("Enter a Fahrentheit temperature: ")
if temp_str:
if temp_str.isdigit():
temp = int(temp_str)
newTemp = 5*(temp-32)/9
print("The Fahrenheit temperature",temp,"is equivalent to ",end='')
print(newTemp,"degrees Celsius")
else:
print("You must enter a number. Bye") | [
"def",
"fahrenheit_to_celsius3",
"(",
")",
":",
"temp_str",
"=",
"input",
"(",
"\"Enter a Fahrentheit temperature: \"",
")",
"if",
"temp_str",
":",
"if",
"temp_str",
".",
"isdigit",
"(",
")",
":",
"temp",
"=",
"int",
"(",
"temp_str",
")",
"newTemp",
"=",
"5",
"*",
"(",
"temp",
"-",
"32",
")",
"/",
"9",
"print",
"(",
"\"The Fahrenheit temperature\"",
",",
"temp",
",",
"\"is equivalent to \"",
",",
"end",
"=",
"''",
")",
"print",
"(",
"newTemp",
",",
"\"degrees Celsius\"",
")",
"else",
":",
"print",
"(",
"\"You must enter a number. Bye\"",
")"
] | [
322,
0
] | [
339,
49
] | python | en | ['en', 'en', 'en'] | True |
inches_to_feet1 | (inches) | converts inches to feet and inches | converts inches to feet and inches | def inches_to_feet1(inches):
""" converts inches to feet and inches """
feet = inches//12 # division by integer with fraction thrown away
extra_inches = inches - 12*feet
print(inches,"inches is",feet,"feet and",extra_inches,"inches") | [
"def",
"inches_to_feet1",
"(",
"inches",
")",
":",
"feet",
"=",
"inches",
"//",
"12",
"# division by integer with fraction thrown away",
"extra_inches",
"=",
"inches",
"-",
"12",
"*",
"feet",
"print",
"(",
"inches",
",",
"\"inches is\"",
",",
"feet",
",",
"\"feet and\"",
",",
"extra_inches",
",",
"\"inches\"",
")"
] | [
350,
0
] | [
354,
67
] | python | en | ['en', 'en', 'en'] | True |
inches_to_feet2 | (inches) |
End solution
|
End solution
| def inches_to_feet2(inches):
#%%
"""
End solution
""" | [
"def",
"inches_to_feet2",
"(",
"inches",
")",
":",
"#%%"
] | [
368,
0
] | [
377,
3
] | python | en | ['en', 'error', 'th'] | False |
cheer | () | Prints 2 4 6 8, who do we appreciate .... Note that everything in
the while loop is indented. The first line not indented is the first
line following the while loop. | Prints 2 4 6 8, who do we appreciate .... Note that everything in
the while loop is indented. The first line not indented is the first
line following the while loop. | def cheer():
""" Prints 2 4 6 8, who do we appreciate .... Note that everything in
the while loop is indented. The first line not indented is the first
line following the while loop. """
ct = 2
while ct <= 8:
print(ct,end=" ") # end = " " keeps from starting a new line
ct = ct + 2
print() # now we'll start a new line
print("Who do we appreciate?")
print("COURSERA!") | [
"def",
"cheer",
"(",
")",
":",
"ct",
"=",
"2",
"while",
"ct",
"<=",
"8",
":",
"print",
"(",
"ct",
",",
"end",
"=",
"\" \"",
")",
"# end = \" \" keeps from starting a new line",
"ct",
"=",
"ct",
"+",
"2",
"print",
"(",
")",
"# now we'll start a new line",
"print",
"(",
"\"Who do we appreciate?\"",
")",
"print",
"(",
"\"COURSERA!\"",
")"
] | [
383,
0
] | [
393,
22
] | python | en | ['en', 'en', 'en'] | True |
cheer2 | () | Same as cheer, but uses a for loop and range()
range uses a start number, a stop number and a step size. | Same as cheer, but uses a for loop and range()
range uses a start number, a stop number and a step size. | def cheer2():
""" Same as cheer, but uses a for loop and range()
range uses a start number, a stop number and a step size. """
for ct in range(2,9,2):
print(ct,end=' ')
print()
print("Who do we appreciate?")
print("COURSERA!") | [
"def",
"cheer2",
"(",
")",
":",
"for",
"ct",
"in",
"range",
"(",
"2",
",",
"9",
",",
"2",
")",
":",
"print",
"(",
"ct",
",",
"end",
"=",
"' '",
")",
"print",
"(",
")",
"print",
"(",
"\"Who do we appreciate?\"",
")",
"print",
"(",
"\"COURSERA!\"",
")"
] | [
423,
0
] | [
430,
22
] | python | en | ['en', 'en', 'en'] | True |
countdown1 | () |
End solution
|
End solution
| def countdown1():
#%%
"""
End solution
""" | [
"def",
"countdown1",
"(",
")",
":",
"#%%"
] | [
444,
0
] | [
452,
3
] | python | en | ['en', 'error', 'th'] | False |
TFXLNetRelativeAttention.rel_shift | (self, x, klen=-1) | perform relative shift to form the relative attention score. | perform relative shift to form the relative attention score. | def rel_shift(self, x, klen=-1):
"""perform relative shift to form the relative attention score."""
x_size = shape_list(x)
x = tf.reshape(x, (x_size[1], x_size[0], x_size[2], x_size[3]))
x = x[1:, ...]
x = tf.reshape(x, (x_size[0], x_size[1] - 1, x_size[2], x_size[3]))
x = x[:, 0:klen, :, :]
# x = torch.index_select(x, 1, torch.arange(klen, device=x.device, dtype=torch.long))
return x | [
"def",
"rel_shift",
"(",
"self",
",",
"x",
",",
"klen",
"=",
"-",
"1",
")",
":",
"x_size",
"=",
"shape_list",
"(",
"x",
")",
"x",
"=",
"tf",
".",
"reshape",
"(",
"x",
",",
"(",
"x_size",
"[",
"1",
"]",
",",
"x_size",
"[",
"0",
"]",
",",
"x_size",
"[",
"2",
"]",
",",
"x_size",
"[",
"3",
"]",
")",
")",
"x",
"=",
"x",
"[",
"1",
":",
",",
"...",
"]",
"x",
"=",
"tf",
".",
"reshape",
"(",
"x",
",",
"(",
"x_size",
"[",
"0",
"]",
",",
"x_size",
"[",
"1",
"]",
"-",
"1",
",",
"x_size",
"[",
"2",
"]",
",",
"x_size",
"[",
"3",
"]",
")",
")",
"x",
"=",
"x",
"[",
":",
",",
"0",
":",
"klen",
",",
":",
",",
":",
"]",
"# x = torch.index_select(x, 1, torch.arange(klen, device=x.device, dtype=torch.long))",
"return",
"x"
] | [
119,
4
] | [
129,
16
] | python | en | ['en', 'en', 'en'] | True |
TFXLNetRelativeAttention.rel_attn_core | (
self, q_head, k_head_h, v_head_h, k_head_r, seg_mat, attn_mask, head_mask, output_attentions, training=False
) | Core relative positional attention operations. | Core relative positional attention operations. | def rel_attn_core(
self, q_head, k_head_h, v_head_h, k_head_r, seg_mat, attn_mask, head_mask, output_attentions, training=False
):
"""Core relative positional attention operations."""
# content based attention score
ac = tf.einsum("ibnd,jbnd->ijbn", q_head + self.r_w_bias, k_head_h)
# position based attention score
bd = tf.einsum("ibnd,jbnd->ijbn", q_head + self.r_r_bias, k_head_r)
bd = self.rel_shift(bd, klen=shape_list(ac)[1])
# segment based attention score
if seg_mat is None:
ef = 0
else:
ef = tf.einsum("ibnd,snd->ibns", q_head + self.r_s_bias, self.seg_embed)
ef = tf.einsum("ijbs,ibns->ijbn", seg_mat, ef)
# merge attention scores and perform masking
attn_score = (ac + bd + ef) * self.scale
if attn_mask is not None:
# attn_score = attn_score * (1 - attn_mask) - 1e30 * attn_mask
if attn_mask.dtype == tf.float16 or attn_mask.dtype == tf.bfloat16:
attn_score = attn_score - 65500 * attn_mask
else:
attn_score = attn_score - 1e30 * attn_mask
# attention probability
attn_prob = tf.nn.softmax(attn_score, axis=1)
attn_prob = self.dropout(attn_prob, training=training)
# Mask heads if we want to
if head_mask is not None:
attn_prob = attn_prob * head_mask
# attention output
attn_vec = tf.einsum("ijbn,jbnd->ibnd", attn_prob, v_head_h)
if output_attentions:
return attn_vec, attn_prob
return attn_vec | [
"def",
"rel_attn_core",
"(",
"self",
",",
"q_head",
",",
"k_head_h",
",",
"v_head_h",
",",
"k_head_r",
",",
"seg_mat",
",",
"attn_mask",
",",
"head_mask",
",",
"output_attentions",
",",
"training",
"=",
"False",
")",
":",
"# content based attention score",
"ac",
"=",
"tf",
".",
"einsum",
"(",
"\"ibnd,jbnd->ijbn\"",
",",
"q_head",
"+",
"self",
".",
"r_w_bias",
",",
"k_head_h",
")",
"# position based attention score",
"bd",
"=",
"tf",
".",
"einsum",
"(",
"\"ibnd,jbnd->ijbn\"",
",",
"q_head",
"+",
"self",
".",
"r_r_bias",
",",
"k_head_r",
")",
"bd",
"=",
"self",
".",
"rel_shift",
"(",
"bd",
",",
"klen",
"=",
"shape_list",
"(",
"ac",
")",
"[",
"1",
"]",
")",
"# segment based attention score",
"if",
"seg_mat",
"is",
"None",
":",
"ef",
"=",
"0",
"else",
":",
"ef",
"=",
"tf",
".",
"einsum",
"(",
"\"ibnd,snd->ibns\"",
",",
"q_head",
"+",
"self",
".",
"r_s_bias",
",",
"self",
".",
"seg_embed",
")",
"ef",
"=",
"tf",
".",
"einsum",
"(",
"\"ijbs,ibns->ijbn\"",
",",
"seg_mat",
",",
"ef",
")",
"# merge attention scores and perform masking",
"attn_score",
"=",
"(",
"ac",
"+",
"bd",
"+",
"ef",
")",
"*",
"self",
".",
"scale",
"if",
"attn_mask",
"is",
"not",
"None",
":",
"# attn_score = attn_score * (1 - attn_mask) - 1e30 * attn_mask",
"if",
"attn_mask",
".",
"dtype",
"==",
"tf",
".",
"float16",
"or",
"attn_mask",
".",
"dtype",
"==",
"tf",
".",
"bfloat16",
":",
"attn_score",
"=",
"attn_score",
"-",
"65500",
"*",
"attn_mask",
"else",
":",
"attn_score",
"=",
"attn_score",
"-",
"1e30",
"*",
"attn_mask",
"# attention probability",
"attn_prob",
"=",
"tf",
".",
"nn",
".",
"softmax",
"(",
"attn_score",
",",
"axis",
"=",
"1",
")",
"attn_prob",
"=",
"self",
".",
"dropout",
"(",
"attn_prob",
",",
"training",
"=",
"training",
")",
"# Mask heads if we want to",
"if",
"head_mask",
"is",
"not",
"None",
":",
"attn_prob",
"=",
"attn_prob",
"*",
"head_mask",
"# attention output",
"attn_vec",
"=",
"tf",
".",
"einsum",
"(",
"\"ijbn,jbnd->ibnd\"",
",",
"attn_prob",
",",
"v_head_h",
")",
"if",
"output_attentions",
":",
"return",
"attn_vec",
",",
"attn_prob",
"return",
"attn_vec"
] | [
131,
4
] | [
173,
23
] | python | en | ['en', 'en', 'en'] | True |
TFXLNetRelativeAttention.post_attention | (self, h, attn_vec, residual=True, training=False) | Post-attention processing. | Post-attention processing. | def post_attention(self, h, attn_vec, residual=True, training=False):
"""Post-attention processing."""
# post-attention projection (back to `d_model`)
attn_out = tf.einsum("ibnd,hnd->ibh", attn_vec, self.o)
attn_out = self.dropout(attn_out, training=training)
if residual:
attn_out = attn_out + h
output = self.layer_norm(attn_out)
return output | [
"def",
"post_attention",
"(",
"self",
",",
"h",
",",
"attn_vec",
",",
"residual",
"=",
"True",
",",
"training",
"=",
"False",
")",
":",
"# post-attention projection (back to `d_model`)",
"attn_out",
"=",
"tf",
".",
"einsum",
"(",
"\"ibnd,hnd->ibh\"",
",",
"attn_vec",
",",
"self",
".",
"o",
")",
"attn_out",
"=",
"self",
".",
"dropout",
"(",
"attn_out",
",",
"training",
"=",
"training",
")",
"if",
"residual",
":",
"attn_out",
"=",
"attn_out",
"+",
"h",
"output",
"=",
"self",
".",
"layer_norm",
"(",
"attn_out",
")",
"return",
"output"
] | [
175,
4
] | [
186,
21
] | python | en | ['en', 'en', 'en'] | False |
mock_panel_fixture | () | Mock a Konnected Panel bridge. | Mock a Konnected Panel bridge. | async def mock_panel_fixture():
"""Mock a Konnected Panel bridge."""
with patch("konnected.Client", autospec=True) as konn_client:
def mock_constructor(host, port, websession):
"""Fake the panel constructor."""
konn_client.host = host
konn_client.port = port
return konn_client
konn_client.side_effect = mock_constructor
konn_client.ClientError = config_flow.CannotConnect
konn_client.get_status.return_value = {
"hwVersion": "2.3.0",
"swVersion": "2.3.1",
"heap": 10000,
"uptime": 12222,
"ip": "192.168.1.90",
"port": 9123,
"sensors": [],
"actuators": [],
"dht_sensors": [],
"ds18b20_sensors": [],
"mac": "11:22:33:44:55:66",
"model": "Konnected Pro", # `model` field only included in pro
"settings": {},
}
yield konn_client | [
"async",
"def",
"mock_panel_fixture",
"(",
")",
":",
"with",
"patch",
"(",
"\"konnected.Client\"",
",",
"autospec",
"=",
"True",
")",
"as",
"konn_client",
":",
"def",
"mock_constructor",
"(",
"host",
",",
"port",
",",
"websession",
")",
":",
"\"\"\"Fake the panel constructor.\"\"\"",
"konn_client",
".",
"host",
"=",
"host",
"konn_client",
".",
"port",
"=",
"port",
"return",
"konn_client",
"konn_client",
".",
"side_effect",
"=",
"mock_constructor",
"konn_client",
".",
"ClientError",
"=",
"config_flow",
".",
"CannotConnect",
"konn_client",
".",
"get_status",
".",
"return_value",
"=",
"{",
"\"hwVersion\"",
":",
"\"2.3.0\"",
",",
"\"swVersion\"",
":",
"\"2.3.1\"",
",",
"\"heap\"",
":",
"10000",
",",
"\"uptime\"",
":",
"12222",
",",
"\"ip\"",
":",
"\"192.168.1.90\"",
",",
"\"port\"",
":",
"9123",
",",
"\"sensors\"",
":",
"[",
"]",
",",
"\"actuators\"",
":",
"[",
"]",
",",
"\"dht_sensors\"",
":",
"[",
"]",
",",
"\"ds18b20_sensors\"",
":",
"[",
"]",
",",
"\"mac\"",
":",
"\"11:22:33:44:55:66\"",
",",
"\"model\"",
":",
"\"Konnected Pro\"",
",",
"# `model` field only included in pro",
"\"settings\"",
":",
"{",
"}",
",",
"}",
"yield",
"konn_client"
] | [
14,
0
] | [
41,
25
] | python | en | ['it', 'st', 'en'] | False |
test_create_and_setup | (hass, mock_panel) | Test that we create a Konnected Panel and save the data. | Test that we create a Konnected Panel and save the data. | async def test_create_and_setup(hass, mock_panel):
"""Test that we create a Konnected Panel and save the data."""
device_config = config_flow.CONFIG_ENTRY_SCHEMA(
{
"host": "1.2.3.4",
"port": 1234,
"id": "112233445566",
"model": "Konnected Pro",
"access_token": "11223344556677889900",
"default_options": config_flow.OPTIONS_SCHEMA({config_flow.CONF_IO: {}}),
}
)
device_options = config_flow.OPTIONS_SCHEMA(
{
"io": {
"1": "Binary Sensor",
"2": "Binary Sensor",
"3": "Binary Sensor",
"4": "Digital Sensor",
"5": "Digital Sensor",
"6": "Switchable Output",
"out": "Switchable Output",
},
"binary_sensors": [
{"zone": "1", "type": "door"},
{"zone": "2", "type": "window", "name": "winder", "inverse": True},
{"zone": "3", "type": "door"},
],
"sensors": [
{"zone": "4", "type": "dht"},
{"zone": "5", "type": "ds18b20", "name": "temper"},
],
"switches": [
{
"zone": "out",
"name": "switcher",
"activation": "low",
"momentary": 50,
"pause": 100,
"repeat": 4,
},
{"zone": "6"},
],
}
)
entry = MockConfigEntry(
domain="konnected",
title="Konnected Alarm Panel",
data=device_config,
options=device_options,
)
entry.add_to_hass(hass)
# override get_status to reflect non-pro board
mock_panel.get_status.return_value = {
"hwVersion": "2.3.0",
"swVersion": "2.3.1",
"heap": 10000,
"uptime": 12222,
"ip": "192.168.1.90",
"port": 9123,
"sensors": [],
"actuators": [],
"dht_sensors": [],
"ds18b20_sensors": [],
"mac": "11:22:33:44:55:66",
"settings": {},
}
# setup the integration and inspect panel behavior
assert (
await async_setup_component(
hass,
panel.DOMAIN,
{
panel.DOMAIN: {
panel.CONF_ACCESS_TOKEN: "arandomstringvalue",
panel.CONF_API_HOST: "http://192.168.1.1:8123",
}
},
)
is True
)
# confirm panel instance was created and configured
# hass.data is the only mechanism to get a reference to the created panel instance
device = hass.data[panel.DOMAIN][panel.CONF_DEVICES]["112233445566"]["panel"]
await device.update_switch("1", 0)
# confirm the correct api is used
# pylint: disable=no-member
assert mock_panel.put_device.call_count == 1
assert mock_panel.put_zone.call_count == 0
# confirm the settings are sent to the panel
# pylint: disable=no-member
assert mock_panel.put_settings.call_args_list[0][1] == {
"sensors": [{"pin": "1"}, {"pin": "2"}, {"pin": "5"}],
"actuators": [{"trigger": 0, "pin": "8"}, {"trigger": 1, "pin": "9"}],
"dht_sensors": [{"poll_interval": 3, "pin": "6"}],
"ds18b20_sensors": [{"pin": "7"}],
"auth_token": "11223344556677889900",
"blink": True,
"discovery": True,
"endpoint": "http://192.168.1.1:8123/api/konnected",
}
# confirm the device settings are saved in hass.data
assert device.stored_configuration == {
"binary_sensors": {
"1": {
"inverse": False,
"name": "Konnected 445566 Zone 1",
"state": None,
"type": "door",
},
"2": {"inverse": True, "name": "winder", "state": None, "type": "window"},
"3": {
"inverse": False,
"name": "Konnected 445566 Zone 3",
"state": None,
"type": "door",
},
},
"blink": True,
"panel": device,
"discovery": True,
"host": "1.2.3.4",
"port": 1234,
"sensors": [
{
"name": "Konnected 445566 Sensor 4",
"poll_interval": 3,
"type": "dht",
"zone": "4",
},
{"name": "temper", "poll_interval": 3, "type": "ds18b20", "zone": "5"},
],
"switches": [
{
"activation": "low",
"momentary": 50,
"name": "switcher",
"pause": 100,
"repeat": 4,
"state": None,
"zone": "out",
},
{
"activation": "high",
"momentary": None,
"name": "Konnected 445566 Actuator 6",
"pause": None,
"repeat": None,
"state": None,
"zone": "6",
},
],
} | [
"async",
"def",
"test_create_and_setup",
"(",
"hass",
",",
"mock_panel",
")",
":",
"device_config",
"=",
"config_flow",
".",
"CONFIG_ENTRY_SCHEMA",
"(",
"{",
"\"host\"",
":",
"\"1.2.3.4\"",
",",
"\"port\"",
":",
"1234",
",",
"\"id\"",
":",
"\"112233445566\"",
",",
"\"model\"",
":",
"\"Konnected Pro\"",
",",
"\"access_token\"",
":",
"\"11223344556677889900\"",
",",
"\"default_options\"",
":",
"config_flow",
".",
"OPTIONS_SCHEMA",
"(",
"{",
"config_flow",
".",
"CONF_IO",
":",
"{",
"}",
"}",
")",
",",
"}",
")",
"device_options",
"=",
"config_flow",
".",
"OPTIONS_SCHEMA",
"(",
"{",
"\"io\"",
":",
"{",
"\"1\"",
":",
"\"Binary Sensor\"",
",",
"\"2\"",
":",
"\"Binary Sensor\"",
",",
"\"3\"",
":",
"\"Binary Sensor\"",
",",
"\"4\"",
":",
"\"Digital Sensor\"",
",",
"\"5\"",
":",
"\"Digital Sensor\"",
",",
"\"6\"",
":",
"\"Switchable Output\"",
",",
"\"out\"",
":",
"\"Switchable Output\"",
",",
"}",
",",
"\"binary_sensors\"",
":",
"[",
"{",
"\"zone\"",
":",
"\"1\"",
",",
"\"type\"",
":",
"\"door\"",
"}",
",",
"{",
"\"zone\"",
":",
"\"2\"",
",",
"\"type\"",
":",
"\"window\"",
",",
"\"name\"",
":",
"\"winder\"",
",",
"\"inverse\"",
":",
"True",
"}",
",",
"{",
"\"zone\"",
":",
"\"3\"",
",",
"\"type\"",
":",
"\"door\"",
"}",
",",
"]",
",",
"\"sensors\"",
":",
"[",
"{",
"\"zone\"",
":",
"\"4\"",
",",
"\"type\"",
":",
"\"dht\"",
"}",
",",
"{",
"\"zone\"",
":",
"\"5\"",
",",
"\"type\"",
":",
"\"ds18b20\"",
",",
"\"name\"",
":",
"\"temper\"",
"}",
",",
"]",
",",
"\"switches\"",
":",
"[",
"{",
"\"zone\"",
":",
"\"out\"",
",",
"\"name\"",
":",
"\"switcher\"",
",",
"\"activation\"",
":",
"\"low\"",
",",
"\"momentary\"",
":",
"50",
",",
"\"pause\"",
":",
"100",
",",
"\"repeat\"",
":",
"4",
",",
"}",
",",
"{",
"\"zone\"",
":",
"\"6\"",
"}",
",",
"]",
",",
"}",
")",
"entry",
"=",
"MockConfigEntry",
"(",
"domain",
"=",
"\"konnected\"",
",",
"title",
"=",
"\"Konnected Alarm Panel\"",
",",
"data",
"=",
"device_config",
",",
"options",
"=",
"device_options",
",",
")",
"entry",
".",
"add_to_hass",
"(",
"hass",
")",
"# override get_status to reflect non-pro board",
"mock_panel",
".",
"get_status",
".",
"return_value",
"=",
"{",
"\"hwVersion\"",
":",
"\"2.3.0\"",
",",
"\"swVersion\"",
":",
"\"2.3.1\"",
",",
"\"heap\"",
":",
"10000",
",",
"\"uptime\"",
":",
"12222",
",",
"\"ip\"",
":",
"\"192.168.1.90\"",
",",
"\"port\"",
":",
"9123",
",",
"\"sensors\"",
":",
"[",
"]",
",",
"\"actuators\"",
":",
"[",
"]",
",",
"\"dht_sensors\"",
":",
"[",
"]",
",",
"\"ds18b20_sensors\"",
":",
"[",
"]",
",",
"\"mac\"",
":",
"\"11:22:33:44:55:66\"",
",",
"\"settings\"",
":",
"{",
"}",
",",
"}",
"# setup the integration and inspect panel behavior",
"assert",
"(",
"await",
"async_setup_component",
"(",
"hass",
",",
"panel",
".",
"DOMAIN",
",",
"{",
"panel",
".",
"DOMAIN",
":",
"{",
"panel",
".",
"CONF_ACCESS_TOKEN",
":",
"\"arandomstringvalue\"",
",",
"panel",
".",
"CONF_API_HOST",
":",
"\"http://192.168.1.1:8123\"",
",",
"}",
"}",
",",
")",
"is",
"True",
")",
"# confirm panel instance was created and configured",
"# hass.data is the only mechanism to get a reference to the created panel instance",
"device",
"=",
"hass",
".",
"data",
"[",
"panel",
".",
"DOMAIN",
"]",
"[",
"panel",
".",
"CONF_DEVICES",
"]",
"[",
"\"112233445566\"",
"]",
"[",
"\"panel\"",
"]",
"await",
"device",
".",
"update_switch",
"(",
"\"1\"",
",",
"0",
")",
"# confirm the correct api is used",
"# pylint: disable=no-member",
"assert",
"mock_panel",
".",
"put_device",
".",
"call_count",
"==",
"1",
"assert",
"mock_panel",
".",
"put_zone",
".",
"call_count",
"==",
"0",
"# confirm the settings are sent to the panel",
"# pylint: disable=no-member",
"assert",
"mock_panel",
".",
"put_settings",
".",
"call_args_list",
"[",
"0",
"]",
"[",
"1",
"]",
"==",
"{",
"\"sensors\"",
":",
"[",
"{",
"\"pin\"",
":",
"\"1\"",
"}",
",",
"{",
"\"pin\"",
":",
"\"2\"",
"}",
",",
"{",
"\"pin\"",
":",
"\"5\"",
"}",
"]",
",",
"\"actuators\"",
":",
"[",
"{",
"\"trigger\"",
":",
"0",
",",
"\"pin\"",
":",
"\"8\"",
"}",
",",
"{",
"\"trigger\"",
":",
"1",
",",
"\"pin\"",
":",
"\"9\"",
"}",
"]",
",",
"\"dht_sensors\"",
":",
"[",
"{",
"\"poll_interval\"",
":",
"3",
",",
"\"pin\"",
":",
"\"6\"",
"}",
"]",
",",
"\"ds18b20_sensors\"",
":",
"[",
"{",
"\"pin\"",
":",
"\"7\"",
"}",
"]",
",",
"\"auth_token\"",
":",
"\"11223344556677889900\"",
",",
"\"blink\"",
":",
"True",
",",
"\"discovery\"",
":",
"True",
",",
"\"endpoint\"",
":",
"\"http://192.168.1.1:8123/api/konnected\"",
",",
"}",
"# confirm the device settings are saved in hass.data",
"assert",
"device",
".",
"stored_configuration",
"==",
"{",
"\"binary_sensors\"",
":",
"{",
"\"1\"",
":",
"{",
"\"inverse\"",
":",
"False",
",",
"\"name\"",
":",
"\"Konnected 445566 Zone 1\"",
",",
"\"state\"",
":",
"None",
",",
"\"type\"",
":",
"\"door\"",
",",
"}",
",",
"\"2\"",
":",
"{",
"\"inverse\"",
":",
"True",
",",
"\"name\"",
":",
"\"winder\"",
",",
"\"state\"",
":",
"None",
",",
"\"type\"",
":",
"\"window\"",
"}",
",",
"\"3\"",
":",
"{",
"\"inverse\"",
":",
"False",
",",
"\"name\"",
":",
"\"Konnected 445566 Zone 3\"",
",",
"\"state\"",
":",
"None",
",",
"\"type\"",
":",
"\"door\"",
",",
"}",
",",
"}",
",",
"\"blink\"",
":",
"True",
",",
"\"panel\"",
":",
"device",
",",
"\"discovery\"",
":",
"True",
",",
"\"host\"",
":",
"\"1.2.3.4\"",
",",
"\"port\"",
":",
"1234",
",",
"\"sensors\"",
":",
"[",
"{",
"\"name\"",
":",
"\"Konnected 445566 Sensor 4\"",
",",
"\"poll_interval\"",
":",
"3",
",",
"\"type\"",
":",
"\"dht\"",
",",
"\"zone\"",
":",
"\"4\"",
",",
"}",
",",
"{",
"\"name\"",
":",
"\"temper\"",
",",
"\"poll_interval\"",
":",
"3",
",",
"\"type\"",
":",
"\"ds18b20\"",
",",
"\"zone\"",
":",
"\"5\"",
"}",
",",
"]",
",",
"\"switches\"",
":",
"[",
"{",
"\"activation\"",
":",
"\"low\"",
",",
"\"momentary\"",
":",
"50",
",",
"\"name\"",
":",
"\"switcher\"",
",",
"\"pause\"",
":",
"100",
",",
"\"repeat\"",
":",
"4",
",",
"\"state\"",
":",
"None",
",",
"\"zone\"",
":",
"\"out\"",
",",
"}",
",",
"{",
"\"activation\"",
":",
"\"high\"",
",",
"\"momentary\"",
":",
"None",
",",
"\"name\"",
":",
"\"Konnected 445566 Actuator 6\"",
",",
"\"pause\"",
":",
"None",
",",
"\"repeat\"",
":",
"None",
",",
"\"state\"",
":",
"None",
",",
"\"zone\"",
":",
"\"6\"",
",",
"}",
",",
"]",
",",
"}"
] | [
44,
0
] | [
204,
5
] | python | en | ['en', 'en', 'en'] | True |
test_create_and_setup_pro | (hass, mock_panel) | Test that we create a Konnected Pro Panel and save the data. | Test that we create a Konnected Pro Panel and save the data. | async def test_create_and_setup_pro(hass, mock_panel):
"""Test that we create a Konnected Pro Panel and save the data."""
device_config = config_flow.CONFIG_ENTRY_SCHEMA(
{
"host": "1.2.3.4",
"port": 1234,
"id": "112233445566",
"model": "Konnected Pro",
"access_token": "11223344556677889900",
"default_options": config_flow.OPTIONS_SCHEMA({config_flow.CONF_IO: {}}),
}
)
device_options = config_flow.OPTIONS_SCHEMA(
{
"io": {
"2": "Binary Sensor",
"6": "Binary Sensor",
"10": "Binary Sensor",
"11": "Binary Sensor",
"3": "Digital Sensor",
"7": "Digital Sensor",
"4": "Switchable Output",
"8": "Switchable Output",
"out1": "Switchable Output",
"alarm1": "Switchable Output",
},
"binary_sensors": [
{"zone": "2", "type": "door"},
{"zone": "6", "type": "window", "name": "winder", "inverse": True},
{"zone": "10", "type": "door"},
{"zone": "11", "type": "window"},
],
"sensors": [
{"zone": "3", "type": "dht", "poll_interval": 5},
{"zone": "7", "type": "ds18b20", "name": "temper"},
],
"switches": [
{"zone": "4"},
{
"zone": "8",
"name": "switcher",
"activation": "low",
"momentary": 50,
"pause": 100,
"repeat": 4,
},
{"zone": "out1"},
{"zone": "alarm1"},
],
}
)
entry = MockConfigEntry(
domain="konnected",
title="Konnected Pro Alarm Panel",
data=device_config,
options=device_options,
)
entry.add_to_hass(hass)
# setup the integration and inspect panel behavior
assert (
await async_setup_component(
hass,
panel.DOMAIN,
{
panel.DOMAIN: {
panel.CONF_ACCESS_TOKEN: "arandomstringvalue",
panel.CONF_API_HOST: "http://192.168.1.1:8123",
}
},
)
is True
)
# confirm panel instance was created and configured
# hass.data is the only mechanism to get a reference to the created panel instance
device = hass.data[panel.DOMAIN][panel.CONF_DEVICES]["112233445566"]["panel"]
await device.update_switch("2", 1)
# confirm the correct api is used
# pylint: disable=no-member
assert mock_panel.put_device.call_count == 0
assert mock_panel.put_zone.call_count == 1
# confirm the settings are sent to the panel
# pylint: disable=no-member
assert mock_panel.put_settings.call_args_list[0][1] == {
"sensors": [{"zone": "2"}, {"zone": "6"}, {"zone": "10"}, {"zone": "11"}],
"actuators": [
{"trigger": 1, "zone": "4"},
{"trigger": 0, "zone": "8"},
{"trigger": 1, "zone": "out1"},
{"trigger": 1, "zone": "alarm1"},
],
"dht_sensors": [{"poll_interval": 5, "zone": "3"}],
"ds18b20_sensors": [{"zone": "7"}],
"auth_token": "11223344556677889900",
"blink": True,
"discovery": True,
"endpoint": "http://192.168.1.1:8123/api/konnected",
}
# confirm the device settings are saved in hass.data
assert device.stored_configuration == {
"binary_sensors": {
"11": {
"inverse": False,
"name": "Konnected 445566 Zone 11",
"state": None,
"type": "window",
},
"10": {
"inverse": False,
"name": "Konnected 445566 Zone 10",
"state": None,
"type": "door",
},
"2": {
"inverse": False,
"name": "Konnected 445566 Zone 2",
"state": None,
"type": "door",
},
"6": {"inverse": True, "name": "winder", "state": None, "type": "window"},
},
"blink": True,
"panel": device,
"discovery": True,
"host": "1.2.3.4",
"port": 1234,
"sensors": [
{
"name": "Konnected 445566 Sensor 3",
"poll_interval": 5,
"type": "dht",
"zone": "3",
},
{"name": "temper", "poll_interval": 3, "type": "ds18b20", "zone": "7"},
],
"switches": [
{
"activation": "high",
"momentary": None,
"name": "Konnected 445566 Actuator 4",
"pause": None,
"repeat": None,
"state": None,
"zone": "4",
},
{
"activation": "low",
"momentary": 50,
"name": "switcher",
"pause": 100,
"repeat": 4,
"state": None,
"zone": "8",
},
{
"activation": "high",
"momentary": None,
"name": "Konnected 445566 Actuator out1",
"pause": None,
"repeat": None,
"state": None,
"zone": "out1",
},
{
"activation": "high",
"momentary": None,
"name": "Konnected 445566 Actuator alarm1",
"pause": None,
"repeat": None,
"state": None,
"zone": "alarm1",
},
],
} | [
"async",
"def",
"test_create_and_setup_pro",
"(",
"hass",
",",
"mock_panel",
")",
":",
"device_config",
"=",
"config_flow",
".",
"CONFIG_ENTRY_SCHEMA",
"(",
"{",
"\"host\"",
":",
"\"1.2.3.4\"",
",",
"\"port\"",
":",
"1234",
",",
"\"id\"",
":",
"\"112233445566\"",
",",
"\"model\"",
":",
"\"Konnected Pro\"",
",",
"\"access_token\"",
":",
"\"11223344556677889900\"",
",",
"\"default_options\"",
":",
"config_flow",
".",
"OPTIONS_SCHEMA",
"(",
"{",
"config_flow",
".",
"CONF_IO",
":",
"{",
"}",
"}",
")",
",",
"}",
")",
"device_options",
"=",
"config_flow",
".",
"OPTIONS_SCHEMA",
"(",
"{",
"\"io\"",
":",
"{",
"\"2\"",
":",
"\"Binary Sensor\"",
",",
"\"6\"",
":",
"\"Binary Sensor\"",
",",
"\"10\"",
":",
"\"Binary Sensor\"",
",",
"\"11\"",
":",
"\"Binary Sensor\"",
",",
"\"3\"",
":",
"\"Digital Sensor\"",
",",
"\"7\"",
":",
"\"Digital Sensor\"",
",",
"\"4\"",
":",
"\"Switchable Output\"",
",",
"\"8\"",
":",
"\"Switchable Output\"",
",",
"\"out1\"",
":",
"\"Switchable Output\"",
",",
"\"alarm1\"",
":",
"\"Switchable Output\"",
",",
"}",
",",
"\"binary_sensors\"",
":",
"[",
"{",
"\"zone\"",
":",
"\"2\"",
",",
"\"type\"",
":",
"\"door\"",
"}",
",",
"{",
"\"zone\"",
":",
"\"6\"",
",",
"\"type\"",
":",
"\"window\"",
",",
"\"name\"",
":",
"\"winder\"",
",",
"\"inverse\"",
":",
"True",
"}",
",",
"{",
"\"zone\"",
":",
"\"10\"",
",",
"\"type\"",
":",
"\"door\"",
"}",
",",
"{",
"\"zone\"",
":",
"\"11\"",
",",
"\"type\"",
":",
"\"window\"",
"}",
",",
"]",
",",
"\"sensors\"",
":",
"[",
"{",
"\"zone\"",
":",
"\"3\"",
",",
"\"type\"",
":",
"\"dht\"",
",",
"\"poll_interval\"",
":",
"5",
"}",
",",
"{",
"\"zone\"",
":",
"\"7\"",
",",
"\"type\"",
":",
"\"ds18b20\"",
",",
"\"name\"",
":",
"\"temper\"",
"}",
",",
"]",
",",
"\"switches\"",
":",
"[",
"{",
"\"zone\"",
":",
"\"4\"",
"}",
",",
"{",
"\"zone\"",
":",
"\"8\"",
",",
"\"name\"",
":",
"\"switcher\"",
",",
"\"activation\"",
":",
"\"low\"",
",",
"\"momentary\"",
":",
"50",
",",
"\"pause\"",
":",
"100",
",",
"\"repeat\"",
":",
"4",
",",
"}",
",",
"{",
"\"zone\"",
":",
"\"out1\"",
"}",
",",
"{",
"\"zone\"",
":",
"\"alarm1\"",
"}",
",",
"]",
",",
"}",
")",
"entry",
"=",
"MockConfigEntry",
"(",
"domain",
"=",
"\"konnected\"",
",",
"title",
"=",
"\"Konnected Pro Alarm Panel\"",
",",
"data",
"=",
"device_config",
",",
"options",
"=",
"device_options",
",",
")",
"entry",
".",
"add_to_hass",
"(",
"hass",
")",
"# setup the integration and inspect panel behavior",
"assert",
"(",
"await",
"async_setup_component",
"(",
"hass",
",",
"panel",
".",
"DOMAIN",
",",
"{",
"panel",
".",
"DOMAIN",
":",
"{",
"panel",
".",
"CONF_ACCESS_TOKEN",
":",
"\"arandomstringvalue\"",
",",
"panel",
".",
"CONF_API_HOST",
":",
"\"http://192.168.1.1:8123\"",
",",
"}",
"}",
",",
")",
"is",
"True",
")",
"# confirm panel instance was created and configured",
"# hass.data is the only mechanism to get a reference to the created panel instance",
"device",
"=",
"hass",
".",
"data",
"[",
"panel",
".",
"DOMAIN",
"]",
"[",
"panel",
".",
"CONF_DEVICES",
"]",
"[",
"\"112233445566\"",
"]",
"[",
"\"panel\"",
"]",
"await",
"device",
".",
"update_switch",
"(",
"\"2\"",
",",
"1",
")",
"# confirm the correct api is used",
"# pylint: disable=no-member",
"assert",
"mock_panel",
".",
"put_device",
".",
"call_count",
"==",
"0",
"assert",
"mock_panel",
".",
"put_zone",
".",
"call_count",
"==",
"1",
"# confirm the settings are sent to the panel",
"# pylint: disable=no-member",
"assert",
"mock_panel",
".",
"put_settings",
".",
"call_args_list",
"[",
"0",
"]",
"[",
"1",
"]",
"==",
"{",
"\"sensors\"",
":",
"[",
"{",
"\"zone\"",
":",
"\"2\"",
"}",
",",
"{",
"\"zone\"",
":",
"\"6\"",
"}",
",",
"{",
"\"zone\"",
":",
"\"10\"",
"}",
",",
"{",
"\"zone\"",
":",
"\"11\"",
"}",
"]",
",",
"\"actuators\"",
":",
"[",
"{",
"\"trigger\"",
":",
"1",
",",
"\"zone\"",
":",
"\"4\"",
"}",
",",
"{",
"\"trigger\"",
":",
"0",
",",
"\"zone\"",
":",
"\"8\"",
"}",
",",
"{",
"\"trigger\"",
":",
"1",
",",
"\"zone\"",
":",
"\"out1\"",
"}",
",",
"{",
"\"trigger\"",
":",
"1",
",",
"\"zone\"",
":",
"\"alarm1\"",
"}",
",",
"]",
",",
"\"dht_sensors\"",
":",
"[",
"{",
"\"poll_interval\"",
":",
"5",
",",
"\"zone\"",
":",
"\"3\"",
"}",
"]",
",",
"\"ds18b20_sensors\"",
":",
"[",
"{",
"\"zone\"",
":",
"\"7\"",
"}",
"]",
",",
"\"auth_token\"",
":",
"\"11223344556677889900\"",
",",
"\"blink\"",
":",
"True",
",",
"\"discovery\"",
":",
"True",
",",
"\"endpoint\"",
":",
"\"http://192.168.1.1:8123/api/konnected\"",
",",
"}",
"# confirm the device settings are saved in hass.data",
"assert",
"device",
".",
"stored_configuration",
"==",
"{",
"\"binary_sensors\"",
":",
"{",
"\"11\"",
":",
"{",
"\"inverse\"",
":",
"False",
",",
"\"name\"",
":",
"\"Konnected 445566 Zone 11\"",
",",
"\"state\"",
":",
"None",
",",
"\"type\"",
":",
"\"window\"",
",",
"}",
",",
"\"10\"",
":",
"{",
"\"inverse\"",
":",
"False",
",",
"\"name\"",
":",
"\"Konnected 445566 Zone 10\"",
",",
"\"state\"",
":",
"None",
",",
"\"type\"",
":",
"\"door\"",
",",
"}",
",",
"\"2\"",
":",
"{",
"\"inverse\"",
":",
"False",
",",
"\"name\"",
":",
"\"Konnected 445566 Zone 2\"",
",",
"\"state\"",
":",
"None",
",",
"\"type\"",
":",
"\"door\"",
",",
"}",
",",
"\"6\"",
":",
"{",
"\"inverse\"",
":",
"True",
",",
"\"name\"",
":",
"\"winder\"",
",",
"\"state\"",
":",
"None",
",",
"\"type\"",
":",
"\"window\"",
"}",
",",
"}",
",",
"\"blink\"",
":",
"True",
",",
"\"panel\"",
":",
"device",
",",
"\"discovery\"",
":",
"True",
",",
"\"host\"",
":",
"\"1.2.3.4\"",
",",
"\"port\"",
":",
"1234",
",",
"\"sensors\"",
":",
"[",
"{",
"\"name\"",
":",
"\"Konnected 445566 Sensor 3\"",
",",
"\"poll_interval\"",
":",
"5",
",",
"\"type\"",
":",
"\"dht\"",
",",
"\"zone\"",
":",
"\"3\"",
",",
"}",
",",
"{",
"\"name\"",
":",
"\"temper\"",
",",
"\"poll_interval\"",
":",
"3",
",",
"\"type\"",
":",
"\"ds18b20\"",
",",
"\"zone\"",
":",
"\"7\"",
"}",
",",
"]",
",",
"\"switches\"",
":",
"[",
"{",
"\"activation\"",
":",
"\"high\"",
",",
"\"momentary\"",
":",
"None",
",",
"\"name\"",
":",
"\"Konnected 445566 Actuator 4\"",
",",
"\"pause\"",
":",
"None",
",",
"\"repeat\"",
":",
"None",
",",
"\"state\"",
":",
"None",
",",
"\"zone\"",
":",
"\"4\"",
",",
"}",
",",
"{",
"\"activation\"",
":",
"\"low\"",
",",
"\"momentary\"",
":",
"50",
",",
"\"name\"",
":",
"\"switcher\"",
",",
"\"pause\"",
":",
"100",
",",
"\"repeat\"",
":",
"4",
",",
"\"state\"",
":",
"None",
",",
"\"zone\"",
":",
"\"8\"",
",",
"}",
",",
"{",
"\"activation\"",
":",
"\"high\"",
",",
"\"momentary\"",
":",
"None",
",",
"\"name\"",
":",
"\"Konnected 445566 Actuator out1\"",
",",
"\"pause\"",
":",
"None",
",",
"\"repeat\"",
":",
"None",
",",
"\"state\"",
":",
"None",
",",
"\"zone\"",
":",
"\"out1\"",
",",
"}",
",",
"{",
"\"activation\"",
":",
"\"high\"",
",",
"\"momentary\"",
":",
"None",
",",
"\"name\"",
":",
"\"Konnected 445566 Actuator alarm1\"",
",",
"\"pause\"",
":",
"None",
",",
"\"repeat\"",
":",
"None",
",",
"\"state\"",
":",
"None",
",",
"\"zone\"",
":",
"\"alarm1\"",
",",
"}",
",",
"]",
",",
"}"
] | [
207,
0
] | [
386,
5
] | python | en | ['en', 'en', 'en'] | True |
test_default_options | (hass, mock_panel) | Test that we create a Konnected Panel and save the data. | Test that we create a Konnected Panel and save the data. | async def test_default_options(hass, mock_panel):
"""Test that we create a Konnected Panel and save the data."""
device_config = config_flow.CONFIG_ENTRY_SCHEMA(
{
"host": "1.2.3.4",
"port": 1234,
"id": "112233445566",
"model": "Konnected Pro",
"access_token": "11223344556677889900",
"default_options": config_flow.OPTIONS_SCHEMA(
{
"io": {
"1": "Binary Sensor",
"2": "Binary Sensor",
"3": "Binary Sensor",
"4": "Digital Sensor",
"5": "Digital Sensor",
"6": "Switchable Output",
"out": "Switchable Output",
},
"binary_sensors": [
{"zone": "1", "type": "door"},
{
"zone": "2",
"type": "window",
"name": "winder",
"inverse": True,
},
{"zone": "3", "type": "door"},
],
"sensors": [
{"zone": "4", "type": "dht"},
{"zone": "5", "type": "ds18b20", "name": "temper"},
],
"switches": [
{
"zone": "out",
"name": "switcher",
"activation": "low",
"momentary": 50,
"pause": 100,
"repeat": 4,
},
{"zone": "6"},
],
}
),
}
)
entry = MockConfigEntry(
domain="konnected",
title="Konnected Alarm Panel",
data=device_config,
options={},
)
entry.add_to_hass(hass)
# override get_status to reflect non-pro board
mock_panel.get_status.return_value = {
"hwVersion": "2.3.0",
"swVersion": "2.3.1",
"heap": 10000,
"uptime": 12222,
"ip": "192.168.1.90",
"port": 9123,
"sensors": [],
"actuators": [],
"dht_sensors": [],
"ds18b20_sensors": [],
"mac": "11:22:33:44:55:66",
"settings": {},
}
# setup the integration and inspect panel behavior
assert (
await async_setup_component(
hass,
panel.DOMAIN,
{
panel.DOMAIN: {
panel.CONF_ACCESS_TOKEN: "arandomstringvalue",
panel.CONF_API_HOST: "http://192.168.1.1:8123",
}
},
)
is True
)
# confirm panel instance was created and configured.
# hass.data is the only mechanism to get a reference to the created panel instance
device = hass.data[panel.DOMAIN][panel.CONF_DEVICES]["112233445566"]["panel"]
await device.update_switch("1", 0)
# confirm the correct api is used
# pylint: disable=no-member
assert mock_panel.put_device.call_count == 1
assert mock_panel.put_zone.call_count == 0
# confirm the settings are sent to the panel
# pylint: disable=no-member
assert mock_panel.put_settings.call_args_list[0][1] == {
"sensors": [{"pin": "1"}, {"pin": "2"}, {"pin": "5"}],
"actuators": [{"trigger": 0, "pin": "8"}, {"trigger": 1, "pin": "9"}],
"dht_sensors": [{"poll_interval": 3, "pin": "6"}],
"ds18b20_sensors": [{"pin": "7"}],
"auth_token": "11223344556677889900",
"blink": True,
"discovery": True,
"endpoint": "http://192.168.1.1:8123/api/konnected",
}
# confirm the device settings are saved in hass.data
assert device.stored_configuration == {
"binary_sensors": {
"1": {
"inverse": False,
"name": "Konnected 445566 Zone 1",
"state": None,
"type": "door",
},
"2": {"inverse": True, "name": "winder", "state": None, "type": "window"},
"3": {
"inverse": False,
"name": "Konnected 445566 Zone 3",
"state": None,
"type": "door",
},
},
"blink": True,
"panel": device,
"discovery": True,
"host": "1.2.3.4",
"port": 1234,
"sensors": [
{
"name": "Konnected 445566 Sensor 4",
"poll_interval": 3,
"type": "dht",
"zone": "4",
},
{"name": "temper", "poll_interval": 3, "type": "ds18b20", "zone": "5"},
],
"switches": [
{
"activation": "low",
"momentary": 50,
"name": "switcher",
"pause": 100,
"repeat": 4,
"state": None,
"zone": "out",
},
{
"activation": "high",
"momentary": None,
"name": "Konnected 445566 Actuator 6",
"pause": None,
"repeat": None,
"state": None,
"zone": "6",
},
],
} | [
"async",
"def",
"test_default_options",
"(",
"hass",
",",
"mock_panel",
")",
":",
"device_config",
"=",
"config_flow",
".",
"CONFIG_ENTRY_SCHEMA",
"(",
"{",
"\"host\"",
":",
"\"1.2.3.4\"",
",",
"\"port\"",
":",
"1234",
",",
"\"id\"",
":",
"\"112233445566\"",
",",
"\"model\"",
":",
"\"Konnected Pro\"",
",",
"\"access_token\"",
":",
"\"11223344556677889900\"",
",",
"\"default_options\"",
":",
"config_flow",
".",
"OPTIONS_SCHEMA",
"(",
"{",
"\"io\"",
":",
"{",
"\"1\"",
":",
"\"Binary Sensor\"",
",",
"\"2\"",
":",
"\"Binary Sensor\"",
",",
"\"3\"",
":",
"\"Binary Sensor\"",
",",
"\"4\"",
":",
"\"Digital Sensor\"",
",",
"\"5\"",
":",
"\"Digital Sensor\"",
",",
"\"6\"",
":",
"\"Switchable Output\"",
",",
"\"out\"",
":",
"\"Switchable Output\"",
",",
"}",
",",
"\"binary_sensors\"",
":",
"[",
"{",
"\"zone\"",
":",
"\"1\"",
",",
"\"type\"",
":",
"\"door\"",
"}",
",",
"{",
"\"zone\"",
":",
"\"2\"",
",",
"\"type\"",
":",
"\"window\"",
",",
"\"name\"",
":",
"\"winder\"",
",",
"\"inverse\"",
":",
"True",
",",
"}",
",",
"{",
"\"zone\"",
":",
"\"3\"",
",",
"\"type\"",
":",
"\"door\"",
"}",
",",
"]",
",",
"\"sensors\"",
":",
"[",
"{",
"\"zone\"",
":",
"\"4\"",
",",
"\"type\"",
":",
"\"dht\"",
"}",
",",
"{",
"\"zone\"",
":",
"\"5\"",
",",
"\"type\"",
":",
"\"ds18b20\"",
",",
"\"name\"",
":",
"\"temper\"",
"}",
",",
"]",
",",
"\"switches\"",
":",
"[",
"{",
"\"zone\"",
":",
"\"out\"",
",",
"\"name\"",
":",
"\"switcher\"",
",",
"\"activation\"",
":",
"\"low\"",
",",
"\"momentary\"",
":",
"50",
",",
"\"pause\"",
":",
"100",
",",
"\"repeat\"",
":",
"4",
",",
"}",
",",
"{",
"\"zone\"",
":",
"\"6\"",
"}",
",",
"]",
",",
"}",
")",
",",
"}",
")",
"entry",
"=",
"MockConfigEntry",
"(",
"domain",
"=",
"\"konnected\"",
",",
"title",
"=",
"\"Konnected Alarm Panel\"",
",",
"data",
"=",
"device_config",
",",
"options",
"=",
"{",
"}",
",",
")",
"entry",
".",
"add_to_hass",
"(",
"hass",
")",
"# override get_status to reflect non-pro board",
"mock_panel",
".",
"get_status",
".",
"return_value",
"=",
"{",
"\"hwVersion\"",
":",
"\"2.3.0\"",
",",
"\"swVersion\"",
":",
"\"2.3.1\"",
",",
"\"heap\"",
":",
"10000",
",",
"\"uptime\"",
":",
"12222",
",",
"\"ip\"",
":",
"\"192.168.1.90\"",
",",
"\"port\"",
":",
"9123",
",",
"\"sensors\"",
":",
"[",
"]",
",",
"\"actuators\"",
":",
"[",
"]",
",",
"\"dht_sensors\"",
":",
"[",
"]",
",",
"\"ds18b20_sensors\"",
":",
"[",
"]",
",",
"\"mac\"",
":",
"\"11:22:33:44:55:66\"",
",",
"\"settings\"",
":",
"{",
"}",
",",
"}",
"# setup the integration and inspect panel behavior",
"assert",
"(",
"await",
"async_setup_component",
"(",
"hass",
",",
"panel",
".",
"DOMAIN",
",",
"{",
"panel",
".",
"DOMAIN",
":",
"{",
"panel",
".",
"CONF_ACCESS_TOKEN",
":",
"\"arandomstringvalue\"",
",",
"panel",
".",
"CONF_API_HOST",
":",
"\"http://192.168.1.1:8123\"",
",",
"}",
"}",
",",
")",
"is",
"True",
")",
"# confirm panel instance was created and configured.",
"# hass.data is the only mechanism to get a reference to the created panel instance",
"device",
"=",
"hass",
".",
"data",
"[",
"panel",
".",
"DOMAIN",
"]",
"[",
"panel",
".",
"CONF_DEVICES",
"]",
"[",
"\"112233445566\"",
"]",
"[",
"\"panel\"",
"]",
"await",
"device",
".",
"update_switch",
"(",
"\"1\"",
",",
"0",
")",
"# confirm the correct api is used",
"# pylint: disable=no-member",
"assert",
"mock_panel",
".",
"put_device",
".",
"call_count",
"==",
"1",
"assert",
"mock_panel",
".",
"put_zone",
".",
"call_count",
"==",
"0",
"# confirm the settings are sent to the panel",
"# pylint: disable=no-member",
"assert",
"mock_panel",
".",
"put_settings",
".",
"call_args_list",
"[",
"0",
"]",
"[",
"1",
"]",
"==",
"{",
"\"sensors\"",
":",
"[",
"{",
"\"pin\"",
":",
"\"1\"",
"}",
",",
"{",
"\"pin\"",
":",
"\"2\"",
"}",
",",
"{",
"\"pin\"",
":",
"\"5\"",
"}",
"]",
",",
"\"actuators\"",
":",
"[",
"{",
"\"trigger\"",
":",
"0",
",",
"\"pin\"",
":",
"\"8\"",
"}",
",",
"{",
"\"trigger\"",
":",
"1",
",",
"\"pin\"",
":",
"\"9\"",
"}",
"]",
",",
"\"dht_sensors\"",
":",
"[",
"{",
"\"poll_interval\"",
":",
"3",
",",
"\"pin\"",
":",
"\"6\"",
"}",
"]",
",",
"\"ds18b20_sensors\"",
":",
"[",
"{",
"\"pin\"",
":",
"\"7\"",
"}",
"]",
",",
"\"auth_token\"",
":",
"\"11223344556677889900\"",
",",
"\"blink\"",
":",
"True",
",",
"\"discovery\"",
":",
"True",
",",
"\"endpoint\"",
":",
"\"http://192.168.1.1:8123/api/konnected\"",
",",
"}",
"# confirm the device settings are saved in hass.data",
"assert",
"device",
".",
"stored_configuration",
"==",
"{",
"\"binary_sensors\"",
":",
"{",
"\"1\"",
":",
"{",
"\"inverse\"",
":",
"False",
",",
"\"name\"",
":",
"\"Konnected 445566 Zone 1\"",
",",
"\"state\"",
":",
"None",
",",
"\"type\"",
":",
"\"door\"",
",",
"}",
",",
"\"2\"",
":",
"{",
"\"inverse\"",
":",
"True",
",",
"\"name\"",
":",
"\"winder\"",
",",
"\"state\"",
":",
"None",
",",
"\"type\"",
":",
"\"window\"",
"}",
",",
"\"3\"",
":",
"{",
"\"inverse\"",
":",
"False",
",",
"\"name\"",
":",
"\"Konnected 445566 Zone 3\"",
",",
"\"state\"",
":",
"None",
",",
"\"type\"",
":",
"\"door\"",
",",
"}",
",",
"}",
",",
"\"blink\"",
":",
"True",
",",
"\"panel\"",
":",
"device",
",",
"\"discovery\"",
":",
"True",
",",
"\"host\"",
":",
"\"1.2.3.4\"",
",",
"\"port\"",
":",
"1234",
",",
"\"sensors\"",
":",
"[",
"{",
"\"name\"",
":",
"\"Konnected 445566 Sensor 4\"",
",",
"\"poll_interval\"",
":",
"3",
",",
"\"type\"",
":",
"\"dht\"",
",",
"\"zone\"",
":",
"\"4\"",
",",
"}",
",",
"{",
"\"name\"",
":",
"\"temper\"",
",",
"\"poll_interval\"",
":",
"3",
",",
"\"type\"",
":",
"\"ds18b20\"",
",",
"\"zone\"",
":",
"\"5\"",
"}",
",",
"]",
",",
"\"switches\"",
":",
"[",
"{",
"\"activation\"",
":",
"\"low\"",
",",
"\"momentary\"",
":",
"50",
",",
"\"name\"",
":",
"\"switcher\"",
",",
"\"pause\"",
":",
"100",
",",
"\"repeat\"",
":",
"4",
",",
"\"state\"",
":",
"None",
",",
"\"zone\"",
":",
"\"out\"",
",",
"}",
",",
"{",
"\"activation\"",
":",
"\"high\"",
",",
"\"momentary\"",
":",
"None",
",",
"\"name\"",
":",
"\"Konnected 445566 Actuator 6\"",
",",
"\"pause\"",
":",
"None",
",",
"\"repeat\"",
":",
"None",
",",
"\"state\"",
":",
"None",
",",
"\"zone\"",
":",
"\"6\"",
",",
"}",
",",
"]",
",",
"}"
] | [
389,
0
] | [
552,
5
] | python | en | ['en', 'en', 'en'] | True |
test_connect_retry | (hass, mock_panel) | Test that we create a Konnected Panel and save the data. | Test that we create a Konnected Panel and save the data. | async def test_connect_retry(hass, mock_panel):
"""Test that we create a Konnected Panel and save the data."""
device_config = config_flow.CONFIG_ENTRY_SCHEMA(
{
"host": "1.2.3.4",
"port": 1234,
"id": "112233445566",
"model": "Konnected Pro",
"access_token": "11223344556677889900",
"default_options": config_flow.OPTIONS_SCHEMA(
{
"io": {
"1": "Binary Sensor",
"2": "Binary Sensor",
"3": "Binary Sensor",
"4": "Digital Sensor",
"5": "Digital Sensor",
"6": "Switchable Output",
"out": "Switchable Output",
},
"binary_sensors": [
{"zone": "1", "type": "door"},
{
"zone": "2",
"type": "window",
"name": "winder",
"inverse": True,
},
{"zone": "3", "type": "door"},
],
"sensors": [
{"zone": "4", "type": "dht"},
{"zone": "5", "type": "ds18b20", "name": "temper"},
],
"switches": [
{
"zone": "out",
"name": "switcher",
"activation": "low",
"momentary": 50,
"pause": 100,
"repeat": 4,
},
{"zone": "6"},
],
}
),
}
)
entry = MockConfigEntry(
domain="konnected",
title="Konnected Alarm Panel",
data=device_config,
options={},
)
entry.add_to_hass(hass)
# fail first 2 attempts, and succeed the third
mock_panel.get_status.side_effect = [
mock_panel.ClientError,
mock_panel.ClientError,
{
"hwVersion": "2.3.0",
"swVersion": "2.3.1",
"heap": 10000,
"uptime": 12222,
"ip": "192.168.1.90",
"port": 9123,
"sensors": [],
"actuators": [],
"dht_sensors": [],
"ds18b20_sensors": [],
"mac": "11:22:33:44:55:66",
"model": "Konnected Pro",
"settings": {},
},
]
# setup the integration and inspect panel behavior
assert (
await async_setup_component(
hass,
panel.DOMAIN,
{
panel.DOMAIN: {
panel.CONF_ACCESS_TOKEN: "arandomstringvalue",
panel.CONF_API_HOST: "http://192.168.1.1:8123",
}
},
)
is True
)
# confirm switch is unavailable after initial attempt
await hass.async_block_till_done()
assert hass.states.get("switch.konnected_445566_actuator_6").state == "unavailable"
# confirm switch is unavailable after second attempt
async_fire_time_changed(hass, utcnow() + timedelta(seconds=11))
await hass.async_block_till_done()
await hass.helpers.entity_component.async_update_entity(
"switch.konnected_445566_actuator_6"
)
assert hass.states.get("switch.konnected_445566_actuator_6").state == "unavailable"
# confirm switch is available after third attempt
async_fire_time_changed(hass, utcnow() + timedelta(seconds=21))
await hass.async_block_till_done()
await hass.helpers.entity_component.async_update_entity(
"switch.konnected_445566_actuator_6"
)
assert hass.states.get("switch.konnected_445566_actuator_6").state == "off" | [
"async",
"def",
"test_connect_retry",
"(",
"hass",
",",
"mock_panel",
")",
":",
"device_config",
"=",
"config_flow",
".",
"CONFIG_ENTRY_SCHEMA",
"(",
"{",
"\"host\"",
":",
"\"1.2.3.4\"",
",",
"\"port\"",
":",
"1234",
",",
"\"id\"",
":",
"\"112233445566\"",
",",
"\"model\"",
":",
"\"Konnected Pro\"",
",",
"\"access_token\"",
":",
"\"11223344556677889900\"",
",",
"\"default_options\"",
":",
"config_flow",
".",
"OPTIONS_SCHEMA",
"(",
"{",
"\"io\"",
":",
"{",
"\"1\"",
":",
"\"Binary Sensor\"",
",",
"\"2\"",
":",
"\"Binary Sensor\"",
",",
"\"3\"",
":",
"\"Binary Sensor\"",
",",
"\"4\"",
":",
"\"Digital Sensor\"",
",",
"\"5\"",
":",
"\"Digital Sensor\"",
",",
"\"6\"",
":",
"\"Switchable Output\"",
",",
"\"out\"",
":",
"\"Switchable Output\"",
",",
"}",
",",
"\"binary_sensors\"",
":",
"[",
"{",
"\"zone\"",
":",
"\"1\"",
",",
"\"type\"",
":",
"\"door\"",
"}",
",",
"{",
"\"zone\"",
":",
"\"2\"",
",",
"\"type\"",
":",
"\"window\"",
",",
"\"name\"",
":",
"\"winder\"",
",",
"\"inverse\"",
":",
"True",
",",
"}",
",",
"{",
"\"zone\"",
":",
"\"3\"",
",",
"\"type\"",
":",
"\"door\"",
"}",
",",
"]",
",",
"\"sensors\"",
":",
"[",
"{",
"\"zone\"",
":",
"\"4\"",
",",
"\"type\"",
":",
"\"dht\"",
"}",
",",
"{",
"\"zone\"",
":",
"\"5\"",
",",
"\"type\"",
":",
"\"ds18b20\"",
",",
"\"name\"",
":",
"\"temper\"",
"}",
",",
"]",
",",
"\"switches\"",
":",
"[",
"{",
"\"zone\"",
":",
"\"out\"",
",",
"\"name\"",
":",
"\"switcher\"",
",",
"\"activation\"",
":",
"\"low\"",
",",
"\"momentary\"",
":",
"50",
",",
"\"pause\"",
":",
"100",
",",
"\"repeat\"",
":",
"4",
",",
"}",
",",
"{",
"\"zone\"",
":",
"\"6\"",
"}",
",",
"]",
",",
"}",
")",
",",
"}",
")",
"entry",
"=",
"MockConfigEntry",
"(",
"domain",
"=",
"\"konnected\"",
",",
"title",
"=",
"\"Konnected Alarm Panel\"",
",",
"data",
"=",
"device_config",
",",
"options",
"=",
"{",
"}",
",",
")",
"entry",
".",
"add_to_hass",
"(",
"hass",
")",
"# fail first 2 attempts, and succeed the third",
"mock_panel",
".",
"get_status",
".",
"side_effect",
"=",
"[",
"mock_panel",
".",
"ClientError",
",",
"mock_panel",
".",
"ClientError",
",",
"{",
"\"hwVersion\"",
":",
"\"2.3.0\"",
",",
"\"swVersion\"",
":",
"\"2.3.1\"",
",",
"\"heap\"",
":",
"10000",
",",
"\"uptime\"",
":",
"12222",
",",
"\"ip\"",
":",
"\"192.168.1.90\"",
",",
"\"port\"",
":",
"9123",
",",
"\"sensors\"",
":",
"[",
"]",
",",
"\"actuators\"",
":",
"[",
"]",
",",
"\"dht_sensors\"",
":",
"[",
"]",
",",
"\"ds18b20_sensors\"",
":",
"[",
"]",
",",
"\"mac\"",
":",
"\"11:22:33:44:55:66\"",
",",
"\"model\"",
":",
"\"Konnected Pro\"",
",",
"\"settings\"",
":",
"{",
"}",
",",
"}",
",",
"]",
"# setup the integration and inspect panel behavior",
"assert",
"(",
"await",
"async_setup_component",
"(",
"hass",
",",
"panel",
".",
"DOMAIN",
",",
"{",
"panel",
".",
"DOMAIN",
":",
"{",
"panel",
".",
"CONF_ACCESS_TOKEN",
":",
"\"arandomstringvalue\"",
",",
"panel",
".",
"CONF_API_HOST",
":",
"\"http://192.168.1.1:8123\"",
",",
"}",
"}",
",",
")",
"is",
"True",
")",
"# confirm switch is unavailable after initial attempt",
"await",
"hass",
".",
"async_block_till_done",
"(",
")",
"assert",
"hass",
".",
"states",
".",
"get",
"(",
"\"switch.konnected_445566_actuator_6\"",
")",
".",
"state",
"==",
"\"unavailable\"",
"# confirm switch is unavailable after second attempt",
"async_fire_time_changed",
"(",
"hass",
",",
"utcnow",
"(",
")",
"+",
"timedelta",
"(",
"seconds",
"=",
"11",
")",
")",
"await",
"hass",
".",
"async_block_till_done",
"(",
")",
"await",
"hass",
".",
"helpers",
".",
"entity_component",
".",
"async_update_entity",
"(",
"\"switch.konnected_445566_actuator_6\"",
")",
"assert",
"hass",
".",
"states",
".",
"get",
"(",
"\"switch.konnected_445566_actuator_6\"",
")",
".",
"state",
"==",
"\"unavailable\"",
"# confirm switch is available after third attempt",
"async_fire_time_changed",
"(",
"hass",
",",
"utcnow",
"(",
")",
"+",
"timedelta",
"(",
"seconds",
"=",
"21",
")",
")",
"await",
"hass",
".",
"async_block_till_done",
"(",
")",
"await",
"hass",
".",
"helpers",
".",
"entity_component",
".",
"async_update_entity",
"(",
"\"switch.konnected_445566_actuator_6\"",
")",
"assert",
"hass",
".",
"states",
".",
"get",
"(",
"\"switch.konnected_445566_actuator_6\"",
")",
".",
"state",
"==",
"\"off\""
] | [
555,
0
] | [
667,
79
] | python | en | ['en', 'en', 'en'] | True |
load_vocab | (vocab_file) | Loads a vocabulary file into a dictionary. | Loads a vocabulary file into a dictionary. | def load_vocab(vocab_file):
"""Loads a vocabulary file into a dictionary."""
vocab = collections.OrderedDict()
with open(vocab_file, "r", encoding="utf-8") as reader:
tokens = reader.readlines()
for index, token in enumerate(tokens):
token = token.rstrip("\n")
vocab[token] = index
return vocab | [
"def",
"load_vocab",
"(",
"vocab_file",
")",
":",
"vocab",
"=",
"collections",
".",
"OrderedDict",
"(",
")",
"with",
"open",
"(",
"vocab_file",
",",
"\"r\"",
",",
"encoding",
"=",
"\"utf-8\"",
")",
"as",
"reader",
":",
"tokens",
"=",
"reader",
".",
"readlines",
"(",
")",
"for",
"index",
",",
"token",
"in",
"enumerate",
"(",
"tokens",
")",
":",
"token",
"=",
"token",
".",
"rstrip",
"(",
"\"\\n\"",
")",
"vocab",
"[",
"token",
"]",
"=",
"index",
"return",
"vocab"
] | [
43,
0
] | [
51,
16
] | python | en | ['en', 'en', 'en'] | True |
ProphetNetTokenizer._convert_token_to_id | (self, token) | Converts a token (str) in an id using the vocab. | Converts a token (str) in an id using the vocab. | def _convert_token_to_id(self, token):
""" Converts a token (str) in an id using the vocab. """
return self.vocab.get(token, self.vocab.get(self.unk_token)) | [
"def",
"_convert_token_to_id",
"(",
"self",
",",
"token",
")",
":",
"return",
"self",
".",
"vocab",
".",
"get",
"(",
"token",
",",
"self",
".",
"vocab",
".",
"get",
"(",
"self",
".",
"unk_token",
")",
")"
] | [
173,
4
] | [
175,
68
] | python | en | ['en', 'en', 'en'] | True |
ProphetNetTokenizer._convert_id_to_token | (self, index) | Converts an index (integer) in a token (str) using the vocab. | Converts an index (integer) in a token (str) using the vocab. | def _convert_id_to_token(self, index):
"""Converts an index (integer) in a token (str) using the vocab."""
return self.ids_to_tokens.get(index, self.unk_token) | [
"def",
"_convert_id_to_token",
"(",
"self",
",",
"index",
")",
":",
"return",
"self",
".",
"ids_to_tokens",
".",
"get",
"(",
"index",
",",
"self",
".",
"unk_token",
")"
] | [
177,
4
] | [
179,
60
] | python | en | ['en', 'en', 'en'] | True |
ProphetNetTokenizer.convert_tokens_to_string | (self, tokens) | Converts a sequence of tokens (string) in a single string. | Converts a sequence of tokens (string) in a single string. | def convert_tokens_to_string(self, tokens):
""" Converts a sequence of tokens (string) in a single string. """
out_string = " ".join(tokens).replace(" ##", "").strip()
return out_string | [
"def",
"convert_tokens_to_string",
"(",
"self",
",",
"tokens",
")",
":",
"out_string",
"=",
"\" \"",
".",
"join",
"(",
"tokens",
")",
".",
"replace",
"(",
"\" ##\"",
",",
"\"\"",
")",
".",
"strip",
"(",
")",
"return",
"out_string"
] | [
181,
4
] | [
184,
25
] | python | en | ['en', 'en', 'en'] | True |
ProphetNetTokenizer.get_special_tokens_mask | (
self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None, already_has_special_tokens: bool = False
) |
Retrieve sequence ids from a token list that has no special tokens added. This method is called when adding
special tokens using the tokenizer ``prepare_for_model`` method.
Args:
token_ids_0 (:obj:`List[int]`):
List of IDs.
token_ids_1 (:obj:`List[int]`, `optional`):
Optional second list of IDs for sequence pairs.
already_has_special_tokens (:obj:`bool`, `optional`, defaults to :obj:`False`):
Whether or not the token list is already formatted with special tokens for the model.
Returns:
:obj:`List[int]`: A list of integers in the range [0, 1]: 1 for a special token, 0 for a sequence token.
|
Retrieve sequence ids from a token list that has no special tokens added. This method is called when adding
special tokens using the tokenizer ``prepare_for_model`` method. | def get_special_tokens_mask(
self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None, already_has_special_tokens: bool = False
) -> List[int]:
"""
Retrieve sequence ids from a token list that has no special tokens added. This method is called when adding
special tokens using the tokenizer ``prepare_for_model`` method.
Args:
token_ids_0 (:obj:`List[int]`):
List of IDs.
token_ids_1 (:obj:`List[int]`, `optional`):
Optional second list of IDs for sequence pairs.
already_has_special_tokens (:obj:`bool`, `optional`, defaults to :obj:`False`):
Whether or not the token list is already formatted with special tokens for the model.
Returns:
:obj:`List[int]`: A list of integers in the range [0, 1]: 1 for a special token, 0 for a sequence token.
"""
if already_has_special_tokens:
if token_ids_1 is not None:
raise ValueError(
"You should not supply a second sequence if the provided sequence of "
"ids is already formatted with special tokens for the model."
)
return list(map(lambda x: 1 if x in [self.sep_token_id, self.cls_token_id] else 0, token_ids_0))
if token_ids_1 is None:
return ([0] * len(token_ids_0)) + [1]
return ([0] * len(token_ids_0)) + [1] + ([0] * len(token_ids_1)) + [1] | [
"def",
"get_special_tokens_mask",
"(",
"self",
",",
"token_ids_0",
":",
"List",
"[",
"int",
"]",
",",
"token_ids_1",
":",
"Optional",
"[",
"List",
"[",
"int",
"]",
"]",
"=",
"None",
",",
"already_has_special_tokens",
":",
"bool",
"=",
"False",
")",
"->",
"List",
"[",
"int",
"]",
":",
"if",
"already_has_special_tokens",
":",
"if",
"token_ids_1",
"is",
"not",
"None",
":",
"raise",
"ValueError",
"(",
"\"You should not supply a second sequence if the provided sequence of \"",
"\"ids is already formatted with special tokens for the model.\"",
")",
"return",
"list",
"(",
"map",
"(",
"lambda",
"x",
":",
"1",
"if",
"x",
"in",
"[",
"self",
".",
"sep_token_id",
",",
"self",
".",
"cls_token_id",
"]",
"else",
"0",
",",
"token_ids_0",
")",
")",
"if",
"token_ids_1",
"is",
"None",
":",
"return",
"(",
"[",
"0",
"]",
"*",
"len",
"(",
"token_ids_0",
")",
")",
"+",
"[",
"1",
"]",
"return",
"(",
"[",
"0",
"]",
"*",
"len",
"(",
"token_ids_0",
")",
")",
"+",
"[",
"1",
"]",
"+",
"(",
"[",
"0",
"]",
"*",
"len",
"(",
"token_ids_1",
")",
")",
"+",
"[",
"1",
"]"
] | [
186,
4
] | [
214,
78
] | python | en | ['en', 'error', 'th'] | False |
ProphetNetTokenizer.create_token_type_ids_from_sequences | (
self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
) |
Create a mask from the two sequences passed to be used in a sequence-pair classification task. A ProphetNet
sequence pair mask has the following format:
::
0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1
| first sequence | second sequence |
If :obj:`token_ids_1` is :obj:`None`, this method only returns the first portion of the mask (0s).
Args:
token_ids_0 (:obj:`List[int]`):
List of IDs.
token_ids_1 (:obj:`List[int]`, `optional`):
Optional second list of IDs for sequence pairs.
Returns:
:obj:`List[int]`: List of `token type IDs <../glossary.html#token-type-ids>`_ according to the given
sequence(s).
|
Create a mask from the two sequences passed to be used in a sequence-pair classification task. A ProphetNet
sequence pair mask has the following format: | def create_token_type_ids_from_sequences(
self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
) -> List[int]:
"""
Create a mask from the two sequences passed to be used in a sequence-pair classification task. A ProphetNet
sequence pair mask has the following format:
::
0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1
| first sequence | second sequence |
If :obj:`token_ids_1` is :obj:`None`, this method only returns the first portion of the mask (0s).
Args:
token_ids_0 (:obj:`List[int]`):
List of IDs.
token_ids_1 (:obj:`List[int]`, `optional`):
Optional second list of IDs for sequence pairs.
Returns:
:obj:`List[int]`: List of `token type IDs <../glossary.html#token-type-ids>`_ according to the given
sequence(s).
"""
sep = [self.sep_token_id]
if token_ids_1 is None:
return len(token_ids_0 + sep) * [0]
return len(token_ids_0 + sep) * [0] + len(token_ids_1 + sep) * [1] | [
"def",
"create_token_type_ids_from_sequences",
"(",
"self",
",",
"token_ids_0",
":",
"List",
"[",
"int",
"]",
",",
"token_ids_1",
":",
"Optional",
"[",
"List",
"[",
"int",
"]",
"]",
"=",
"None",
")",
"->",
"List",
"[",
"int",
"]",
":",
"sep",
"=",
"[",
"self",
".",
"sep_token_id",
"]",
"if",
"token_ids_1",
"is",
"None",
":",
"return",
"len",
"(",
"token_ids_0",
"+",
"sep",
")",
"*",
"[",
"0",
"]",
"return",
"len",
"(",
"token_ids_0",
"+",
"sep",
")",
"*",
"[",
"0",
"]",
"+",
"len",
"(",
"token_ids_1",
"+",
"sep",
")",
"*",
"[",
"1",
"]"
] | [
216,
4
] | [
243,
74
] | python | en | ['en', 'error', 'th'] | False |
ProphetNetTokenizer.build_inputs_with_special_tokens | (
self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
) |
Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and
adding special tokens. A BERT sequence has the following format:
- single sequence: ``[CLS] X [SEP]``
- pair of sequences: ``[CLS] A [SEP] B [SEP]``
Args:
token_ids_0 (:obj:`List[int]`):
List of IDs to which the special tokens will be added.
token_ids_1 (:obj:`List[int]`, `optional`):
Optional second list of IDs for sequence pairs.
Returns:
:obj:`List[int]`: List of `input IDs <../glossary.html#input-ids>`__ with the appropriate special tokens.
|
Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and
adding special tokens. A BERT sequence has the following format: | def build_inputs_with_special_tokens(
self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
) -> List[int]:
"""
Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and
adding special tokens. A BERT sequence has the following format:
- single sequence: ``[CLS] X [SEP]``
- pair of sequences: ``[CLS] A [SEP] B [SEP]``
Args:
token_ids_0 (:obj:`List[int]`):
List of IDs to which the special tokens will be added.
token_ids_1 (:obj:`List[int]`, `optional`):
Optional second list of IDs for sequence pairs.
Returns:
:obj:`List[int]`: List of `input IDs <../glossary.html#input-ids>`__ with the appropriate special tokens.
"""
if token_ids_1 is None:
return token_ids_0 + [self.sep_token_id]
sep = [self.sep_token_id]
return token_ids_0 + sep + token_ids_1 + sep | [
"def",
"build_inputs_with_special_tokens",
"(",
"self",
",",
"token_ids_0",
":",
"List",
"[",
"int",
"]",
",",
"token_ids_1",
":",
"Optional",
"[",
"List",
"[",
"int",
"]",
"]",
"=",
"None",
")",
"->",
"List",
"[",
"int",
"]",
":",
"if",
"token_ids_1",
"is",
"None",
":",
"return",
"token_ids_0",
"+",
"[",
"self",
".",
"sep_token_id",
"]",
"sep",
"=",
"[",
"self",
".",
"sep_token_id",
"]",
"return",
"token_ids_0",
"+",
"sep",
"+",
"token_ids_1",
"+",
"sep"
] | [
265,
4
] | [
287,
52
] | python | en | ['en', 'error', 'th'] | False |
async_setup_platform | (hass, config, async_add_entities, discovery_info=None) | Find and return battery. | Find and return battery. | async def async_setup_platform(hass, config, async_add_entities, discovery_info=None):
"""Find and return battery."""
if discovery_info is None:
return
batteries = []
lwlink = hass.data[LIGHTWAVE_LINK]
for device_config in discovery_info.values():
name = device_config[CONF_NAME]
serial = device_config[CONF_SERIAL]
batteries.append(LightwaveBattery(name, lwlink, serial))
async_add_entities(batteries) | [
"async",
"def",
"async_setup_platform",
"(",
"hass",
",",
"config",
",",
"async_add_entities",
",",
"discovery_info",
"=",
"None",
")",
":",
"if",
"discovery_info",
"is",
"None",
":",
"return",
"batteries",
"=",
"[",
"]",
"lwlink",
"=",
"hass",
".",
"data",
"[",
"LIGHTWAVE_LINK",
"]",
"for",
"device_config",
"in",
"discovery_info",
".",
"values",
"(",
")",
":",
"name",
"=",
"device_config",
"[",
"CONF_NAME",
"]",
"serial",
"=",
"device_config",
"[",
"CONF_SERIAL",
"]",
"batteries",
".",
"append",
"(",
"LightwaveBattery",
"(",
"name",
",",
"lwlink",
",",
"serial",
")",
")",
"async_add_entities",
"(",
"batteries",
")"
] | [
7,
0
] | [
21,
33
] | python | en | ['en', 'en', 'en'] | True |
LightwaveBattery.__init__ | (self, name, lwlink, serial) | Initialize the Lightwave Trv battery sensor. | Initialize the Lightwave Trv battery sensor. | def __init__(self, name, lwlink, serial):
"""Initialize the Lightwave Trv battery sensor."""
self._name = name
self._state = None
self._lwlink = lwlink
self._serial = serial | [
"def",
"__init__",
"(",
"self",
",",
"name",
",",
"lwlink",
",",
"serial",
")",
":",
"self",
".",
"_name",
"=",
"name",
"self",
".",
"_state",
"=",
"None",
"self",
".",
"_lwlink",
"=",
"lwlink",
"self",
".",
"_serial",
"=",
"serial"
] | [
27,
4
] | [
32,
29
] | python | en | ['en', 'da', 'en'] | True |
LightwaveBattery.device_class | (self) | Return the device class of the sensor. | Return the device class of the sensor. | def device_class(self):
"""Return the device class of the sensor."""
return DEVICE_CLASS_BATTERY | [
"def",
"device_class",
"(",
"self",
")",
":",
"return",
"DEVICE_CLASS_BATTERY"
] | [
35,
4
] | [
37,
35
] | python | en | ['en', 'en', 'en'] | True |
LightwaveBattery.name | (self) | Return the name of the sensor. | Return the name of the sensor. | def name(self):
"""Return the name of the sensor."""
return self._name | [
"def",
"name",
"(",
"self",
")",
":",
"return",
"self",
".",
"_name"
] | [
40,
4
] | [
42,
25
] | python | en | ['en', 'mi', 'en'] | True |
LightwaveBattery.state | (self) | Return the state of the sensor. | Return the state of the sensor. | def state(self):
"""Return the state of the sensor."""
return self._state | [
"def",
"state",
"(",
"self",
")",
":",
"return",
"self",
".",
"_state"
] | [
45,
4
] | [
47,
26
] | python | en | ['en', 'en', 'en'] | True |
LightwaveBattery.unit_of_measurement | (self) | Return the state of the sensor. | Return the state of the sensor. | def unit_of_measurement(self):
"""Return the state of the sensor."""
return PERCENTAGE | [
"def",
"unit_of_measurement",
"(",
"self",
")",
":",
"return",
"PERCENTAGE"
] | [
50,
4
] | [
52,
25
] | python | en | ['en', 'en', 'en'] | True |
LightwaveBattery.update | (self) | Communicate with a Lightwave RTF Proxy to get state. | Communicate with a Lightwave RTF Proxy to get state. | def update(self):
"""Communicate with a Lightwave RTF Proxy to get state."""
(dummy_temp, dummy_targ, battery, dummy_output) = self._lwlink.read_trv_status(
self._serial
)
self._state = battery | [
"def",
"update",
"(",
"self",
")",
":",
"(",
"dummy_temp",
",",
"dummy_targ",
",",
"battery",
",",
"dummy_output",
")",
"=",
"self",
".",
"_lwlink",
".",
"read_trv_status",
"(",
"self",
".",
"_serial",
")",
"self",
".",
"_state",
"=",
"battery"
] | [
54,
4
] | [
59,
29
] | python | en | ['en', 'en', 'en'] | True |
mock_all | (aioclient_mock) | Mock all setup requests. | Mock all setup requests. | def mock_all(aioclient_mock):
"""Mock all setup requests."""
aioclient_mock.post("http://127.0.0.1/homeassistant/options", json={"result": "ok"})
aioclient_mock.get("http://127.0.0.1/supervisor/ping", json={"result": "ok"})
aioclient_mock.post("http://127.0.0.1/supervisor/options", json={"result": "ok"})
aioclient_mock.get(
"http://127.0.0.1/info",
json={
"result": "ok",
"data": {"supervisor": "222", "homeassistant": "0.110.0", "hassos": None},
},
)
aioclient_mock.get(
"http://127.0.0.1/host/info",
json={
"result": "ok",
"data": {
"result": "ok",
"data": {
"chassis": "vm",
"operating_system": "Debian GNU/Linux 10 (buster)",
"kernel": "4.19.0-6-amd64",
},
},
},
)
aioclient_mock.get(
"http://127.0.0.1/core/info",
json={"result": "ok", "data": {"version_latest": "1.0.0"}},
)
aioclient_mock.get(
"http://127.0.0.1/os/info",
json={"result": "ok", "data": {"version_latest": "1.0.0"}},
)
aioclient_mock.get(
"http://127.0.0.1/supervisor/info",
json={"result": "ok", "data": {"version_latest": "1.0.0"}},
)
aioclient_mock.get(
"http://127.0.0.1/ingress/panels", json={"result": "ok", "data": {"panels": {}}}
) | [
"def",
"mock_all",
"(",
"aioclient_mock",
")",
":",
"aioclient_mock",
".",
"post",
"(",
"\"http://127.0.0.1/homeassistant/options\"",
",",
"json",
"=",
"{",
"\"result\"",
":",
"\"ok\"",
"}",
")",
"aioclient_mock",
".",
"get",
"(",
"\"http://127.0.0.1/supervisor/ping\"",
",",
"json",
"=",
"{",
"\"result\"",
":",
"\"ok\"",
"}",
")",
"aioclient_mock",
".",
"post",
"(",
"\"http://127.0.0.1/supervisor/options\"",
",",
"json",
"=",
"{",
"\"result\"",
":",
"\"ok\"",
"}",
")",
"aioclient_mock",
".",
"get",
"(",
"\"http://127.0.0.1/info\"",
",",
"json",
"=",
"{",
"\"result\"",
":",
"\"ok\"",
",",
"\"data\"",
":",
"{",
"\"supervisor\"",
":",
"\"222\"",
",",
"\"homeassistant\"",
":",
"\"0.110.0\"",
",",
"\"hassos\"",
":",
"None",
"}",
",",
"}",
",",
")",
"aioclient_mock",
".",
"get",
"(",
"\"http://127.0.0.1/host/info\"",
",",
"json",
"=",
"{",
"\"result\"",
":",
"\"ok\"",
",",
"\"data\"",
":",
"{",
"\"result\"",
":",
"\"ok\"",
",",
"\"data\"",
":",
"{",
"\"chassis\"",
":",
"\"vm\"",
",",
"\"operating_system\"",
":",
"\"Debian GNU/Linux 10 (buster)\"",
",",
"\"kernel\"",
":",
"\"4.19.0-6-amd64\"",
",",
"}",
",",
"}",
",",
"}",
",",
")",
"aioclient_mock",
".",
"get",
"(",
"\"http://127.0.0.1/core/info\"",
",",
"json",
"=",
"{",
"\"result\"",
":",
"\"ok\"",
",",
"\"data\"",
":",
"{",
"\"version_latest\"",
":",
"\"1.0.0\"",
"}",
"}",
",",
")",
"aioclient_mock",
".",
"get",
"(",
"\"http://127.0.0.1/os/info\"",
",",
"json",
"=",
"{",
"\"result\"",
":",
"\"ok\"",
",",
"\"data\"",
":",
"{",
"\"version_latest\"",
":",
"\"1.0.0\"",
"}",
"}",
",",
")",
"aioclient_mock",
".",
"get",
"(",
"\"http://127.0.0.1/supervisor/info\"",
",",
"json",
"=",
"{",
"\"result\"",
":",
"\"ok\"",
",",
"\"data\"",
":",
"{",
"\"version_latest\"",
":",
"\"1.0.0\"",
"}",
"}",
",",
")",
"aioclient_mock",
".",
"get",
"(",
"\"http://127.0.0.1/ingress/panels\"",
",",
"json",
"=",
"{",
"\"result\"",
":",
"\"ok\"",
",",
"\"data\"",
":",
"{",
"\"panels\"",
":",
"{",
"}",
"}",
"}",
")"
] | [
16,
0
] | [
56,
5
] | python | en | ['en', 'bg', 'en'] | True |
test_setup_api_ping | (hass, aioclient_mock) | Test setup with API ping. | Test setup with API ping. | async def test_setup_api_ping(hass, aioclient_mock):
"""Test setup with API ping."""
with patch.dict(os.environ, MOCK_ENVIRON):
result = await async_setup_component(hass, "hassio", {})
assert result
assert aioclient_mock.call_count == 9
assert hass.components.hassio.get_core_info()["version_latest"] == "1.0.0"
assert hass.components.hassio.is_hassio() | [
"async",
"def",
"test_setup_api_ping",
"(",
"hass",
",",
"aioclient_mock",
")",
":",
"with",
"patch",
".",
"dict",
"(",
"os",
".",
"environ",
",",
"MOCK_ENVIRON",
")",
":",
"result",
"=",
"await",
"async_setup_component",
"(",
"hass",
",",
"\"hassio\"",
",",
"{",
"}",
")",
"assert",
"result",
"assert",
"aioclient_mock",
".",
"call_count",
"==",
"9",
"assert",
"hass",
".",
"components",
".",
"hassio",
".",
"get_core_info",
"(",
")",
"[",
"\"version_latest\"",
"]",
"==",
"\"1.0.0\"",
"assert",
"hass",
".",
"components",
".",
"hassio",
".",
"is_hassio",
"(",
")"
] | [
59,
0
] | [
67,
45
] | python | en | ['en', 'ceb', 'en'] | True |
test_setup_api_panel | (hass, aioclient_mock) | Test setup with API ping. | Test setup with API ping. | async def test_setup_api_panel(hass, aioclient_mock):
"""Test setup with API ping."""
assert await async_setup_component(hass, "frontend", {})
with patch.dict(os.environ, MOCK_ENVIRON):
result = await async_setup_component(hass, "hassio", {})
assert result
panels = hass.data[frontend.DATA_PANELS]
assert panels.get("hassio").to_response() == {
"component_name": "custom",
"icon": "hass:home-assistant",
"title": "Supervisor",
"url_path": "hassio",
"require_admin": True,
"config": {
"_panel_custom": {
"embed_iframe": True,
"js_url": "/api/hassio/app/entrypoint.js",
"name": "hassio-main",
"trust_external": False,
}
},
} | [
"async",
"def",
"test_setup_api_panel",
"(",
"hass",
",",
"aioclient_mock",
")",
":",
"assert",
"await",
"async_setup_component",
"(",
"hass",
",",
"\"frontend\"",
",",
"{",
"}",
")",
"with",
"patch",
".",
"dict",
"(",
"os",
".",
"environ",
",",
"MOCK_ENVIRON",
")",
":",
"result",
"=",
"await",
"async_setup_component",
"(",
"hass",
",",
"\"hassio\"",
",",
"{",
"}",
")",
"assert",
"result",
"panels",
"=",
"hass",
".",
"data",
"[",
"frontend",
".",
"DATA_PANELS",
"]",
"assert",
"panels",
".",
"get",
"(",
"\"hassio\"",
")",
".",
"to_response",
"(",
")",
"==",
"{",
"\"component_name\"",
":",
"\"custom\"",
",",
"\"icon\"",
":",
"\"hass:home-assistant\"",
",",
"\"title\"",
":",
"\"Supervisor\"",
",",
"\"url_path\"",
":",
"\"hassio\"",
",",
"\"require_admin\"",
":",
"True",
",",
"\"config\"",
":",
"{",
"\"_panel_custom\"",
":",
"{",
"\"embed_iframe\"",
":",
"True",
",",
"\"js_url\"",
":",
"\"/api/hassio/app/entrypoint.js\"",
",",
"\"name\"",
":",
"\"hassio-main\"",
",",
"\"trust_external\"",
":",
"False",
",",
"}",
"}",
",",
"}"
] | [
70,
0
] | [
93,
5
] | python | en | ['en', 'ceb', 'en'] | True |
test_setup_api_push_api_data | (hass, aioclient_mock) | Test setup with API push. | Test setup with API push. | async def test_setup_api_push_api_data(hass, aioclient_mock):
"""Test setup with API push."""
with patch.dict(os.environ, MOCK_ENVIRON):
result = await async_setup_component(
hass, "hassio", {"http": {"server_port": 9999}, "hassio": {}}
)
assert result
assert aioclient_mock.call_count == 9
assert not aioclient_mock.mock_calls[1][2]["ssl"]
assert aioclient_mock.mock_calls[1][2]["port"] == 9999
assert aioclient_mock.mock_calls[1][2]["watchdog"] | [
"async",
"def",
"test_setup_api_push_api_data",
"(",
"hass",
",",
"aioclient_mock",
")",
":",
"with",
"patch",
".",
"dict",
"(",
"os",
".",
"environ",
",",
"MOCK_ENVIRON",
")",
":",
"result",
"=",
"await",
"async_setup_component",
"(",
"hass",
",",
"\"hassio\"",
",",
"{",
"\"http\"",
":",
"{",
"\"server_port\"",
":",
"9999",
"}",
",",
"\"hassio\"",
":",
"{",
"}",
"}",
")",
"assert",
"result",
"assert",
"aioclient_mock",
".",
"call_count",
"==",
"9",
"assert",
"not",
"aioclient_mock",
".",
"mock_calls",
"[",
"1",
"]",
"[",
"2",
"]",
"[",
"\"ssl\"",
"]",
"assert",
"aioclient_mock",
".",
"mock_calls",
"[",
"1",
"]",
"[",
"2",
"]",
"[",
"\"port\"",
"]",
"==",
"9999",
"assert",
"aioclient_mock",
".",
"mock_calls",
"[",
"1",
"]",
"[",
"2",
"]",
"[",
"\"watchdog\"",
"]"
] | [
96,
0
] | [
107,
54
] | python | en | ['en', 'zu', 'en'] | True |
test_setup_api_push_api_data_server_host | (hass, aioclient_mock) | Test setup with API push with active server host. | Test setup with API push with active server host. | async def test_setup_api_push_api_data_server_host(hass, aioclient_mock):
"""Test setup with API push with active server host."""
with patch.dict(os.environ, MOCK_ENVIRON):
result = await async_setup_component(
hass,
"hassio",
{"http": {"server_port": 9999, "server_host": "127.0.0.1"}, "hassio": {}},
)
assert result
assert aioclient_mock.call_count == 9
assert not aioclient_mock.mock_calls[1][2]["ssl"]
assert aioclient_mock.mock_calls[1][2]["port"] == 9999
assert not aioclient_mock.mock_calls[1][2]["watchdog"] | [
"async",
"def",
"test_setup_api_push_api_data_server_host",
"(",
"hass",
",",
"aioclient_mock",
")",
":",
"with",
"patch",
".",
"dict",
"(",
"os",
".",
"environ",
",",
"MOCK_ENVIRON",
")",
":",
"result",
"=",
"await",
"async_setup_component",
"(",
"hass",
",",
"\"hassio\"",
",",
"{",
"\"http\"",
":",
"{",
"\"server_port\"",
":",
"9999",
",",
"\"server_host\"",
":",
"\"127.0.0.1\"",
"}",
",",
"\"hassio\"",
":",
"{",
"}",
"}",
",",
")",
"assert",
"result",
"assert",
"aioclient_mock",
".",
"call_count",
"==",
"9",
"assert",
"not",
"aioclient_mock",
".",
"mock_calls",
"[",
"1",
"]",
"[",
"2",
"]",
"[",
"\"ssl\"",
"]",
"assert",
"aioclient_mock",
".",
"mock_calls",
"[",
"1",
"]",
"[",
"2",
"]",
"[",
"\"port\"",
"]",
"==",
"9999",
"assert",
"not",
"aioclient_mock",
".",
"mock_calls",
"[",
"1",
"]",
"[",
"2",
"]",
"[",
"\"watchdog\"",
"]"
] | [
110,
0
] | [
123,
58
] | python | en | ['en', 'en', 'en'] | True |
test_setup_api_push_api_data_default | (hass, aioclient_mock, hass_storage) | Test setup with API push default data. | Test setup with API push default data. | async def test_setup_api_push_api_data_default(hass, aioclient_mock, hass_storage):
"""Test setup with API push default data."""
with patch.dict(os.environ, MOCK_ENVIRON):
result = await async_setup_component(hass, "hassio", {"http": {}, "hassio": {}})
assert result
assert aioclient_mock.call_count == 9
assert not aioclient_mock.mock_calls[1][2]["ssl"]
assert aioclient_mock.mock_calls[1][2]["port"] == 8123
refresh_token = aioclient_mock.mock_calls[1][2]["refresh_token"]
hassio_user = await hass.auth.async_get_user(
hass_storage[STORAGE_KEY]["data"]["hassio_user"]
)
assert hassio_user is not None
assert hassio_user.system_generated
assert len(hassio_user.groups) == 1
assert hassio_user.groups[0].id == GROUP_ID_ADMIN
for token in hassio_user.refresh_tokens.values():
if token.token == refresh_token:
break
else:
assert False, "refresh token not found" | [
"async",
"def",
"test_setup_api_push_api_data_default",
"(",
"hass",
",",
"aioclient_mock",
",",
"hass_storage",
")",
":",
"with",
"patch",
".",
"dict",
"(",
"os",
".",
"environ",
",",
"MOCK_ENVIRON",
")",
":",
"result",
"=",
"await",
"async_setup_component",
"(",
"hass",
",",
"\"hassio\"",
",",
"{",
"\"http\"",
":",
"{",
"}",
",",
"\"hassio\"",
":",
"{",
"}",
"}",
")",
"assert",
"result",
"assert",
"aioclient_mock",
".",
"call_count",
"==",
"9",
"assert",
"not",
"aioclient_mock",
".",
"mock_calls",
"[",
"1",
"]",
"[",
"2",
"]",
"[",
"\"ssl\"",
"]",
"assert",
"aioclient_mock",
".",
"mock_calls",
"[",
"1",
"]",
"[",
"2",
"]",
"[",
"\"port\"",
"]",
"==",
"8123",
"refresh_token",
"=",
"aioclient_mock",
".",
"mock_calls",
"[",
"1",
"]",
"[",
"2",
"]",
"[",
"\"refresh_token\"",
"]",
"hassio_user",
"=",
"await",
"hass",
".",
"auth",
".",
"async_get_user",
"(",
"hass_storage",
"[",
"STORAGE_KEY",
"]",
"[",
"\"data\"",
"]",
"[",
"\"hassio_user\"",
"]",
")",
"assert",
"hassio_user",
"is",
"not",
"None",
"assert",
"hassio_user",
".",
"system_generated",
"assert",
"len",
"(",
"hassio_user",
".",
"groups",
")",
"==",
"1",
"assert",
"hassio_user",
".",
"groups",
"[",
"0",
"]",
".",
"id",
"==",
"GROUP_ID_ADMIN",
"for",
"token",
"in",
"hassio_user",
".",
"refresh_tokens",
".",
"values",
"(",
")",
":",
"if",
"token",
".",
"token",
"==",
"refresh_token",
":",
"break",
"else",
":",
"assert",
"False",
",",
"\"refresh token not found\""
] | [
126,
0
] | [
147,
47
] | python | en | ['en', 'hi-Latn', 'en'] | True |
test_setup_adds_admin_group_to_user | (hass, aioclient_mock, hass_storage) | Test setup with API push default data. | Test setup with API push default data. | async def test_setup_adds_admin_group_to_user(hass, aioclient_mock, hass_storage):
"""Test setup with API push default data."""
# Create user without admin
user = await hass.auth.async_create_system_user("Hass.io")
assert not user.is_admin
await hass.auth.async_create_refresh_token(user)
hass_storage[STORAGE_KEY] = {
"data": {"hassio_user": user.id},
"key": STORAGE_KEY,
"version": 1,
}
with patch.dict(os.environ, MOCK_ENVIRON):
result = await async_setup_component(hass, "hassio", {"http": {}, "hassio": {}})
assert result
assert user.is_admin | [
"async",
"def",
"test_setup_adds_admin_group_to_user",
"(",
"hass",
",",
"aioclient_mock",
",",
"hass_storage",
")",
":",
"# Create user without admin",
"user",
"=",
"await",
"hass",
".",
"auth",
".",
"async_create_system_user",
"(",
"\"Hass.io\"",
")",
"assert",
"not",
"user",
".",
"is_admin",
"await",
"hass",
".",
"auth",
".",
"async_create_refresh_token",
"(",
"user",
")",
"hass_storage",
"[",
"STORAGE_KEY",
"]",
"=",
"{",
"\"data\"",
":",
"{",
"\"hassio_user\"",
":",
"user",
".",
"id",
"}",
",",
"\"key\"",
":",
"STORAGE_KEY",
",",
"\"version\"",
":",
"1",
",",
"}",
"with",
"patch",
".",
"dict",
"(",
"os",
".",
"environ",
",",
"MOCK_ENVIRON",
")",
":",
"result",
"=",
"await",
"async_setup_component",
"(",
"hass",
",",
"\"hassio\"",
",",
"{",
"\"http\"",
":",
"{",
"}",
",",
"\"hassio\"",
":",
"{",
"}",
"}",
")",
"assert",
"result",
"assert",
"user",
".",
"is_admin"
] | [
150,
0
] | [
167,
24
] | python | en | ['en', 'hi-Latn', 'en'] | True |
test_setup_api_existing_hassio_user | (hass, aioclient_mock, hass_storage) | Test setup with API push default data. | Test setup with API push default data. | async def test_setup_api_existing_hassio_user(hass, aioclient_mock, hass_storage):
"""Test setup with API push default data."""
user = await hass.auth.async_create_system_user("Hass.io test")
token = await hass.auth.async_create_refresh_token(user)
hass_storage[STORAGE_KEY] = {"version": 1, "data": {"hassio_user": user.id}}
with patch.dict(os.environ, MOCK_ENVIRON):
result = await async_setup_component(hass, "hassio", {"http": {}, "hassio": {}})
assert result
assert aioclient_mock.call_count == 9
assert not aioclient_mock.mock_calls[1][2]["ssl"]
assert aioclient_mock.mock_calls[1][2]["port"] == 8123
assert aioclient_mock.mock_calls[1][2]["refresh_token"] == token.token | [
"async",
"def",
"test_setup_api_existing_hassio_user",
"(",
"hass",
",",
"aioclient_mock",
",",
"hass_storage",
")",
":",
"user",
"=",
"await",
"hass",
".",
"auth",
".",
"async_create_system_user",
"(",
"\"Hass.io test\"",
")",
"token",
"=",
"await",
"hass",
".",
"auth",
".",
"async_create_refresh_token",
"(",
"user",
")",
"hass_storage",
"[",
"STORAGE_KEY",
"]",
"=",
"{",
"\"version\"",
":",
"1",
",",
"\"data\"",
":",
"{",
"\"hassio_user\"",
":",
"user",
".",
"id",
"}",
"}",
"with",
"patch",
".",
"dict",
"(",
"os",
".",
"environ",
",",
"MOCK_ENVIRON",
")",
":",
"result",
"=",
"await",
"async_setup_component",
"(",
"hass",
",",
"\"hassio\"",
",",
"{",
"\"http\"",
":",
"{",
"}",
",",
"\"hassio\"",
":",
"{",
"}",
"}",
")",
"assert",
"result",
"assert",
"aioclient_mock",
".",
"call_count",
"==",
"9",
"assert",
"not",
"aioclient_mock",
".",
"mock_calls",
"[",
"1",
"]",
"[",
"2",
"]",
"[",
"\"ssl\"",
"]",
"assert",
"aioclient_mock",
".",
"mock_calls",
"[",
"1",
"]",
"[",
"2",
"]",
"[",
"\"port\"",
"]",
"==",
"8123",
"assert",
"aioclient_mock",
".",
"mock_calls",
"[",
"1",
"]",
"[",
"2",
"]",
"[",
"\"refresh_token\"",
"]",
"==",
"token",
".",
"token"
] | [
170,
0
] | [
182,
74
] | python | en | ['en', 'hi-Latn', 'en'] | True |
test_setup_core_push_timezone | (hass, aioclient_mock) | Test setup with API push default data. | Test setup with API push default data. | async def test_setup_core_push_timezone(hass, aioclient_mock):
"""Test setup with API push default data."""
hass.config.time_zone = "testzone"
with patch.dict(os.environ, MOCK_ENVIRON):
result = await async_setup_component(hass, "hassio", {"hassio": {}})
assert result
assert aioclient_mock.call_count == 9
assert aioclient_mock.mock_calls[2][2]["timezone"] == "testzone"
with patch("homeassistant.util.dt.set_default_time_zone"):
await hass.config.async_update(time_zone="America/New_York")
await hass.async_block_till_done()
assert aioclient_mock.mock_calls[-1][2]["timezone"] == "America/New_York" | [
"async",
"def",
"test_setup_core_push_timezone",
"(",
"hass",
",",
"aioclient_mock",
")",
":",
"hass",
".",
"config",
".",
"time_zone",
"=",
"\"testzone\"",
"with",
"patch",
".",
"dict",
"(",
"os",
".",
"environ",
",",
"MOCK_ENVIRON",
")",
":",
"result",
"=",
"await",
"async_setup_component",
"(",
"hass",
",",
"\"hassio\"",
",",
"{",
"\"hassio\"",
":",
"{",
"}",
"}",
")",
"assert",
"result",
"assert",
"aioclient_mock",
".",
"call_count",
"==",
"9",
"assert",
"aioclient_mock",
".",
"mock_calls",
"[",
"2",
"]",
"[",
"2",
"]",
"[",
"\"timezone\"",
"]",
"==",
"\"testzone\"",
"with",
"patch",
"(",
"\"homeassistant.util.dt.set_default_time_zone\"",
")",
":",
"await",
"hass",
".",
"config",
".",
"async_update",
"(",
"time_zone",
"=",
"\"America/New_York\"",
")",
"await",
"hass",
".",
"async_block_till_done",
"(",
")",
"assert",
"aioclient_mock",
".",
"mock_calls",
"[",
"-",
"1",
"]",
"[",
"2",
"]",
"[",
"\"timezone\"",
"]",
"==",
"\"America/New_York\""
] | [
185,
0
] | [
199,
77
] | python | en | ['en', 'hi-Latn', 'en'] | True |
test_setup_hassio_no_additional_data | (hass, aioclient_mock) | Test setup with API push default data. | Test setup with API push default data. | async def test_setup_hassio_no_additional_data(hass, aioclient_mock):
"""Test setup with API push default data."""
with patch.dict(os.environ, MOCK_ENVIRON), patch.dict(
os.environ, {"HASSIO_TOKEN": "123456"}
):
result = await async_setup_component(hass, "hassio", {"hassio": {}})
assert result
assert aioclient_mock.call_count == 9
assert aioclient_mock.mock_calls[-1][3]["X-Hassio-Key"] == "123456" | [
"async",
"def",
"test_setup_hassio_no_additional_data",
"(",
"hass",
",",
"aioclient_mock",
")",
":",
"with",
"patch",
".",
"dict",
"(",
"os",
".",
"environ",
",",
"MOCK_ENVIRON",
")",
",",
"patch",
".",
"dict",
"(",
"os",
".",
"environ",
",",
"{",
"\"HASSIO_TOKEN\"",
":",
"\"123456\"",
"}",
")",
":",
"result",
"=",
"await",
"async_setup_component",
"(",
"hass",
",",
"\"hassio\"",
",",
"{",
"\"hassio\"",
":",
"{",
"}",
"}",
")",
"assert",
"result",
"assert",
"aioclient_mock",
".",
"call_count",
"==",
"9",
"assert",
"aioclient_mock",
".",
"mock_calls",
"[",
"-",
"1",
"]",
"[",
"3",
"]",
"[",
"\"X-Hassio-Key\"",
"]",
"==",
"\"123456\""
] | [
202,
0
] | [
211,
71
] | python | en | ['en', 'hi-Latn', 'en'] | True |
test_fail_setup_without_environ_var | (hass) | Fail setup if no environ variable set. | Fail setup if no environ variable set. | async def test_fail_setup_without_environ_var(hass):
"""Fail setup if no environ variable set."""
with patch.dict(os.environ, {}, clear=True):
result = await async_setup_component(hass, "hassio", {})
assert not result | [
"async",
"def",
"test_fail_setup_without_environ_var",
"(",
"hass",
")",
":",
"with",
"patch",
".",
"dict",
"(",
"os",
".",
"environ",
",",
"{",
"}",
",",
"clear",
"=",
"True",
")",
":",
"result",
"=",
"await",
"async_setup_component",
"(",
"hass",
",",
"\"hassio\"",
",",
"{",
"}",
")",
"assert",
"not",
"result"
] | [
214,
0
] | [
218,
25
] | python | en | ['es', 'st', 'en'] | False |
test_warn_when_cannot_connect | (hass, caplog) | Fail warn when we cannot connect. | Fail warn when we cannot connect. | async def test_warn_when_cannot_connect(hass, caplog):
"""Fail warn when we cannot connect."""
with patch.dict(os.environ, MOCK_ENVIRON), patch(
"homeassistant.components.hassio.HassIO.is_connected",
return_value=None,
):
result = await async_setup_component(hass, "hassio", {})
assert result
assert hass.components.hassio.is_hassio()
assert "Not connected with Hass.io / system too busy!" in caplog.text | [
"async",
"def",
"test_warn_when_cannot_connect",
"(",
"hass",
",",
"caplog",
")",
":",
"with",
"patch",
".",
"dict",
"(",
"os",
".",
"environ",
",",
"MOCK_ENVIRON",
")",
",",
"patch",
"(",
"\"homeassistant.components.hassio.HassIO.is_connected\"",
",",
"return_value",
"=",
"None",
",",
")",
":",
"result",
"=",
"await",
"async_setup_component",
"(",
"hass",
",",
"\"hassio\"",
",",
"{",
"}",
")",
"assert",
"result",
"assert",
"hass",
".",
"components",
".",
"hassio",
".",
"is_hassio",
"(",
")",
"assert",
"\"Not connected with Hass.io / system too busy!\"",
"in",
"caplog",
".",
"text"
] | [
221,
0
] | [
231,
73
] | python | en | ['en', 'en', 'en'] | True |
test_service_register | (hassio_env, hass) | Check if service will be setup. | Check if service will be setup. | async def test_service_register(hassio_env, hass):
"""Check if service will be setup."""
assert await async_setup_component(hass, "hassio", {})
assert hass.services.has_service("hassio", "addon_start")
assert hass.services.has_service("hassio", "addon_stop")
assert hass.services.has_service("hassio", "addon_restart")
assert hass.services.has_service("hassio", "addon_stdin")
assert hass.services.has_service("hassio", "host_shutdown")
assert hass.services.has_service("hassio", "host_reboot")
assert hass.services.has_service("hassio", "host_reboot")
assert hass.services.has_service("hassio", "snapshot_full")
assert hass.services.has_service("hassio", "snapshot_partial")
assert hass.services.has_service("hassio", "restore_full")
assert hass.services.has_service("hassio", "restore_partial") | [
"async",
"def",
"test_service_register",
"(",
"hassio_env",
",",
"hass",
")",
":",
"assert",
"await",
"async_setup_component",
"(",
"hass",
",",
"\"hassio\"",
",",
"{",
"}",
")",
"assert",
"hass",
".",
"services",
".",
"has_service",
"(",
"\"hassio\"",
",",
"\"addon_start\"",
")",
"assert",
"hass",
".",
"services",
".",
"has_service",
"(",
"\"hassio\"",
",",
"\"addon_stop\"",
")",
"assert",
"hass",
".",
"services",
".",
"has_service",
"(",
"\"hassio\"",
",",
"\"addon_restart\"",
")",
"assert",
"hass",
".",
"services",
".",
"has_service",
"(",
"\"hassio\"",
",",
"\"addon_stdin\"",
")",
"assert",
"hass",
".",
"services",
".",
"has_service",
"(",
"\"hassio\"",
",",
"\"host_shutdown\"",
")",
"assert",
"hass",
".",
"services",
".",
"has_service",
"(",
"\"hassio\"",
",",
"\"host_reboot\"",
")",
"assert",
"hass",
".",
"services",
".",
"has_service",
"(",
"\"hassio\"",
",",
"\"host_reboot\"",
")",
"assert",
"hass",
".",
"services",
".",
"has_service",
"(",
"\"hassio\"",
",",
"\"snapshot_full\"",
")",
"assert",
"hass",
".",
"services",
".",
"has_service",
"(",
"\"hassio\"",
",",
"\"snapshot_partial\"",
")",
"assert",
"hass",
".",
"services",
".",
"has_service",
"(",
"\"hassio\"",
",",
"\"restore_full\"",
")",
"assert",
"hass",
".",
"services",
".",
"has_service",
"(",
"\"hassio\"",
",",
"\"restore_partial\"",
")"
] | [
234,
0
] | [
247,
65
] | python | en | ['en', 'en', 'en'] | True |
test_service_calls | (hassio_env, hass, aioclient_mock) | Call service and check the API calls behind that. | Call service and check the API calls behind that. | async def test_service_calls(hassio_env, hass, aioclient_mock):
"""Call service and check the API calls behind that."""
assert await async_setup_component(hass, "hassio", {})
aioclient_mock.post("http://127.0.0.1/addons/test/start", json={"result": "ok"})
aioclient_mock.post("http://127.0.0.1/addons/test/stop", json={"result": "ok"})
aioclient_mock.post("http://127.0.0.1/addons/test/restart", json={"result": "ok"})
aioclient_mock.post("http://127.0.0.1/addons/test/stdin", json={"result": "ok"})
aioclient_mock.post("http://127.0.0.1/host/shutdown", json={"result": "ok"})
aioclient_mock.post("http://127.0.0.1/host/reboot", json={"result": "ok"})
aioclient_mock.post("http://127.0.0.1/snapshots/new/full", json={"result": "ok"})
aioclient_mock.post("http://127.0.0.1/snapshots/new/partial", json={"result": "ok"})
aioclient_mock.post(
"http://127.0.0.1/snapshots/test/restore/full", json={"result": "ok"}
)
aioclient_mock.post(
"http://127.0.0.1/snapshots/test/restore/partial", json={"result": "ok"}
)
await hass.services.async_call("hassio", "addon_start", {"addon": "test"})
await hass.services.async_call("hassio", "addon_stop", {"addon": "test"})
await hass.services.async_call("hassio", "addon_restart", {"addon": "test"})
await hass.services.async_call(
"hassio", "addon_stdin", {"addon": "test", "input": "test"}
)
await hass.async_block_till_done()
assert aioclient_mock.call_count == 7
assert aioclient_mock.mock_calls[-1][2] == "test"
await hass.services.async_call("hassio", "host_shutdown", {})
await hass.services.async_call("hassio", "host_reboot", {})
await hass.async_block_till_done()
assert aioclient_mock.call_count == 9
await hass.services.async_call("hassio", "snapshot_full", {})
await hass.services.async_call(
"hassio",
"snapshot_partial",
{"addons": ["test"], "folders": ["ssl"], "password": "123456"},
)
await hass.async_block_till_done()
assert aioclient_mock.call_count == 11
assert aioclient_mock.mock_calls[-1][2] == {
"addons": ["test"],
"folders": ["ssl"],
"password": "123456",
}
await hass.services.async_call("hassio", "restore_full", {"snapshot": "test"})
await hass.services.async_call(
"hassio",
"restore_partial",
{
"snapshot": "test",
"homeassistant": False,
"addons": ["test"],
"folders": ["ssl"],
"password": "123456",
},
)
await hass.async_block_till_done()
assert aioclient_mock.call_count == 13
assert aioclient_mock.mock_calls[-1][2] == {
"addons": ["test"],
"folders": ["ssl"],
"homeassistant": False,
"password": "123456",
} | [
"async",
"def",
"test_service_calls",
"(",
"hassio_env",
",",
"hass",
",",
"aioclient_mock",
")",
":",
"assert",
"await",
"async_setup_component",
"(",
"hass",
",",
"\"hassio\"",
",",
"{",
"}",
")",
"aioclient_mock",
".",
"post",
"(",
"\"http://127.0.0.1/addons/test/start\"",
",",
"json",
"=",
"{",
"\"result\"",
":",
"\"ok\"",
"}",
")",
"aioclient_mock",
".",
"post",
"(",
"\"http://127.0.0.1/addons/test/stop\"",
",",
"json",
"=",
"{",
"\"result\"",
":",
"\"ok\"",
"}",
")",
"aioclient_mock",
".",
"post",
"(",
"\"http://127.0.0.1/addons/test/restart\"",
",",
"json",
"=",
"{",
"\"result\"",
":",
"\"ok\"",
"}",
")",
"aioclient_mock",
".",
"post",
"(",
"\"http://127.0.0.1/addons/test/stdin\"",
",",
"json",
"=",
"{",
"\"result\"",
":",
"\"ok\"",
"}",
")",
"aioclient_mock",
".",
"post",
"(",
"\"http://127.0.0.1/host/shutdown\"",
",",
"json",
"=",
"{",
"\"result\"",
":",
"\"ok\"",
"}",
")",
"aioclient_mock",
".",
"post",
"(",
"\"http://127.0.0.1/host/reboot\"",
",",
"json",
"=",
"{",
"\"result\"",
":",
"\"ok\"",
"}",
")",
"aioclient_mock",
".",
"post",
"(",
"\"http://127.0.0.1/snapshots/new/full\"",
",",
"json",
"=",
"{",
"\"result\"",
":",
"\"ok\"",
"}",
")",
"aioclient_mock",
".",
"post",
"(",
"\"http://127.0.0.1/snapshots/new/partial\"",
",",
"json",
"=",
"{",
"\"result\"",
":",
"\"ok\"",
"}",
")",
"aioclient_mock",
".",
"post",
"(",
"\"http://127.0.0.1/snapshots/test/restore/full\"",
",",
"json",
"=",
"{",
"\"result\"",
":",
"\"ok\"",
"}",
")",
"aioclient_mock",
".",
"post",
"(",
"\"http://127.0.0.1/snapshots/test/restore/partial\"",
",",
"json",
"=",
"{",
"\"result\"",
":",
"\"ok\"",
"}",
")",
"await",
"hass",
".",
"services",
".",
"async_call",
"(",
"\"hassio\"",
",",
"\"addon_start\"",
",",
"{",
"\"addon\"",
":",
"\"test\"",
"}",
")",
"await",
"hass",
".",
"services",
".",
"async_call",
"(",
"\"hassio\"",
",",
"\"addon_stop\"",
",",
"{",
"\"addon\"",
":",
"\"test\"",
"}",
")",
"await",
"hass",
".",
"services",
".",
"async_call",
"(",
"\"hassio\"",
",",
"\"addon_restart\"",
",",
"{",
"\"addon\"",
":",
"\"test\"",
"}",
")",
"await",
"hass",
".",
"services",
".",
"async_call",
"(",
"\"hassio\"",
",",
"\"addon_stdin\"",
",",
"{",
"\"addon\"",
":",
"\"test\"",
",",
"\"input\"",
":",
"\"test\"",
"}",
")",
"await",
"hass",
".",
"async_block_till_done",
"(",
")",
"assert",
"aioclient_mock",
".",
"call_count",
"==",
"7",
"assert",
"aioclient_mock",
".",
"mock_calls",
"[",
"-",
"1",
"]",
"[",
"2",
"]",
"==",
"\"test\"",
"await",
"hass",
".",
"services",
".",
"async_call",
"(",
"\"hassio\"",
",",
"\"host_shutdown\"",
",",
"{",
"}",
")",
"await",
"hass",
".",
"services",
".",
"async_call",
"(",
"\"hassio\"",
",",
"\"host_reboot\"",
",",
"{",
"}",
")",
"await",
"hass",
".",
"async_block_till_done",
"(",
")",
"assert",
"aioclient_mock",
".",
"call_count",
"==",
"9",
"await",
"hass",
".",
"services",
".",
"async_call",
"(",
"\"hassio\"",
",",
"\"snapshot_full\"",
",",
"{",
"}",
")",
"await",
"hass",
".",
"services",
".",
"async_call",
"(",
"\"hassio\"",
",",
"\"snapshot_partial\"",
",",
"{",
"\"addons\"",
":",
"[",
"\"test\"",
"]",
",",
"\"folders\"",
":",
"[",
"\"ssl\"",
"]",
",",
"\"password\"",
":",
"\"123456\"",
"}",
",",
")",
"await",
"hass",
".",
"async_block_till_done",
"(",
")",
"assert",
"aioclient_mock",
".",
"call_count",
"==",
"11",
"assert",
"aioclient_mock",
".",
"mock_calls",
"[",
"-",
"1",
"]",
"[",
"2",
"]",
"==",
"{",
"\"addons\"",
":",
"[",
"\"test\"",
"]",
",",
"\"folders\"",
":",
"[",
"\"ssl\"",
"]",
",",
"\"password\"",
":",
"\"123456\"",
",",
"}",
"await",
"hass",
".",
"services",
".",
"async_call",
"(",
"\"hassio\"",
",",
"\"restore_full\"",
",",
"{",
"\"snapshot\"",
":",
"\"test\"",
"}",
")",
"await",
"hass",
".",
"services",
".",
"async_call",
"(",
"\"hassio\"",
",",
"\"restore_partial\"",
",",
"{",
"\"snapshot\"",
":",
"\"test\"",
",",
"\"homeassistant\"",
":",
"False",
",",
"\"addons\"",
":",
"[",
"\"test\"",
"]",
",",
"\"folders\"",
":",
"[",
"\"ssl\"",
"]",
",",
"\"password\"",
":",
"\"123456\"",
",",
"}",
",",
")",
"await",
"hass",
".",
"async_block_till_done",
"(",
")",
"assert",
"aioclient_mock",
".",
"call_count",
"==",
"13",
"assert",
"aioclient_mock",
".",
"mock_calls",
"[",
"-",
"1",
"]",
"[",
"2",
"]",
"==",
"{",
"\"addons\"",
":",
"[",
"\"test\"",
"]",
",",
"\"folders\"",
":",
"[",
"\"ssl\"",
"]",
",",
"\"homeassistant\"",
":",
"False",
",",
"\"password\"",
":",
"\"123456\"",
",",
"}"
] | [
250,
0
] | [
321,
5
] | python | en | ['en', 'en', 'en'] | True |
test_service_calls_core | (hassio_env, hass, aioclient_mock) | Call core service and check the API calls behind that. | Call core service and check the API calls behind that. | async def test_service_calls_core(hassio_env, hass, aioclient_mock):
"""Call core service and check the API calls behind that."""
assert await async_setup_component(hass, "hassio", {})
aioclient_mock.post("http://127.0.0.1/homeassistant/restart", json={"result": "ok"})
aioclient_mock.post("http://127.0.0.1/homeassistant/stop", json={"result": "ok"})
await hass.services.async_call("homeassistant", "stop")
await hass.async_block_till_done()
assert aioclient_mock.call_count == 4
await hass.services.async_call("homeassistant", "check_config")
await hass.async_block_till_done()
assert aioclient_mock.call_count == 4
with patch(
"homeassistant.config.async_check_ha_config_file", return_value=None
) as mock_check_config:
await hass.services.async_call("homeassistant", "restart")
await hass.async_block_till_done()
assert mock_check_config.called
assert aioclient_mock.call_count == 5 | [
"async",
"def",
"test_service_calls_core",
"(",
"hassio_env",
",",
"hass",
",",
"aioclient_mock",
")",
":",
"assert",
"await",
"async_setup_component",
"(",
"hass",
",",
"\"hassio\"",
",",
"{",
"}",
")",
"aioclient_mock",
".",
"post",
"(",
"\"http://127.0.0.1/homeassistant/restart\"",
",",
"json",
"=",
"{",
"\"result\"",
":",
"\"ok\"",
"}",
")",
"aioclient_mock",
".",
"post",
"(",
"\"http://127.0.0.1/homeassistant/stop\"",
",",
"json",
"=",
"{",
"\"result\"",
":",
"\"ok\"",
"}",
")",
"await",
"hass",
".",
"services",
".",
"async_call",
"(",
"\"homeassistant\"",
",",
"\"stop\"",
")",
"await",
"hass",
".",
"async_block_till_done",
"(",
")",
"assert",
"aioclient_mock",
".",
"call_count",
"==",
"4",
"await",
"hass",
".",
"services",
".",
"async_call",
"(",
"\"homeassistant\"",
",",
"\"check_config\"",
")",
"await",
"hass",
".",
"async_block_till_done",
"(",
")",
"assert",
"aioclient_mock",
".",
"call_count",
"==",
"4",
"with",
"patch",
"(",
"\"homeassistant.config.async_check_ha_config_file\"",
",",
"return_value",
"=",
"None",
")",
"as",
"mock_check_config",
":",
"await",
"hass",
".",
"services",
".",
"async_call",
"(",
"\"homeassistant\"",
",",
"\"restart\"",
")",
"await",
"hass",
".",
"async_block_till_done",
"(",
")",
"assert",
"mock_check_config",
".",
"called",
"assert",
"aioclient_mock",
".",
"call_count",
"==",
"5"
] | [
324,
0
] | [
348,
41
] | python | en | ['en', 'en', 'en'] | True |
filter_soup | (soup, **kwargs) |
Adds an external link marker to external links
and makes them open in new tabs.
|
Adds an external link marker to external links
and makes them open in new tabs.
| def filter_soup(soup, **kwargs):
"""
Adds an external link marker to external links
and makes them open in new tabs.
"""
extern_regex = re.compile(r"^https?://")
links = soup.find_all("a", href=True)
for link in links:
if extern_regex.match(link["href"]):
link["target"] = "_blank"
ex_link_marker = soup.new_tag("i", attrs={
"class":"fa fa-external-link",
"aria-hidden": "true"})
link.append(" ")
link.append(ex_link_marker)
oldclass = link.get('class',[])
if type(oldclass) == str:
oldclass = [oldclass]
link['class'] = oldclass + ['external-link'] | [
"def",
"filter_soup",
"(",
"soup",
",",
"*",
"*",
"kwargs",
")",
":",
"extern_regex",
"=",
"re",
".",
"compile",
"(",
"r\"^https?://\"",
")",
"links",
"=",
"soup",
".",
"find_all",
"(",
"\"a\"",
",",
"href",
"=",
"True",
")",
"for",
"link",
"in",
"links",
":",
"if",
"extern_regex",
".",
"match",
"(",
"link",
"[",
"\"href\"",
"]",
")",
":",
"link",
"[",
"\"target\"",
"]",
"=",
"\"_blank\"",
"ex_link_marker",
"=",
"soup",
".",
"new_tag",
"(",
"\"i\"",
",",
"attrs",
"=",
"{",
"\"class\"",
":",
"\"fa fa-external-link\"",
",",
"\"aria-hidden\"",
":",
"\"true\"",
"}",
")",
"link",
".",
"append",
"(",
"\" \"",
")",
"link",
".",
"append",
"(",
"ex_link_marker",
")",
"oldclass",
"=",
"link",
".",
"get",
"(",
"'class'",
",",
"[",
"]",
")",
"if",
"type",
"(",
"oldclass",
")",
"==",
"str",
":",
"oldclass",
"=",
"[",
"oldclass",
"]",
"link",
"[",
"'class'",
"]",
"=",
"oldclass",
"+",
"[",
"'external-link'",
"]"
] | [
13,
0
] | [
33,
56
] | python | en | ['en', 'error', 'th'] | False |
TestKiraSensor.add_entities | (self, devices) | Mock add devices. | Mock add devices. | def add_entities(self, devices):
"""Mock add devices."""
for device in devices:
self.DEVICES.append(device) | [
"def",
"add_entities",
"(",
"self",
",",
"devices",
")",
":",
"for",
"device",
"in",
"devices",
":",
"self",
".",
"DEVICES",
".",
"append",
"(",
"device",
")"
] | [
19,
4
] | [
22,
39
] | python | en | ['es', 'en', 'en'] | True |
TestKiraSensor.setUp | (self) | Initialize values for this testcase class. | Initialize values for this testcase class. | def setUp(self):
"""Initialize values for this testcase class."""
self.hass = get_test_home_assistant()
mock_kira = MagicMock()
self.hass.data[kira.DOMAIN] = {kira.CONF_SENSOR: {}}
self.hass.data[kira.DOMAIN][kira.CONF_SENSOR]["kira"] = mock_kira
self.addCleanup(self.hass.stop) | [
"def",
"setUp",
"(",
"self",
")",
":",
"self",
".",
"hass",
"=",
"get_test_home_assistant",
"(",
")",
"mock_kira",
"=",
"MagicMock",
"(",
")",
"self",
".",
"hass",
".",
"data",
"[",
"kira",
".",
"DOMAIN",
"]",
"=",
"{",
"kira",
".",
"CONF_SENSOR",
":",
"{",
"}",
"}",
"self",
".",
"hass",
".",
"data",
"[",
"kira",
".",
"DOMAIN",
"]",
"[",
"kira",
".",
"CONF_SENSOR",
"]",
"[",
"\"kira\"",
"]",
"=",
"mock_kira",
"self",
".",
"addCleanup",
"(",
"self",
".",
"hass",
".",
"stop",
")"
] | [
24,
4
] | [
30,
39
] | python | en | ['en', 'en', 'en'] | True |
TestKiraSensor.test_kira_sensor_callback | (self) | Ensure Kira sensor properly updates its attributes from callback. | Ensure Kira sensor properly updates its attributes from callback. | def test_kira_sensor_callback(self):
"""Ensure Kira sensor properly updates its attributes from callback."""
kira.setup_platform(self.hass, TEST_CONFIG, self.add_entities, DISCOVERY_INFO)
assert len(self.DEVICES) == 1
sensor = self.DEVICES[0]
assert sensor.name == "kira"
sensor.hass = self.hass
codeName = "FAKE_CODE"
deviceName = "FAKE_DEVICE"
codeTuple = (codeName, deviceName)
sensor._update_callback(codeTuple)
assert sensor.state == codeName
assert sensor.device_state_attributes == {kira.CONF_DEVICE: deviceName} | [
"def",
"test_kira_sensor_callback",
"(",
"self",
")",
":",
"kira",
".",
"setup_platform",
"(",
"self",
".",
"hass",
",",
"TEST_CONFIG",
",",
"self",
".",
"add_entities",
",",
"DISCOVERY_INFO",
")",
"assert",
"len",
"(",
"self",
".",
"DEVICES",
")",
"==",
"1",
"sensor",
"=",
"self",
".",
"DEVICES",
"[",
"0",
"]",
"assert",
"sensor",
".",
"name",
"==",
"\"kira\"",
"sensor",
".",
"hass",
"=",
"self",
".",
"hass",
"codeName",
"=",
"\"FAKE_CODE\"",
"deviceName",
"=",
"\"FAKE_DEVICE\"",
"codeTuple",
"=",
"(",
"codeName",
",",
"deviceName",
")",
"sensor",
".",
"_update_callback",
"(",
"codeTuple",
")",
"assert",
"sensor",
".",
"state",
"==",
"codeName",
"assert",
"sensor",
".",
"device_state_attributes",
"==",
"{",
"kira",
".",
"CONF_DEVICE",
":",
"deviceName",
"}"
] | [
33,
4
] | [
49,
79
] | python | en | ['en', 'ny', 'en'] | True |
setup_platform | (hass, config, add_entities, discovery_info=None) | Set up the Lutron switches. | Set up the Lutron switches. | def setup_platform(hass, config, add_entities, discovery_info=None):
"""Set up the Lutron switches."""
devs = []
# Add Lutron Switches
for (area_name, device) in hass.data[LUTRON_DEVICES]["switch"]:
dev = LutronSwitch(area_name, device, hass.data[LUTRON_CONTROLLER])
devs.append(dev)
# Add the indicator LEDs for scenes (keypad buttons)
for scene_data in hass.data[LUTRON_DEVICES]["scene"]:
(area_name, keypad_name, scene, led) = scene_data
if led is not None:
led = LutronLed(
area_name, keypad_name, scene, led, hass.data[LUTRON_CONTROLLER]
)
devs.append(led)
add_entities(devs, True) | [
"def",
"setup_platform",
"(",
"hass",
",",
"config",
",",
"add_entities",
",",
"discovery_info",
"=",
"None",
")",
":",
"devs",
"=",
"[",
"]",
"# Add Lutron Switches",
"for",
"(",
"area_name",
",",
"device",
")",
"in",
"hass",
".",
"data",
"[",
"LUTRON_DEVICES",
"]",
"[",
"\"switch\"",
"]",
":",
"dev",
"=",
"LutronSwitch",
"(",
"area_name",
",",
"device",
",",
"hass",
".",
"data",
"[",
"LUTRON_CONTROLLER",
"]",
")",
"devs",
".",
"append",
"(",
"dev",
")",
"# Add the indicator LEDs for scenes (keypad buttons)",
"for",
"scene_data",
"in",
"hass",
".",
"data",
"[",
"LUTRON_DEVICES",
"]",
"[",
"\"scene\"",
"]",
":",
"(",
"area_name",
",",
"keypad_name",
",",
"scene",
",",
"led",
")",
"=",
"scene_data",
"if",
"led",
"is",
"not",
"None",
":",
"led",
"=",
"LutronLed",
"(",
"area_name",
",",
"keypad_name",
",",
"scene",
",",
"led",
",",
"hass",
".",
"data",
"[",
"LUTRON_CONTROLLER",
"]",
")",
"devs",
".",
"append",
"(",
"led",
")",
"add_entities",
"(",
"devs",
",",
"True",
")"
] | [
6,
0
] | [
24,
28
] | python | en | ['en', 'en', 'en'] | True |
LutronSwitch.__init__ | (self, area_name, lutron_device, controller) | Initialize the switch. | Initialize the switch. | def __init__(self, area_name, lutron_device, controller):
"""Initialize the switch."""
self._prev_state = None
super().__init__(area_name, lutron_device, controller) | [
"def",
"__init__",
"(",
"self",
",",
"area_name",
",",
"lutron_device",
",",
"controller",
")",
":",
"self",
".",
"_prev_state",
"=",
"None",
"super",
"(",
")",
".",
"__init__",
"(",
"area_name",
",",
"lutron_device",
",",
"controller",
")"
] | [
30,
4
] | [
33,
62
] | python | en | ['en', 'en', 'en'] | True |
LutronSwitch.turn_on | (self, **kwargs) | Turn the switch on. | Turn the switch on. | def turn_on(self, **kwargs):
"""Turn the switch on."""
self._lutron_device.level = 100 | [
"def",
"turn_on",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"_lutron_device",
".",
"level",
"=",
"100"
] | [
35,
4
] | [
37,
39
] | python | en | ['en', 'en', 'en'] | True |
LutronSwitch.turn_off | (self, **kwargs) | Turn the switch off. | Turn the switch off. | def turn_off(self, **kwargs):
"""Turn the switch off."""
self._lutron_device.level = 0 | [
"def",
"turn_off",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"_lutron_device",
".",
"level",
"=",
"0"
] | [
39,
4
] | [
41,
37
] | python | en | ['en', 'en', 'en'] | True |
LutronSwitch.device_state_attributes | (self) | Return the state attributes. | Return the state attributes. | def device_state_attributes(self):
"""Return the state attributes."""
return {"lutron_integration_id": self._lutron_device.id} | [
"def",
"device_state_attributes",
"(",
"self",
")",
":",
"return",
"{",
"\"lutron_integration_id\"",
":",
"self",
".",
"_lutron_device",
".",
"id",
"}"
] | [
44,
4
] | [
46,
64
] | python | en | ['en', 'en', 'en'] | True |
LutronSwitch.is_on | (self) | Return true if device is on. | Return true if device is on. | def is_on(self):
"""Return true if device is on."""
return self._lutron_device.last_level() > 0 | [
"def",
"is_on",
"(",
"self",
")",
":",
"return",
"self",
".",
"_lutron_device",
".",
"last_level",
"(",
")",
">",
"0"
] | [
49,
4
] | [
51,
51
] | python | en | ['en', 'fy', 'en'] | True |
LutronSwitch.update | (self) | Call when forcing a refresh of the device. | Call when forcing a refresh of the device. | def update(self):
"""Call when forcing a refresh of the device."""
if self._prev_state is None:
self._prev_state = self._lutron_device.level > 0 | [
"def",
"update",
"(",
"self",
")",
":",
"if",
"self",
".",
"_prev_state",
"is",
"None",
":",
"self",
".",
"_prev_state",
"=",
"self",
".",
"_lutron_device",
".",
"level",
">",
"0"
] | [
53,
4
] | [
56,
60
] | python | en | ['en', 'en', 'en'] | True |
LutronLed.__init__ | (self, area_name, keypad_name, scene_device, led_device, controller) | Initialize the switch. | Initialize the switch. | def __init__(self, area_name, keypad_name, scene_device, led_device, controller):
"""Initialize the switch."""
self._keypad_name = keypad_name
self._scene_name = scene_device.name
super().__init__(area_name, led_device, controller) | [
"def",
"__init__",
"(",
"self",
",",
"area_name",
",",
"keypad_name",
",",
"scene_device",
",",
"led_device",
",",
"controller",
")",
":",
"self",
".",
"_keypad_name",
"=",
"keypad_name",
"self",
".",
"_scene_name",
"=",
"scene_device",
".",
"name",
"super",
"(",
")",
".",
"__init__",
"(",
"area_name",
",",
"led_device",
",",
"controller",
")"
] | [
62,
4
] | [
66,
59
] | python | en | ['en', 'en', 'en'] | True |
LutronLed.turn_on | (self, **kwargs) | Turn the LED on. | Turn the LED on. | def turn_on(self, **kwargs):
"""Turn the LED on."""
self._lutron_device.state = 1 | [
"def",
"turn_on",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"_lutron_device",
".",
"state",
"=",
"1"
] | [
68,
4
] | [
70,
37
] | python | en | ['en', 'zu', 'en'] | True |
LutronLed.turn_off | (self, **kwargs) | Turn the LED off. | Turn the LED off. | def turn_off(self, **kwargs):
"""Turn the LED off."""
self._lutron_device.state = 0 | [
"def",
"turn_off",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"_lutron_device",
".",
"state",
"=",
"0"
] | [
72,
4
] | [
74,
37
] | python | en | ['en', 'sm', 'en'] | True |
LutronLed.device_state_attributes | (self) | Return the state attributes. | Return the state attributes. | def device_state_attributes(self):
"""Return the state attributes."""
return {
"keypad": self._keypad_name,
"scene": self._scene_name,
"led": self._lutron_device.name,
} | [
"def",
"device_state_attributes",
"(",
"self",
")",
":",
"return",
"{",
"\"keypad\"",
":",
"self",
".",
"_keypad_name",
",",
"\"scene\"",
":",
"self",
".",
"_scene_name",
",",
"\"led\"",
":",
"self",
".",
"_lutron_device",
".",
"name",
",",
"}"
] | [
77,
4
] | [
83,
9
] | python | en | ['en', 'en', 'en'] | True |
LutronLed.is_on | (self) | Return true if device is on. | Return true if device is on. | def is_on(self):
"""Return true if device is on."""
return self._lutron_device.last_state | [
"def",
"is_on",
"(",
"self",
")",
":",
"return",
"self",
".",
"_lutron_device",
".",
"last_state"
] | [
86,
4
] | [
88,
45
] | python | en | ['en', 'fy', 'en'] | True |
LutronLed.name | (self) | Return the name of the LED. | Return the name of the LED. | def name(self):
"""Return the name of the LED."""
return f"{self._area_name} {self._keypad_name}: {self._scene_name} LED" | [
"def",
"name",
"(",
"self",
")",
":",
"return",
"f\"{self._area_name} {self._keypad_name}: {self._scene_name} LED\""
] | [
91,
4
] | [
93,
79
] | python | en | ['en', 'en', 'en'] | True |
LutronLed.update | (self) | Call when forcing a refresh of the device. | Call when forcing a refresh of the device. | def update(self):
"""Call when forcing a refresh of the device."""
if self._lutron_device.last_state is not None:
return
# The following property getter actually triggers an update in Lutron
self._lutron_device.state | [
"def",
"update",
"(",
"self",
")",
":",
"if",
"self",
".",
"_lutron_device",
".",
"last_state",
"is",
"not",
"None",
":",
"return",
"# The following property getter actually triggers an update in Lutron",
"self",
".",
"_lutron_device",
".",
"state"
] | [
95,
4
] | [
101,
33
] | python | en | ['en', 'en', 'en'] | True |
load_tf_weights_in_t5 | (model, config, tf_checkpoint_path) | Load tf checkpoints in a pytorch model. | Load tf checkpoints in a pytorch model. | def load_tf_weights_in_t5(model, config, tf_checkpoint_path):
"""Load tf checkpoints in a pytorch model."""
try:
import re
import numpy as np
import tensorflow as tf
except ImportError:
logger.error(
"Loading a TensorFlow model in PyTorch, requires TensorFlow to be installed. Please see "
"https://www.tensorflow.org/install/ for installation instructions."
)
raise
tf_path = os.path.abspath(tf_checkpoint_path)
logger.info("Converting TensorFlow checkpoint from {}".format(tf_path))
# Load weights from TF model
init_vars = tf.train.list_variables(tf_path)
names = []
tf_weights = {}
for name, shape in init_vars:
logger.info("Loading TF weight {} with shape {}".format(name, shape))
array = tf.train.load_variable(tf_path, name)
names.append(name)
tf_weights[name] = array
for txt_name in names:
name = txt_name.split("/")
# adam_v and adam_m are variables used in AdamWeightDecayOptimizer to calculated m and v
# which are not required for using pretrained model
if any(
n in ["adam_v", "adam_m", "AdamWeightDecayOptimizer", "AdamWeightDecayOptimizer_1", "global_step"]
for n in name
):
logger.info("Skipping {}".format("/".join(name)))
tf_weights.pop(txt_name, None)
continue
if "_slot_" in name[-1]:
logger.info("Skipping {}".format("/".join(name)))
tf_weights.pop(txt_name, None)
continue
pointer = model
array = tf_weights[txt_name]
for m_name in name:
if re.fullmatch(r"[A-Za-z]+_\d+", m_name):
scope_names = re.split(r"_(\d+)", m_name)
else:
scope_names = [m_name]
if scope_names[0] in ["kernel", "scale", "embedding"]:
pointer = getattr(pointer, "weight")
elif scope_names[0] == "self_attention":
pointer = getattr(pointer, "layer")
pointer = pointer[0]
elif scope_names[0] == "enc_dec_attention":
pointer = getattr(pointer, "layer")
pointer = pointer[1]
elif scope_names[0] == "dense_relu_dense":
pointer = getattr(pointer, "layer")
pointer = pointer[2]
elif scope_names[0] == "rms_norm":
if hasattr(pointer, "layer_norm"):
pointer = getattr(pointer, "layer_norm")
elif hasattr(pointer, "final_layer_norm"):
pointer = getattr(pointer, "final_layer_norm")
elif scope_names[0] == "scale":
pointer = getattr(pointer, "weight")
elif scope_names[0] == "output_bias" or scope_names[0] == "beta":
pointer = getattr(pointer, "bias")
elif scope_names[0] == "squad":
pointer = getattr(pointer, "classifier")
elif scope_names[0] == "decoder" and name[1] == "logits":
continue
elif scope_names[0] == "logits":
pointer = getattr(pointer, "lm_head")
elif scope_names[0] == "wi" and len(scope_names) > 1 and scope_names[1].isdigit():
pointer = getattr(pointer, f"wi_{scope_names[1]}")
continue
else:
try:
pointer = getattr(pointer, scope_names[0])
except AttributeError:
logger.info("Skipping {}".format("/".join(name)))
continue
if len(scope_names) >= 2:
num = int(scope_names[1])
pointer = pointer[num]
if scope_names[0] not in ["kernel", "scale", "embedding"]:
pointer = getattr(pointer, "weight")
if scope_names[0] != "embedding":
logger.info("Transposing numpy weight of shape {} for {}".format(array.shape, name))
array = np.transpose(array)
try:
assert (
pointer.shape == array.shape
), f"Pointer shape {pointer.shape} and array shape {array.shape} mismatched"
except AssertionError as e:
e.args += (pointer.shape, array.shape)
raise
logger.info("Initialize PyTorch weight {}".format(name))
pointer.data = torch.from_numpy(array.astype(np.float32))
tf_weights.pop(txt_name, None)
logger.info("Weights not copied to PyTorch model: {}".format(", ".join(tf_weights.keys())))
return model | [
"def",
"load_tf_weights_in_t5",
"(",
"model",
",",
"config",
",",
"tf_checkpoint_path",
")",
":",
"try",
":",
"import",
"re",
"import",
"numpy",
"as",
"np",
"import",
"tensorflow",
"as",
"tf",
"except",
"ImportError",
":",
"logger",
".",
"error",
"(",
"\"Loading a TensorFlow model in PyTorch, requires TensorFlow to be installed. Please see \"",
"\"https://www.tensorflow.org/install/ for installation instructions.\"",
")",
"raise",
"tf_path",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"tf_checkpoint_path",
")",
"logger",
".",
"info",
"(",
"\"Converting TensorFlow checkpoint from {}\"",
".",
"format",
"(",
"tf_path",
")",
")",
"# Load weights from TF model",
"init_vars",
"=",
"tf",
".",
"train",
".",
"list_variables",
"(",
"tf_path",
")",
"names",
"=",
"[",
"]",
"tf_weights",
"=",
"{",
"}",
"for",
"name",
",",
"shape",
"in",
"init_vars",
":",
"logger",
".",
"info",
"(",
"\"Loading TF weight {} with shape {}\"",
".",
"format",
"(",
"name",
",",
"shape",
")",
")",
"array",
"=",
"tf",
".",
"train",
".",
"load_variable",
"(",
"tf_path",
",",
"name",
")",
"names",
".",
"append",
"(",
"name",
")",
"tf_weights",
"[",
"name",
"]",
"=",
"array",
"for",
"txt_name",
"in",
"names",
":",
"name",
"=",
"txt_name",
".",
"split",
"(",
"\"/\"",
")",
"# adam_v and adam_m are variables used in AdamWeightDecayOptimizer to calculated m and v",
"# which are not required for using pretrained model",
"if",
"any",
"(",
"n",
"in",
"[",
"\"adam_v\"",
",",
"\"adam_m\"",
",",
"\"AdamWeightDecayOptimizer\"",
",",
"\"AdamWeightDecayOptimizer_1\"",
",",
"\"global_step\"",
"]",
"for",
"n",
"in",
"name",
")",
":",
"logger",
".",
"info",
"(",
"\"Skipping {}\"",
".",
"format",
"(",
"\"/\"",
".",
"join",
"(",
"name",
")",
")",
")",
"tf_weights",
".",
"pop",
"(",
"txt_name",
",",
"None",
")",
"continue",
"if",
"\"_slot_\"",
"in",
"name",
"[",
"-",
"1",
"]",
":",
"logger",
".",
"info",
"(",
"\"Skipping {}\"",
".",
"format",
"(",
"\"/\"",
".",
"join",
"(",
"name",
")",
")",
")",
"tf_weights",
".",
"pop",
"(",
"txt_name",
",",
"None",
")",
"continue",
"pointer",
"=",
"model",
"array",
"=",
"tf_weights",
"[",
"txt_name",
"]",
"for",
"m_name",
"in",
"name",
":",
"if",
"re",
".",
"fullmatch",
"(",
"r\"[A-Za-z]+_\\d+\"",
",",
"m_name",
")",
":",
"scope_names",
"=",
"re",
".",
"split",
"(",
"r\"_(\\d+)\"",
",",
"m_name",
")",
"else",
":",
"scope_names",
"=",
"[",
"m_name",
"]",
"if",
"scope_names",
"[",
"0",
"]",
"in",
"[",
"\"kernel\"",
",",
"\"scale\"",
",",
"\"embedding\"",
"]",
":",
"pointer",
"=",
"getattr",
"(",
"pointer",
",",
"\"weight\"",
")",
"elif",
"scope_names",
"[",
"0",
"]",
"==",
"\"self_attention\"",
":",
"pointer",
"=",
"getattr",
"(",
"pointer",
",",
"\"layer\"",
")",
"pointer",
"=",
"pointer",
"[",
"0",
"]",
"elif",
"scope_names",
"[",
"0",
"]",
"==",
"\"enc_dec_attention\"",
":",
"pointer",
"=",
"getattr",
"(",
"pointer",
",",
"\"layer\"",
")",
"pointer",
"=",
"pointer",
"[",
"1",
"]",
"elif",
"scope_names",
"[",
"0",
"]",
"==",
"\"dense_relu_dense\"",
":",
"pointer",
"=",
"getattr",
"(",
"pointer",
",",
"\"layer\"",
")",
"pointer",
"=",
"pointer",
"[",
"2",
"]",
"elif",
"scope_names",
"[",
"0",
"]",
"==",
"\"rms_norm\"",
":",
"if",
"hasattr",
"(",
"pointer",
",",
"\"layer_norm\"",
")",
":",
"pointer",
"=",
"getattr",
"(",
"pointer",
",",
"\"layer_norm\"",
")",
"elif",
"hasattr",
"(",
"pointer",
",",
"\"final_layer_norm\"",
")",
":",
"pointer",
"=",
"getattr",
"(",
"pointer",
",",
"\"final_layer_norm\"",
")",
"elif",
"scope_names",
"[",
"0",
"]",
"==",
"\"scale\"",
":",
"pointer",
"=",
"getattr",
"(",
"pointer",
",",
"\"weight\"",
")",
"elif",
"scope_names",
"[",
"0",
"]",
"==",
"\"output_bias\"",
"or",
"scope_names",
"[",
"0",
"]",
"==",
"\"beta\"",
":",
"pointer",
"=",
"getattr",
"(",
"pointer",
",",
"\"bias\"",
")",
"elif",
"scope_names",
"[",
"0",
"]",
"==",
"\"squad\"",
":",
"pointer",
"=",
"getattr",
"(",
"pointer",
",",
"\"classifier\"",
")",
"elif",
"scope_names",
"[",
"0",
"]",
"==",
"\"decoder\"",
"and",
"name",
"[",
"1",
"]",
"==",
"\"logits\"",
":",
"continue",
"elif",
"scope_names",
"[",
"0",
"]",
"==",
"\"logits\"",
":",
"pointer",
"=",
"getattr",
"(",
"pointer",
",",
"\"lm_head\"",
")",
"elif",
"scope_names",
"[",
"0",
"]",
"==",
"\"wi\"",
"and",
"len",
"(",
"scope_names",
")",
">",
"1",
"and",
"scope_names",
"[",
"1",
"]",
".",
"isdigit",
"(",
")",
":",
"pointer",
"=",
"getattr",
"(",
"pointer",
",",
"f\"wi_{scope_names[1]}\"",
")",
"continue",
"else",
":",
"try",
":",
"pointer",
"=",
"getattr",
"(",
"pointer",
",",
"scope_names",
"[",
"0",
"]",
")",
"except",
"AttributeError",
":",
"logger",
".",
"info",
"(",
"\"Skipping {}\"",
".",
"format",
"(",
"\"/\"",
".",
"join",
"(",
"name",
")",
")",
")",
"continue",
"if",
"len",
"(",
"scope_names",
")",
">=",
"2",
":",
"num",
"=",
"int",
"(",
"scope_names",
"[",
"1",
"]",
")",
"pointer",
"=",
"pointer",
"[",
"num",
"]",
"if",
"scope_names",
"[",
"0",
"]",
"not",
"in",
"[",
"\"kernel\"",
",",
"\"scale\"",
",",
"\"embedding\"",
"]",
":",
"pointer",
"=",
"getattr",
"(",
"pointer",
",",
"\"weight\"",
")",
"if",
"scope_names",
"[",
"0",
"]",
"!=",
"\"embedding\"",
":",
"logger",
".",
"info",
"(",
"\"Transposing numpy weight of shape {} for {}\"",
".",
"format",
"(",
"array",
".",
"shape",
",",
"name",
")",
")",
"array",
"=",
"np",
".",
"transpose",
"(",
"array",
")",
"try",
":",
"assert",
"(",
"pointer",
".",
"shape",
"==",
"array",
".",
"shape",
")",
",",
"f\"Pointer shape {pointer.shape} and array shape {array.shape} mismatched\"",
"except",
"AssertionError",
"as",
"e",
":",
"e",
".",
"args",
"+=",
"(",
"pointer",
".",
"shape",
",",
"array",
".",
"shape",
")",
"raise",
"logger",
".",
"info",
"(",
"\"Initialize PyTorch weight {}\"",
".",
"format",
"(",
"name",
")",
")",
"pointer",
".",
"data",
"=",
"torch",
".",
"from_numpy",
"(",
"array",
".",
"astype",
"(",
"np",
".",
"float32",
")",
")",
"tf_weights",
".",
"pop",
"(",
"txt_name",
",",
"None",
")",
"logger",
".",
"info",
"(",
"\"Weights not copied to PyTorch model: {}\"",
".",
"format",
"(",
"\", \"",
".",
"join",
"(",
"tf_weights",
".",
"keys",
"(",
")",
")",
")",
")",
"return",
"model"
] | [
70,
0
] | [
173,
16
] | python | en | ['en', 'en', 'en'] | True |
T5LayerNorm.__init__ | (self, hidden_size, eps=1e-6) |
Construct a layernorm module in the T5 style No bias and no subtraction of mean.
|
Construct a layernorm module in the T5 style No bias and no subtraction of mean.
| def __init__(self, hidden_size, eps=1e-6):
"""
Construct a layernorm module in the T5 style No bias and no subtraction of mean.
"""
super().__init__()
self.weight = nn.Parameter(torch.ones(hidden_size))
self.variance_epsilon = eps | [
"def",
"__init__",
"(",
"self",
",",
"hidden_size",
",",
"eps",
"=",
"1e-6",
")",
":",
"super",
"(",
")",
".",
"__init__",
"(",
")",
"self",
".",
"weight",
"=",
"nn",
".",
"Parameter",
"(",
"torch",
".",
"ones",
"(",
"hidden_size",
")",
")",
"self",
".",
"variance_epsilon",
"=",
"eps"
] | [
229,
4
] | [
235,
35
] | python | en | ['en', 'error', 'th'] | False |
T5Attention._relative_position_bucket | (relative_position, bidirectional=True, num_buckets=32, max_distance=128) |
Adapted from Mesh Tensorflow:
https://github.com/tensorflow/mesh/blob/0cb87fe07da627bf0b7e60475d59f95ed6b5be3d/mesh_tensorflow/transformer/transformer_layers.py#L593
Translate relative position to a bucket number for relative attention. The relative position is defined as
memory_position - query_position, i.e. the distance in tokens from the attending position to the attended-to
position. If bidirectional=False, then positive relative positions are invalid. We use smaller buckets for
small absolute relative_position and larger buckets for larger absolute relative_positions. All relative
positions >=max_distance map to the same bucket. All relative positions <=-max_distance map to the same bucket.
This should allow for more graceful generalization to longer sequences than the model has been trained on
Args:
relative_position: an int32 Tensor
bidirectional: a boolean - whether the attention is bidirectional
num_buckets: an integer
max_distance: an integer
Returns:
a Tensor with the same shape as relative_position, containing int32 values in the range [0, num_buckets)
|
Adapted from Mesh Tensorflow:
https://github.com/tensorflow/mesh/blob/0cb87fe07da627bf0b7e60475d59f95ed6b5be3d/mesh_tensorflow/transformer/transformer_layers.py#L593 | def _relative_position_bucket(relative_position, bidirectional=True, num_buckets=32, max_distance=128):
"""
Adapted from Mesh Tensorflow:
https://github.com/tensorflow/mesh/blob/0cb87fe07da627bf0b7e60475d59f95ed6b5be3d/mesh_tensorflow/transformer/transformer_layers.py#L593
Translate relative position to a bucket number for relative attention. The relative position is defined as
memory_position - query_position, i.e. the distance in tokens from the attending position to the attended-to
position. If bidirectional=False, then positive relative positions are invalid. We use smaller buckets for
small absolute relative_position and larger buckets for larger absolute relative_positions. All relative
positions >=max_distance map to the same bucket. All relative positions <=-max_distance map to the same bucket.
This should allow for more graceful generalization to longer sequences than the model has been trained on
Args:
relative_position: an int32 Tensor
bidirectional: a boolean - whether the attention is bidirectional
num_buckets: an integer
max_distance: an integer
Returns:
a Tensor with the same shape as relative_position, containing int32 values in the range [0, num_buckets)
"""
relative_buckets = 0
if bidirectional:
num_buckets //= 2
relative_buckets += (relative_position > 0).to(torch.long) * num_buckets
relative_position = torch.abs(relative_position)
else:
relative_position = -torch.min(relative_position, torch.zeros_like(relative_position))
# now relative_position is in the range [0, inf)
# half of the buckets are for exact increments in positions
max_exact = num_buckets // 2
is_small = relative_position < max_exact
# The other half of the buckets are for logarithmically bigger bins in positions up to max_distance
relative_postion_if_large = max_exact + (
torch.log(relative_position.float() / max_exact)
/ math.log(max_distance / max_exact)
* (num_buckets - max_exact)
).to(torch.long)
relative_postion_if_large = torch.min(
relative_postion_if_large, torch.full_like(relative_postion_if_large, num_buckets - 1)
)
relative_buckets += torch.where(is_small, relative_position, relative_postion_if_large)
return relative_buckets | [
"def",
"_relative_position_bucket",
"(",
"relative_position",
",",
"bidirectional",
"=",
"True",
",",
"num_buckets",
"=",
"32",
",",
"max_distance",
"=",
"128",
")",
":",
"relative_buckets",
"=",
"0",
"if",
"bidirectional",
":",
"num_buckets",
"//=",
"2",
"relative_buckets",
"+=",
"(",
"relative_position",
">",
"0",
")",
".",
"to",
"(",
"torch",
".",
"long",
")",
"*",
"num_buckets",
"relative_position",
"=",
"torch",
".",
"abs",
"(",
"relative_position",
")",
"else",
":",
"relative_position",
"=",
"-",
"torch",
".",
"min",
"(",
"relative_position",
",",
"torch",
".",
"zeros_like",
"(",
"relative_position",
")",
")",
"# now relative_position is in the range [0, inf)",
"# half of the buckets are for exact increments in positions",
"max_exact",
"=",
"num_buckets",
"//",
"2",
"is_small",
"=",
"relative_position",
"<",
"max_exact",
"# The other half of the buckets are for logarithmically bigger bins in positions up to max_distance",
"relative_postion_if_large",
"=",
"max_exact",
"+",
"(",
"torch",
".",
"log",
"(",
"relative_position",
".",
"float",
"(",
")",
"/",
"max_exact",
")",
"/",
"math",
".",
"log",
"(",
"max_distance",
"/",
"max_exact",
")",
"*",
"(",
"num_buckets",
"-",
"max_exact",
")",
")",
".",
"to",
"(",
"torch",
".",
"long",
")",
"relative_postion_if_large",
"=",
"torch",
".",
"min",
"(",
"relative_postion_if_large",
",",
"torch",
".",
"full_like",
"(",
"relative_postion_if_large",
",",
"num_buckets",
"-",
"1",
")",
")",
"relative_buckets",
"+=",
"torch",
".",
"where",
"(",
"is_small",
",",
"relative_position",
",",
"relative_postion_if_large",
")",
"return",
"relative_buckets"
] | [
343,
4
] | [
388,
31
] | python | en | ['en', 'error', 'th'] | False |
T5Attention.compute_bias | (self, query_length, key_length) | Compute binned relative position bias | Compute binned relative position bias | def compute_bias(self, query_length, key_length):
""" Compute binned relative position bias """
context_position = torch.arange(query_length, dtype=torch.long)[:, None]
memory_position = torch.arange(key_length, dtype=torch.long)[None, :]
relative_position = memory_position - context_position # shape (query_length, key_length)
relative_position_bucket = self._relative_position_bucket(
relative_position, # shape (query_length, key_length)
bidirectional=(not self.is_decoder),
num_buckets=self.relative_attention_num_buckets,
)
relative_position_bucket = relative_position_bucket.to(self.relative_attention_bias.weight.device)
values = self.relative_attention_bias(relative_position_bucket) # shape (query_length, key_length, num_heads)
values = values.permute([2, 0, 1]).unsqueeze(0) # shape (1, num_heads, query_length, key_length)
return values | [
"def",
"compute_bias",
"(",
"self",
",",
"query_length",
",",
"key_length",
")",
":",
"context_position",
"=",
"torch",
".",
"arange",
"(",
"query_length",
",",
"dtype",
"=",
"torch",
".",
"long",
")",
"[",
":",
",",
"None",
"]",
"memory_position",
"=",
"torch",
".",
"arange",
"(",
"key_length",
",",
"dtype",
"=",
"torch",
".",
"long",
")",
"[",
"None",
",",
":",
"]",
"relative_position",
"=",
"memory_position",
"-",
"context_position",
"# shape (query_length, key_length)",
"relative_position_bucket",
"=",
"self",
".",
"_relative_position_bucket",
"(",
"relative_position",
",",
"# shape (query_length, key_length)",
"bidirectional",
"=",
"(",
"not",
"self",
".",
"is_decoder",
")",
",",
"num_buckets",
"=",
"self",
".",
"relative_attention_num_buckets",
",",
")",
"relative_position_bucket",
"=",
"relative_position_bucket",
".",
"to",
"(",
"self",
".",
"relative_attention_bias",
".",
"weight",
".",
"device",
")",
"values",
"=",
"self",
".",
"relative_attention_bias",
"(",
"relative_position_bucket",
")",
"# shape (query_length, key_length, num_heads)",
"values",
"=",
"values",
".",
"permute",
"(",
"[",
"2",
",",
"0",
",",
"1",
"]",
")",
".",
"unsqueeze",
"(",
"0",
")",
"# shape (1, num_heads, query_length, key_length)",
"return",
"values"
] | [
390,
4
] | [
403,
21
] | python | en | ['en', 'en', 'nl'] | True |
T5Attention.forward | (
self,
hidden_states,
mask=None,
key_value_states=None,
position_bias=None,
past_key_value=None,
layer_head_mask=None,
query_length=None,
use_cache=False,
output_attentions=False,
) |
Self-attention (if key_value_states is None) or attention over source sentence (provided by key_value_states).
|
Self-attention (if key_value_states is None) or attention over source sentence (provided by key_value_states).
| def forward(
self,
hidden_states,
mask=None,
key_value_states=None,
position_bias=None,
past_key_value=None,
layer_head_mask=None,
query_length=None,
use_cache=False,
output_attentions=False,
):
"""
Self-attention (if key_value_states is None) or attention over source sentence (provided by key_value_states).
"""
# Input is (batch_size, seq_length, dim)
# Mask is (batch_size, key_length) (non-causal) or (batch_size, key_length, key_length)
# past_key_value[0] is (batch_size, n_heads, q_len - 1, dim_per_head)
batch_size, seq_length = hidden_states.shape[:2]
real_seq_length = seq_length
if past_key_value is not None:
assert (
len(past_key_value) == 2
), "past_key_value should have 2 past states: keys and values. Got {} past states".format(
len(past_key_value)
)
real_seq_length += past_key_value[0].shape[2] if query_length is None else query_length
key_length = real_seq_length if key_value_states is None else key_value_states.shape[1]
def shape(states):
""" projection """
return states.view(batch_size, -1, self.n_heads, self.key_value_proj_dim).transpose(1, 2)
def unshape(states):
""" reshape """
return states.transpose(1, 2).contiguous().view(batch_size, -1, self.inner_dim)
def project(hidden_states, proj_layer, key_value_states, past_key_value):
""" projects hidden states correctly to key/query states """
if key_value_states is None:
# self-attn
# (batch_size, n_heads, seq_length, dim_per_head)
hidden_states = shape(proj_layer(hidden_states))
elif past_key_value is None:
# cross-attn
# (batch_size, n_heads, seq_length, dim_per_head)
hidden_states = shape(proj_layer(key_value_states))
if past_key_value is not None:
if key_value_states is None:
# self-attn
# (batch_size, n_heads, key_length, dim_per_head)
hidden_states = torch.cat([past_key_value, hidden_states], dim=2)
else:
# cross-attn
hidden_states = past_key_value
return hidden_states
# get query states
query_states = shape(self.q(hidden_states)) # (batch_size, n_heads, seq_length, dim_per_head)
# get key/value states
key_states = project(
hidden_states, self.k, key_value_states, past_key_value[0] if past_key_value is not None else None
)
value_states = project(
hidden_states, self.v, key_value_states, past_key_value[1] if past_key_value is not None else None
)
# compute scores
scores = torch.matmul(
query_states, key_states.transpose(3, 2)
) # equivalent of torch.einsum("bnqd,bnkd->bnqk", query_states, key_states), compatible with onnx op>9
if position_bias is None:
if not self.has_relative_attention_bias:
position_bias = torch.zeros(
(1, self.n_heads, real_seq_length, key_length), device=scores.device, dtype=scores.dtype
)
else:
position_bias = self.compute_bias(real_seq_length, key_length)
# if key and values are already calculated
# we want only the last query position bias
if past_key_value is not None:
position_bias = position_bias[:, :, -seq_length:, :]
if mask is not None:
position_bias = position_bias + mask # (batch_size, n_heads, seq_length, key_length)
scores += position_bias
attn_weights = F.softmax(scores.float(), dim=-1).type_as(
scores
) # (batch_size, n_heads, seq_length, key_length)
attn_weights = F.dropout(
attn_weights, p=self.dropout, training=self.training
) # (batch_size, n_heads, seq_length, key_length)
# Mask heads if we want to
if layer_head_mask is not None:
attn_weights = attn_weights * layer_head_mask
attn_output = unshape(torch.matmul(attn_weights, value_states)) # (batch_size, seq_length, dim)
attn_output = self.o(attn_output)
present_key_value_state = (key_states, value_states) if (self.is_decoder and use_cache) else None
outputs = (attn_output,) + (present_key_value_state,) + (position_bias,)
if output_attentions:
outputs = outputs + (attn_weights,)
return outputs | [
"def",
"forward",
"(",
"self",
",",
"hidden_states",
",",
"mask",
"=",
"None",
",",
"key_value_states",
"=",
"None",
",",
"position_bias",
"=",
"None",
",",
"past_key_value",
"=",
"None",
",",
"layer_head_mask",
"=",
"None",
",",
"query_length",
"=",
"None",
",",
"use_cache",
"=",
"False",
",",
"output_attentions",
"=",
"False",
",",
")",
":",
"# Input is (batch_size, seq_length, dim)",
"# Mask is (batch_size, key_length) (non-causal) or (batch_size, key_length, key_length)",
"# past_key_value[0] is (batch_size, n_heads, q_len - 1, dim_per_head)",
"batch_size",
",",
"seq_length",
"=",
"hidden_states",
".",
"shape",
"[",
":",
"2",
"]",
"real_seq_length",
"=",
"seq_length",
"if",
"past_key_value",
"is",
"not",
"None",
":",
"assert",
"(",
"len",
"(",
"past_key_value",
")",
"==",
"2",
")",
",",
"\"past_key_value should have 2 past states: keys and values. Got {} past states\"",
".",
"format",
"(",
"len",
"(",
"past_key_value",
")",
")",
"real_seq_length",
"+=",
"past_key_value",
"[",
"0",
"]",
".",
"shape",
"[",
"2",
"]",
"if",
"query_length",
"is",
"None",
"else",
"query_length",
"key_length",
"=",
"real_seq_length",
"if",
"key_value_states",
"is",
"None",
"else",
"key_value_states",
".",
"shape",
"[",
"1",
"]",
"def",
"shape",
"(",
"states",
")",
":",
"\"\"\" projection \"\"\"",
"return",
"states",
".",
"view",
"(",
"batch_size",
",",
"-",
"1",
",",
"self",
".",
"n_heads",
",",
"self",
".",
"key_value_proj_dim",
")",
".",
"transpose",
"(",
"1",
",",
"2",
")",
"def",
"unshape",
"(",
"states",
")",
":",
"\"\"\" reshape \"\"\"",
"return",
"states",
".",
"transpose",
"(",
"1",
",",
"2",
")",
".",
"contiguous",
"(",
")",
".",
"view",
"(",
"batch_size",
",",
"-",
"1",
",",
"self",
".",
"inner_dim",
")",
"def",
"project",
"(",
"hidden_states",
",",
"proj_layer",
",",
"key_value_states",
",",
"past_key_value",
")",
":",
"\"\"\" projects hidden states correctly to key/query states \"\"\"",
"if",
"key_value_states",
"is",
"None",
":",
"# self-attn",
"# (batch_size, n_heads, seq_length, dim_per_head)",
"hidden_states",
"=",
"shape",
"(",
"proj_layer",
"(",
"hidden_states",
")",
")",
"elif",
"past_key_value",
"is",
"None",
":",
"# cross-attn",
"# (batch_size, n_heads, seq_length, dim_per_head)",
"hidden_states",
"=",
"shape",
"(",
"proj_layer",
"(",
"key_value_states",
")",
")",
"if",
"past_key_value",
"is",
"not",
"None",
":",
"if",
"key_value_states",
"is",
"None",
":",
"# self-attn",
"# (batch_size, n_heads, key_length, dim_per_head)",
"hidden_states",
"=",
"torch",
".",
"cat",
"(",
"[",
"past_key_value",
",",
"hidden_states",
"]",
",",
"dim",
"=",
"2",
")",
"else",
":",
"# cross-attn",
"hidden_states",
"=",
"past_key_value",
"return",
"hidden_states",
"# get query states",
"query_states",
"=",
"shape",
"(",
"self",
".",
"q",
"(",
"hidden_states",
")",
")",
"# (batch_size, n_heads, seq_length, dim_per_head)",
"# get key/value states",
"key_states",
"=",
"project",
"(",
"hidden_states",
",",
"self",
".",
"k",
",",
"key_value_states",
",",
"past_key_value",
"[",
"0",
"]",
"if",
"past_key_value",
"is",
"not",
"None",
"else",
"None",
")",
"value_states",
"=",
"project",
"(",
"hidden_states",
",",
"self",
".",
"v",
",",
"key_value_states",
",",
"past_key_value",
"[",
"1",
"]",
"if",
"past_key_value",
"is",
"not",
"None",
"else",
"None",
")",
"# compute scores",
"scores",
"=",
"torch",
".",
"matmul",
"(",
"query_states",
",",
"key_states",
".",
"transpose",
"(",
"3",
",",
"2",
")",
")",
"# equivalent of torch.einsum(\"bnqd,bnkd->bnqk\", query_states, key_states), compatible with onnx op>9",
"if",
"position_bias",
"is",
"None",
":",
"if",
"not",
"self",
".",
"has_relative_attention_bias",
":",
"position_bias",
"=",
"torch",
".",
"zeros",
"(",
"(",
"1",
",",
"self",
".",
"n_heads",
",",
"real_seq_length",
",",
"key_length",
")",
",",
"device",
"=",
"scores",
".",
"device",
",",
"dtype",
"=",
"scores",
".",
"dtype",
")",
"else",
":",
"position_bias",
"=",
"self",
".",
"compute_bias",
"(",
"real_seq_length",
",",
"key_length",
")",
"# if key and values are already calculated",
"# we want only the last query position bias",
"if",
"past_key_value",
"is",
"not",
"None",
":",
"position_bias",
"=",
"position_bias",
"[",
":",
",",
":",
",",
"-",
"seq_length",
":",
",",
":",
"]",
"if",
"mask",
"is",
"not",
"None",
":",
"position_bias",
"=",
"position_bias",
"+",
"mask",
"# (batch_size, n_heads, seq_length, key_length)",
"scores",
"+=",
"position_bias",
"attn_weights",
"=",
"F",
".",
"softmax",
"(",
"scores",
".",
"float",
"(",
")",
",",
"dim",
"=",
"-",
"1",
")",
".",
"type_as",
"(",
"scores",
")",
"# (batch_size, n_heads, seq_length, key_length)",
"attn_weights",
"=",
"F",
".",
"dropout",
"(",
"attn_weights",
",",
"p",
"=",
"self",
".",
"dropout",
",",
"training",
"=",
"self",
".",
"training",
")",
"# (batch_size, n_heads, seq_length, key_length)",
"# Mask heads if we want to",
"if",
"layer_head_mask",
"is",
"not",
"None",
":",
"attn_weights",
"=",
"attn_weights",
"*",
"layer_head_mask",
"attn_output",
"=",
"unshape",
"(",
"torch",
".",
"matmul",
"(",
"attn_weights",
",",
"value_states",
")",
")",
"# (batch_size, seq_length, dim)",
"attn_output",
"=",
"self",
".",
"o",
"(",
"attn_output",
")",
"present_key_value_state",
"=",
"(",
"key_states",
",",
"value_states",
")",
"if",
"(",
"self",
".",
"is_decoder",
"and",
"use_cache",
")",
"else",
"None",
"outputs",
"=",
"(",
"attn_output",
",",
")",
"+",
"(",
"present_key_value_state",
",",
")",
"+",
"(",
"position_bias",
",",
")",
"if",
"output_attentions",
":",
"outputs",
"=",
"outputs",
"+",
"(",
"attn_weights",
",",
")",
"return",
"outputs"
] | [
405,
4
] | [
518,
22
] | python | en | ['en', 'error', 'th'] | False |
T5PreTrainedModel._init_weights | (self, module) | Initialize the weights | Initialize the weights | def _init_weights(self, module):
""" Initialize the weights """
factor = self.config.initializer_factor # Used for testing weights initialization
if isinstance(module, T5LayerNorm):
module.weight.data.fill_(factor * 1.0)
elif isinstance(module, (T5Model, T5ForConditionalGeneration, T5EncoderModel)):
# Mesh TensorFlow embeddings initialization
# See https://github.com/tensorflow/mesh/blob/fa19d69eafc9a482aff0b59ddd96b025c0cb207d/mesh_tensorflow/layers.py#L1624
module.shared.weight.data.normal_(mean=0.0, std=factor * 1.0)
elif isinstance(module, T5DenseReluDense):
# Mesh TensorFlow FF initialization
# See https://github.com/tensorflow/mesh/blob/master/mesh_tensorflow/transformer/transformer_layers.py#L56
# and https://github.com/tensorflow/mesh/blob/fa19d69eafc9a482aff0b59ddd96b025c0cb207d/mesh_tensorflow/layers.py#L89
module.wi.weight.data.normal_(mean=0.0, std=factor * ((self.config.d_model) ** -0.5))
if hasattr(module.wi, "bias") and module.wi.bias is not None:
module.wi.bias.data.zero_()
module.wo.weight.data.normal_(mean=0.0, std=factor * ((self.config.d_ff) ** -0.5))
if hasattr(module.wo, "bias") and module.wo.bias is not None:
module.wo.bias.data.zero_()
elif isinstance(module, T5DenseGatedGeluDense):
module.wi_0.weight.data.normal_(mean=0.0, std=factor * ((self.config.d_model) ** -0.5))
if hasattr(module.wi_0, "bias") and module.wi_0.bias is not None:
module.wi_0.bias.data.zero_()
module.wi_1.weight.data.normal_(mean=0.0, std=factor * ((self.config.d_model) ** -0.5))
if hasattr(module.wi_1, "bias") and module.wi_1.bias is not None:
module.wi_1.bias.data.zero_()
module.wo.weight.data.normal_(mean=0.0, std=factor * ((self.config.d_ff) ** -0.5))
if hasattr(module.wo, "bias") and module.wo.bias is not None:
module.wo.bias.data.zero_()
elif isinstance(module, T5Attention):
# Mesh TensorFlow attention initialization to avoid scaling before softmax
# See https://github.com/tensorflow/mesh/blob/fa19d69eafc9a482aff0b59ddd96b025c0cb207d/mesh_tensorflow/transformer/attention.py#L136
d_model = self.config.d_model
key_value_proj_dim = self.config.d_kv
n_heads = self.config.num_heads
module.q.weight.data.normal_(mean=0.0, std=factor * ((d_model * key_value_proj_dim) ** -0.5))
module.k.weight.data.normal_(mean=0.0, std=factor * (d_model ** -0.5))
module.v.weight.data.normal_(mean=0.0, std=factor * (d_model ** -0.5))
module.o.weight.data.normal_(mean=0.0, std=factor * ((n_heads * key_value_proj_dim) ** -0.5))
if module.has_relative_attention_bias:
module.relative_attention_bias.weight.data.normal_(mean=0.0, std=factor * ((d_model) ** -0.5)) | [
"def",
"_init_weights",
"(",
"self",
",",
"module",
")",
":",
"factor",
"=",
"self",
".",
"config",
".",
"initializer_factor",
"# Used for testing weights initialization",
"if",
"isinstance",
"(",
"module",
",",
"T5LayerNorm",
")",
":",
"module",
".",
"weight",
".",
"data",
".",
"fill_",
"(",
"factor",
"*",
"1.0",
")",
"elif",
"isinstance",
"(",
"module",
",",
"(",
"T5Model",
",",
"T5ForConditionalGeneration",
",",
"T5EncoderModel",
")",
")",
":",
"# Mesh TensorFlow embeddings initialization",
"# See https://github.com/tensorflow/mesh/blob/fa19d69eafc9a482aff0b59ddd96b025c0cb207d/mesh_tensorflow/layers.py#L1624",
"module",
".",
"shared",
".",
"weight",
".",
"data",
".",
"normal_",
"(",
"mean",
"=",
"0.0",
",",
"std",
"=",
"factor",
"*",
"1.0",
")",
"elif",
"isinstance",
"(",
"module",
",",
"T5DenseReluDense",
")",
":",
"# Mesh TensorFlow FF initialization",
"# See https://github.com/tensorflow/mesh/blob/master/mesh_tensorflow/transformer/transformer_layers.py#L56",
"# and https://github.com/tensorflow/mesh/blob/fa19d69eafc9a482aff0b59ddd96b025c0cb207d/mesh_tensorflow/layers.py#L89",
"module",
".",
"wi",
".",
"weight",
".",
"data",
".",
"normal_",
"(",
"mean",
"=",
"0.0",
",",
"std",
"=",
"factor",
"*",
"(",
"(",
"self",
".",
"config",
".",
"d_model",
")",
"**",
"-",
"0.5",
")",
")",
"if",
"hasattr",
"(",
"module",
".",
"wi",
",",
"\"bias\"",
")",
"and",
"module",
".",
"wi",
".",
"bias",
"is",
"not",
"None",
":",
"module",
".",
"wi",
".",
"bias",
".",
"data",
".",
"zero_",
"(",
")",
"module",
".",
"wo",
".",
"weight",
".",
"data",
".",
"normal_",
"(",
"mean",
"=",
"0.0",
",",
"std",
"=",
"factor",
"*",
"(",
"(",
"self",
".",
"config",
".",
"d_ff",
")",
"**",
"-",
"0.5",
")",
")",
"if",
"hasattr",
"(",
"module",
".",
"wo",
",",
"\"bias\"",
")",
"and",
"module",
".",
"wo",
".",
"bias",
"is",
"not",
"None",
":",
"module",
".",
"wo",
".",
"bias",
".",
"data",
".",
"zero_",
"(",
")",
"elif",
"isinstance",
"(",
"module",
",",
"T5DenseGatedGeluDense",
")",
":",
"module",
".",
"wi_0",
".",
"weight",
".",
"data",
".",
"normal_",
"(",
"mean",
"=",
"0.0",
",",
"std",
"=",
"factor",
"*",
"(",
"(",
"self",
".",
"config",
".",
"d_model",
")",
"**",
"-",
"0.5",
")",
")",
"if",
"hasattr",
"(",
"module",
".",
"wi_0",
",",
"\"bias\"",
")",
"and",
"module",
".",
"wi_0",
".",
"bias",
"is",
"not",
"None",
":",
"module",
".",
"wi_0",
".",
"bias",
".",
"data",
".",
"zero_",
"(",
")",
"module",
".",
"wi_1",
".",
"weight",
".",
"data",
".",
"normal_",
"(",
"mean",
"=",
"0.0",
",",
"std",
"=",
"factor",
"*",
"(",
"(",
"self",
".",
"config",
".",
"d_model",
")",
"**",
"-",
"0.5",
")",
")",
"if",
"hasattr",
"(",
"module",
".",
"wi_1",
",",
"\"bias\"",
")",
"and",
"module",
".",
"wi_1",
".",
"bias",
"is",
"not",
"None",
":",
"module",
".",
"wi_1",
".",
"bias",
".",
"data",
".",
"zero_",
"(",
")",
"module",
".",
"wo",
".",
"weight",
".",
"data",
".",
"normal_",
"(",
"mean",
"=",
"0.0",
",",
"std",
"=",
"factor",
"*",
"(",
"(",
"self",
".",
"config",
".",
"d_ff",
")",
"**",
"-",
"0.5",
")",
")",
"if",
"hasattr",
"(",
"module",
".",
"wo",
",",
"\"bias\"",
")",
"and",
"module",
".",
"wo",
".",
"bias",
"is",
"not",
"None",
":",
"module",
".",
"wo",
".",
"bias",
".",
"data",
".",
"zero_",
"(",
")",
"elif",
"isinstance",
"(",
"module",
",",
"T5Attention",
")",
":",
"# Mesh TensorFlow attention initialization to avoid scaling before softmax",
"# See https://github.com/tensorflow/mesh/blob/fa19d69eafc9a482aff0b59ddd96b025c0cb207d/mesh_tensorflow/transformer/attention.py#L136",
"d_model",
"=",
"self",
".",
"config",
".",
"d_model",
"key_value_proj_dim",
"=",
"self",
".",
"config",
".",
"d_kv",
"n_heads",
"=",
"self",
".",
"config",
".",
"num_heads",
"module",
".",
"q",
".",
"weight",
".",
"data",
".",
"normal_",
"(",
"mean",
"=",
"0.0",
",",
"std",
"=",
"factor",
"*",
"(",
"(",
"d_model",
"*",
"key_value_proj_dim",
")",
"**",
"-",
"0.5",
")",
")",
"module",
".",
"k",
".",
"weight",
".",
"data",
".",
"normal_",
"(",
"mean",
"=",
"0.0",
",",
"std",
"=",
"factor",
"*",
"(",
"d_model",
"**",
"-",
"0.5",
")",
")",
"module",
".",
"v",
".",
"weight",
".",
"data",
".",
"normal_",
"(",
"mean",
"=",
"0.0",
",",
"std",
"=",
"factor",
"*",
"(",
"d_model",
"**",
"-",
"0.5",
")",
")",
"module",
".",
"o",
".",
"weight",
".",
"data",
".",
"normal_",
"(",
"mean",
"=",
"0.0",
",",
"std",
"=",
"factor",
"*",
"(",
"(",
"n_heads",
"*",
"key_value_proj_dim",
")",
"**",
"-",
"0.5",
")",
")",
"if",
"module",
".",
"has_relative_attention_bias",
":",
"module",
".",
"relative_attention_bias",
".",
"weight",
".",
"data",
".",
"normal_",
"(",
"mean",
"=",
"0.0",
",",
"std",
"=",
"factor",
"*",
"(",
"(",
"d_model",
")",
"**",
"-",
"0.5",
")",
")"
] | [
719,
4
] | [
759,
110
] | python | en | ['en', 'en', 'en'] | True |
buy_doge | () | doge_price = binance_client.get_symbol_ticker(symbol="DOGEEUR")
doge_amount = int(config.get("CONFIG", "SPEND")) / float(doge_price["price"])
print(round(doge_amount, 4))
print(round(doge_amount, 4) * float(doge_price["price"])) | doge_price = binance_client.get_symbol_ticker(symbol="DOGEEUR")
doge_amount = int(config.get("CONFIG", "SPEND")) / float(doge_price["price"])
print(round(doge_amount, 4))
print(round(doge_amount, 4) * float(doge_price["price"])) | def buy_doge():
"""doge_price = binance_client.get_symbol_ticker(symbol="DOGEEUR")
doge_amount = int(config.get("CONFIG", "SPEND")) / float(doge_price["price"])
print(round(doge_amount, 4))
print(round(doge_amount, 4) * float(doge_price["price"]))"""
try:
binance_client.create_test_order(
symbol='DOGEEUR',
side=SIDE_BUY,
type=ORDER_TYPE_MARKET,
quantity=1000)
except BinanceAPIException as e:
print(e.status_code)
print(e.message)
except BinanceOrderException as e:
print(e) | [
"def",
"buy_doge",
"(",
")",
":",
"try",
":",
"binance_client",
".",
"create_test_order",
"(",
"symbol",
"=",
"'DOGEEUR'",
",",
"side",
"=",
"SIDE_BUY",
",",
"type",
"=",
"ORDER_TYPE_MARKET",
",",
"quantity",
"=",
"1000",
")",
"except",
"BinanceAPIException",
"as",
"e",
":",
"print",
"(",
"e",
".",
"status_code",
")",
"print",
"(",
"e",
".",
"message",
")",
"except",
"BinanceOrderException",
"as",
"e",
":",
"print",
"(",
"e",
")"
] | [
116,
0
] | [
131,
16
] | python | de | ['en', 'de', 'nl'] | False |
main | () | if not os.path.isfile("settings/handles.txt"):
first_time()
with open("settings/handles.txt", "r") as file:
handles = file.read().splitlines()
for i in range(len(handles)):
doge_mentioned = check_tweets_for_doge(handles[i])
if doge_mentioned:
buy_doge() | if not os.path.isfile("settings/handles.txt"):
first_time() | def main():
"""if not os.path.isfile("settings/handles.txt"):
first_time()
with open("settings/handles.txt", "r") as file:
handles = file.read().splitlines()
for i in range(len(handles)):
doge_mentioned = check_tweets_for_doge(handles[i])
if doge_mentioned:
buy_doge()"""
buy_doge() | [
"def",
"main",
"(",
")",
":",
"buy_doge",
"(",
")"
] | [
134,
0
] | [
146,
14
] | python | en | ['en', 'en', 'en'] | True |
setup_platform | (hass, config, add_entities, discovery_info=None) | Set up mFi sensors. | Set up mFi sensors. | def setup_platform(hass, config, add_entities, discovery_info=None):
"""Set up mFi sensors."""
host = config.get(CONF_HOST)
username = config.get(CONF_USERNAME)
password = config.get(CONF_PASSWORD)
use_tls = config[CONF_SSL]
verify_tls = config.get(CONF_VERIFY_SSL)
default_port = 6443 if use_tls else 6080
port = int(config.get(CONF_PORT, default_port))
try:
client = MFiClient(
host, username, password, port=port, use_tls=use_tls, verify=verify_tls
)
except (FailedToLogin, requests.exceptions.ConnectionError) as ex:
_LOGGER.error("Unable to connect to mFi: %s", str(ex))
return False
add_entities(
MfiSwitch(port)
for device in client.get_devices()
for port in device.ports.values()
if port.model in SWITCH_MODELS
) | [
"def",
"setup_platform",
"(",
"hass",
",",
"config",
",",
"add_entities",
",",
"discovery_info",
"=",
"None",
")",
":",
"host",
"=",
"config",
".",
"get",
"(",
"CONF_HOST",
")",
"username",
"=",
"config",
".",
"get",
"(",
"CONF_USERNAME",
")",
"password",
"=",
"config",
".",
"get",
"(",
"CONF_PASSWORD",
")",
"use_tls",
"=",
"config",
"[",
"CONF_SSL",
"]",
"verify_tls",
"=",
"config",
".",
"get",
"(",
"CONF_VERIFY_SSL",
")",
"default_port",
"=",
"6443",
"if",
"use_tls",
"else",
"6080",
"port",
"=",
"int",
"(",
"config",
".",
"get",
"(",
"CONF_PORT",
",",
"default_port",
")",
")",
"try",
":",
"client",
"=",
"MFiClient",
"(",
"host",
",",
"username",
",",
"password",
",",
"port",
"=",
"port",
",",
"use_tls",
"=",
"use_tls",
",",
"verify",
"=",
"verify_tls",
")",
"except",
"(",
"FailedToLogin",
",",
"requests",
".",
"exceptions",
".",
"ConnectionError",
")",
"as",
"ex",
":",
"_LOGGER",
".",
"error",
"(",
"\"Unable to connect to mFi: %s\"",
",",
"str",
"(",
"ex",
")",
")",
"return",
"False",
"add_entities",
"(",
"MfiSwitch",
"(",
"port",
")",
"for",
"device",
"in",
"client",
".",
"get_devices",
"(",
")",
"for",
"port",
"in",
"device",
".",
"ports",
".",
"values",
"(",
")",
"if",
"port",
".",
"model",
"in",
"SWITCH_MODELS",
")"
] | [
37,
0
] | [
60,
5
] | python | en | ['en', 'bg', 'en'] | True |
MfiSwitch.__init__ | (self, port) | Initialize the mFi device. | Initialize the mFi device. | def __init__(self, port):
"""Initialize the mFi device."""
self._port = port
self._target_state = None | [
"def",
"__init__",
"(",
"self",
",",
"port",
")",
":",
"self",
".",
"_port",
"=",
"port",
"self",
".",
"_target_state",
"=",
"None"
] | [
66,
4
] | [
69,
33
] | python | en | ['en', 'en', 'en'] | True |
MfiSwitch.unique_id | (self) | Return the unique ID of the device. | Return the unique ID of the device. | def unique_id(self):
"""Return the unique ID of the device."""
return self._port.ident | [
"def",
"unique_id",
"(",
"self",
")",
":",
"return",
"self",
".",
"_port",
".",
"ident"
] | [
72,
4
] | [
74,
31
] | python | en | ['en', 'en', 'en'] | True |
MfiSwitch.name | (self) | Return the name of the device. | Return the name of the device. | def name(self):
"""Return the name of the device."""
return self._port.label | [
"def",
"name",
"(",
"self",
")",
":",
"return",
"self",
".",
"_port",
".",
"label"
] | [
77,
4
] | [
79,
31
] | python | en | ['en', 'en', 'en'] | True |
MfiSwitch.is_on | (self) | Return true if the device is on. | Return true if the device is on. | def is_on(self):
"""Return true if the device is on."""
return self._port.output | [
"def",
"is_on",
"(",
"self",
")",
":",
"return",
"self",
".",
"_port",
".",
"output"
] | [
82,
4
] | [
84,
32
] | python | en | ['en', 'en', 'en'] | True |
MfiSwitch.update | (self) | Get the latest state and update the state. | Get the latest state and update the state. | def update(self):
"""Get the latest state and update the state."""
self._port.refresh()
if self._target_state is not None:
self._port.data["output"] = float(self._target_state)
self._target_state = None | [
"def",
"update",
"(",
"self",
")",
":",
"self",
".",
"_port",
".",
"refresh",
"(",
")",
"if",
"self",
".",
"_target_state",
"is",
"not",
"None",
":",
"self",
".",
"_port",
".",
"data",
"[",
"\"output\"",
"]",
"=",
"float",
"(",
"self",
".",
"_target_state",
")",
"self",
".",
"_target_state",
"=",
"None"
] | [
86,
4
] | [
91,
37
] | python | en | ['en', 'en', 'en'] | True |
MfiSwitch.turn_on | (self, **kwargs) | Turn the switch on. | Turn the switch on. | def turn_on(self, **kwargs):
"""Turn the switch on."""
self._port.control(True)
self._target_state = True | [
"def",
"turn_on",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"_port",
".",
"control",
"(",
"True",
")",
"self",
".",
"_target_state",
"=",
"True"
] | [
93,
4
] | [
96,
33
] | python | en | ['en', 'en', 'en'] | True |
MfiSwitch.turn_off | (self, **kwargs) | Turn the switch off. | Turn the switch off. | def turn_off(self, **kwargs):
"""Turn the switch off."""
self._port.control(False)
self._target_state = False | [
"def",
"turn_off",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"_port",
".",
"control",
"(",
"False",
")",
"self",
".",
"_target_state",
"=",
"False"
] | [
98,
4
] | [
101,
34
] | python | en | ['en', 'en', 'en'] | True |
MfiSwitch.current_power_w | (self) | Return the current power usage in W. | Return the current power usage in W. | def current_power_w(self):
"""Return the current power usage in W."""
return int(self._port.data.get("active_pwr", 0)) | [
"def",
"current_power_w",
"(",
"self",
")",
":",
"return",
"int",
"(",
"self",
".",
"_port",
".",
"data",
".",
"get",
"(",
"\"active_pwr\"",
",",
"0",
")",
")"
] | [
104,
4
] | [
106,
56
] | python | en | ['en', 'en', 'en'] | True |
MfiSwitch.device_state_attributes | (self) | Return the state attributes for the device. | Return the state attributes for the device. | def device_state_attributes(self):
"""Return the state attributes for the device."""
return {
"volts": round(self._port.data.get("v_rms", 0), 1),
"amps": round(self._port.data.get("i_rms", 0), 1),
} | [
"def",
"device_state_attributes",
"(",
"self",
")",
":",
"return",
"{",
"\"volts\"",
":",
"round",
"(",
"self",
".",
"_port",
".",
"data",
".",
"get",
"(",
"\"v_rms\"",
",",
"0",
")",
",",
"1",
")",
",",
"\"amps\"",
":",
"round",
"(",
"self",
".",
"_port",
".",
"data",
".",
"get",
"(",
"\"i_rms\"",
",",
"0",
")",
",",
"1",
")",
",",
"}"
] | [
109,
4
] | [
114,
9
] | python | en | ['en', 'en', 'en'] | True |
test_has_location_with_invalid_states | () | Set up the tests. | Set up the tests. | def test_has_location_with_invalid_states():
"""Set up the tests."""
for state in (None, 1, "hello", object):
assert not location.has_location(state) | [
"def",
"test_has_location_with_invalid_states",
"(",
")",
":",
"for",
"state",
"in",
"(",
"None",
",",
"1",
",",
"\"hello\"",
",",
"object",
")",
":",
"assert",
"not",
"location",
".",
"has_location",
"(",
"state",
")"
] | [
6,
0
] | [
9,
47
] | python | en | ['en', 'en', 'en'] | True |
test_has_location_with_states_with_invalid_locations | () | Set up the tests. | Set up the tests. | def test_has_location_with_states_with_invalid_locations():
"""Set up the tests."""
state = State(
"hello.world", "invalid", {ATTR_LATITUDE: "no number", ATTR_LONGITUDE: 123.12}
)
assert not location.has_location(state) | [
"def",
"test_has_location_with_states_with_invalid_locations",
"(",
")",
":",
"state",
"=",
"State",
"(",
"\"hello.world\"",
",",
"\"invalid\"",
",",
"{",
"ATTR_LATITUDE",
":",
"\"no number\"",
",",
"ATTR_LONGITUDE",
":",
"123.12",
"}",
")",
"assert",
"not",
"location",
".",
"has_location",
"(",
"state",
")"
] | [
12,
0
] | [
17,
43
] | python | en | ['en', 'en', 'en'] | True |
test_has_location_with_states_with_valid_location | () | Set up the tests. | Set up the tests. | def test_has_location_with_states_with_valid_location():
"""Set up the tests."""
state = State(
"hello.world", "invalid", {ATTR_LATITUDE: 123.12, ATTR_LONGITUDE: 123.12}
)
assert location.has_location(state) | [
"def",
"test_has_location_with_states_with_valid_location",
"(",
")",
":",
"state",
"=",
"State",
"(",
"\"hello.world\"",
",",
"\"invalid\"",
",",
"{",
"ATTR_LATITUDE",
":",
"123.12",
",",
"ATTR_LONGITUDE",
":",
"123.12",
"}",
")",
"assert",
"location",
".",
"has_location",
"(",
"state",
")"
] | [
20,
0
] | [
25,
39
] | python | en | ['en', 'en', 'en'] | True |
test_closest_with_no_states_with_location | () | Set up the tests. | Set up the tests. | def test_closest_with_no_states_with_location():
"""Set up the tests."""
state = State("light.test", "on")
state2 = State(
"light.test", "on", {ATTR_LATITUDE: "invalid", ATTR_LONGITUDE: 123.45}
)
state3 = State("light.test", "on", {ATTR_LONGITUDE: 123.45})
assert location.closest(123.45, 123.45, [state, state2, state3]) is None | [
"def",
"test_closest_with_no_states_with_location",
"(",
")",
":",
"state",
"=",
"State",
"(",
"\"light.test\"",
",",
"\"on\"",
")",
"state2",
"=",
"State",
"(",
"\"light.test\"",
",",
"\"on\"",
",",
"{",
"ATTR_LATITUDE",
":",
"\"invalid\"",
",",
"ATTR_LONGITUDE",
":",
"123.45",
"}",
")",
"state3",
"=",
"State",
"(",
"\"light.test\"",
",",
"\"on\"",
",",
"{",
"ATTR_LONGITUDE",
":",
"123.45",
"}",
")",
"assert",
"location",
".",
"closest",
"(",
"123.45",
",",
"123.45",
",",
"[",
"state",
",",
"state2",
",",
"state3",
"]",
")",
"is",
"None"
] | [
28,
0
] | [
36,
76
] | 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.