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 |
---|---|---|---|---|---|---|---|---|---|---|---|
get_image_file | (image_file_name: str) | Get the image file.
Returns:
None.
| Get the image file. | def get_image_file(image_file_name: str):
"""Get the image file.
Returns:
None.
"""
master_details = redis_controller.get_master_details()
return master_details["image_files"].get(image_file_name, {}) | [
"def",
"get_image_file",
"(",
"image_file_name",
":",
"str",
")",
":",
"master_details",
"=",
"redis_controller",
".",
"get_master_details",
"(",
")",
"return",
"master_details",
"[",
"\"image_files\"",
"]",
".",
"get",
"(",
"image_file_name",
",",
"{",
"}",
")"
] | [
33,
0
] | [
41,
65
] | python | en | ['en', 'en', 'en'] | True |
create_image_file | (**kwargs) | Create a image file.
Returns:
None.
| Create a image file. | def create_image_file(**kwargs):
"""Create a image file.
Returns:
None.
"""
image_file_details = kwargs["json_dict"]
with redis_controller.lock(name="lock:master_details"):
master_details = redis_controller.get_master_details()
master_details["image_files"][image_file_details["name"]] = image_file_details
redis_controller.set_master_details(master_details=master_details)
return {} | [
"def",
"create_image_file",
"(",
"*",
"*",
"kwargs",
")",
":",
"image_file_details",
"=",
"kwargs",
"[",
"\"json_dict\"",
"]",
"with",
"redis_controller",
".",
"lock",
"(",
"name",
"=",
"\"lock:master_details\"",
")",
":",
"master_details",
"=",
"redis_controller",
".",
"get_master_details",
"(",
")",
"master_details",
"[",
"\"image_files\"",
"]",
"[",
"image_file_details",
"[",
"\"name\"",
"]",
"]",
"=",
"image_file_details",
"redis_controller",
".",
"set_master_details",
"(",
"master_details",
"=",
"master_details",
")",
"return",
"{",
"}"
] | [
46,
0
] | [
58,
13
] | python | en | ['en', 'sm', 'en'] | True |
iter_manifests | () | Iterate over all available manifests. | Iterate over all available manifests. | def iter_manifests():
"""Iterate over all available manifests."""
manifests = [
json.loads(fil.read_text()) for fil in component_dir.glob("*/manifest.json")
]
return sorted(manifests, key=lambda man: man["domain"]) | [
"def",
"iter_manifests",
"(",
")",
":",
"manifests",
"=",
"[",
"json",
".",
"loads",
"(",
"fil",
".",
"read_text",
"(",
")",
")",
"for",
"fil",
"in",
"component_dir",
".",
"glob",
"(",
"\"*/manifest.json\"",
")",
"]",
"return",
"sorted",
"(",
"manifests",
",",
"key",
"=",
"lambda",
"man",
":",
"man",
"[",
"\"domain\"",
"]",
")"
] | [
7,
0
] | [
12,
59
] | python | en | ['en', 'en', 'en'] | True |
TFAttention.causal_attention_mask | (nd, ns) |
1's in the lower triangle, counting from the lower right corner. Same as tf.matrix_band_part(tf.ones([nd, ns]),
-1, ns-nd), but doesn't produce garbage on TPUs.
|
1's in the lower triangle, counting from the lower right corner. Same as tf.matrix_band_part(tf.ones([nd, ns]),
-1, ns-nd), but doesn't produce garbage on TPUs.
| def causal_attention_mask(nd, ns):
"""
1's in the lower triangle, counting from the lower right corner. Same as tf.matrix_band_part(tf.ones([nd, ns]),
-1, ns-nd), but doesn't produce garbage on TPUs.
"""
i = tf.range(nd)[:, None]
j = tf.range(ns)
m = i >= j - ns + nd
return m | [
"def",
"causal_attention_mask",
"(",
"nd",
",",
"ns",
")",
":",
"i",
"=",
"tf",
".",
"range",
"(",
"nd",
")",
"[",
":",
",",
"None",
"]",
"j",
"=",
"tf",
".",
"range",
"(",
"ns",
")",
"m",
"=",
"i",
">=",
"j",
"-",
"ns",
"+",
"nd",
"return",
"m"
] | [
84,
4
] | [
92,
16
] | python | en | ['en', 'error', 'th'] | False |
setup_platform | (hass, config, add_entities, discovery_info=None) | Set up the EcoNet water heaters. | Set up the EcoNet water heaters. | def setup_platform(hass, config, add_entities, discovery_info=None):
"""Set up the EcoNet water heaters."""
hass.data[ECONET_DATA] = {}
hass.data[ECONET_DATA]["water_heaters"] = []
username = config.get(CONF_USERNAME)
password = config.get(CONF_PASSWORD)
econet = PyEcoNet(username, password)
water_heaters = econet.get_water_heaters()
hass_water_heaters = [
EcoNetWaterHeater(water_heater) for water_heater in water_heaters
]
add_entities(hass_water_heaters)
hass.data[ECONET_DATA]["water_heaters"].extend(hass_water_heaters)
def service_handle(service):
"""Handle the service calls."""
entity_ids = service.data.get("entity_id")
all_heaters = hass.data[ECONET_DATA]["water_heaters"]
_heaters = [
x for x in all_heaters if not entity_ids or x.entity_id in entity_ids
]
for _water_heater in _heaters:
if service.service == SERVICE_ADD_VACATION:
start = service.data.get(ATTR_START_DATE)
end = service.data.get(ATTR_END_DATE)
_water_heater.add_vacation(start, end)
if service.service == SERVICE_DELETE_VACATION:
for vacation in _water_heater.water_heater.vacations:
vacation.delete()
_water_heater.schedule_update_ha_state(True)
hass.services.register(
DOMAIN, SERVICE_ADD_VACATION, service_handle, schema=ADD_VACATION_SCHEMA
)
hass.services.register(
DOMAIN, SERVICE_DELETE_VACATION, service_handle, schema=DELETE_VACATION_SCHEMA
) | [
"def",
"setup_platform",
"(",
"hass",
",",
"config",
",",
"add_entities",
",",
"discovery_info",
"=",
"None",
")",
":",
"hass",
".",
"data",
"[",
"ECONET_DATA",
"]",
"=",
"{",
"}",
"hass",
".",
"data",
"[",
"ECONET_DATA",
"]",
"[",
"\"water_heaters\"",
"]",
"=",
"[",
"]",
"username",
"=",
"config",
".",
"get",
"(",
"CONF_USERNAME",
")",
"password",
"=",
"config",
".",
"get",
"(",
"CONF_PASSWORD",
")",
"econet",
"=",
"PyEcoNet",
"(",
"username",
",",
"password",
")",
"water_heaters",
"=",
"econet",
".",
"get_water_heaters",
"(",
")",
"hass_water_heaters",
"=",
"[",
"EcoNetWaterHeater",
"(",
"water_heater",
")",
"for",
"water_heater",
"in",
"water_heaters",
"]",
"add_entities",
"(",
"hass_water_heaters",
")",
"hass",
".",
"data",
"[",
"ECONET_DATA",
"]",
"[",
"\"water_heaters\"",
"]",
".",
"extend",
"(",
"hass_water_heaters",
")",
"def",
"service_handle",
"(",
"service",
")",
":",
"\"\"\"Handle the service calls.\"\"\"",
"entity_ids",
"=",
"service",
".",
"data",
".",
"get",
"(",
"\"entity_id\"",
")",
"all_heaters",
"=",
"hass",
".",
"data",
"[",
"ECONET_DATA",
"]",
"[",
"\"water_heaters\"",
"]",
"_heaters",
"=",
"[",
"x",
"for",
"x",
"in",
"all_heaters",
"if",
"not",
"entity_ids",
"or",
"x",
".",
"entity_id",
"in",
"entity_ids",
"]",
"for",
"_water_heater",
"in",
"_heaters",
":",
"if",
"service",
".",
"service",
"==",
"SERVICE_ADD_VACATION",
":",
"start",
"=",
"service",
".",
"data",
".",
"get",
"(",
"ATTR_START_DATE",
")",
"end",
"=",
"service",
".",
"data",
".",
"get",
"(",
"ATTR_END_DATE",
")",
"_water_heater",
".",
"add_vacation",
"(",
"start",
",",
"end",
")",
"if",
"service",
".",
"service",
"==",
"SERVICE_DELETE_VACATION",
":",
"for",
"vacation",
"in",
"_water_heater",
".",
"water_heater",
".",
"vacations",
":",
"vacation",
".",
"delete",
"(",
")",
"_water_heater",
".",
"schedule_update_ha_state",
"(",
"True",
")",
"hass",
".",
"services",
".",
"register",
"(",
"DOMAIN",
",",
"SERVICE_ADD_VACATION",
",",
"service_handle",
",",
"schema",
"=",
"ADD_VACATION_SCHEMA",
")",
"hass",
".",
"services",
".",
"register",
"(",
"DOMAIN",
",",
"SERVICE_DELETE_VACATION",
",",
"service_handle",
",",
"schema",
"=",
"DELETE_VACATION_SCHEMA",
")"
] | [
77,
0
] | [
119,
5
] | python | en | ['en', 'en', 'en'] | True |
EcoNetWaterHeater.__init__ | (self, water_heater) | Initialize the water heater. | Initialize the water heater. | def __init__(self, water_heater):
"""Initialize the water heater."""
self.water_heater = water_heater
self.supported_modes = self.water_heater.supported_modes
self.econet_state_to_ha = {}
self.ha_state_to_econet = {}
for mode in ECONET_STATE_TO_HA:
if mode in self.supported_modes:
self.econet_state_to_ha[mode] = ECONET_STATE_TO_HA.get(mode)
for key, value in self.econet_state_to_ha.items():
self.ha_state_to_econet[value] = key
for mode in self.supported_modes:
if mode not in ECONET_STATE_TO_HA:
error = f"Invalid operation mode mapping. {mode} doesn't map. Please report this."
_LOGGER.error(error) | [
"def",
"__init__",
"(",
"self",
",",
"water_heater",
")",
":",
"self",
".",
"water_heater",
"=",
"water_heater",
"self",
".",
"supported_modes",
"=",
"self",
".",
"water_heater",
".",
"supported_modes",
"self",
".",
"econet_state_to_ha",
"=",
"{",
"}",
"self",
".",
"ha_state_to_econet",
"=",
"{",
"}",
"for",
"mode",
"in",
"ECONET_STATE_TO_HA",
":",
"if",
"mode",
"in",
"self",
".",
"supported_modes",
":",
"self",
".",
"econet_state_to_ha",
"[",
"mode",
"]",
"=",
"ECONET_STATE_TO_HA",
".",
"get",
"(",
"mode",
")",
"for",
"key",
",",
"value",
"in",
"self",
".",
"econet_state_to_ha",
".",
"items",
"(",
")",
":",
"self",
".",
"ha_state_to_econet",
"[",
"value",
"]",
"=",
"key",
"for",
"mode",
"in",
"self",
".",
"supported_modes",
":",
"if",
"mode",
"not",
"in",
"ECONET_STATE_TO_HA",
":",
"error",
"=",
"f\"Invalid operation mode mapping. {mode} doesn't map. Please report this.\"",
"_LOGGER",
".",
"error",
"(",
"error",
")"
] | [
125,
4
] | [
139,
36
] | python | en | ['en', 'en', 'en'] | True |
EcoNetWaterHeater.name | (self) | Return the device name. | Return the device name. | def name(self):
"""Return the device name."""
return self.water_heater.name | [
"def",
"name",
"(",
"self",
")",
":",
"return",
"self",
".",
"water_heater",
".",
"name"
] | [
142,
4
] | [
144,
37
] | python | en | ['en', 'en', 'en'] | True |
EcoNetWaterHeater.available | (self) | Return if the the device is online or not. | Return if the the device is online or not. | def available(self):
"""Return if the the device is online or not."""
return self.water_heater.is_connected | [
"def",
"available",
"(",
"self",
")",
":",
"return",
"self",
".",
"water_heater",
".",
"is_connected"
] | [
147,
4
] | [
149,
45
] | python | en | ['en', 'en', 'en'] | True |
EcoNetWaterHeater.temperature_unit | (self) | Return the unit of measurement. | Return the unit of measurement. | def temperature_unit(self):
"""Return the unit of measurement."""
return TEMP_FAHRENHEIT | [
"def",
"temperature_unit",
"(",
"self",
")",
":",
"return",
"TEMP_FAHRENHEIT"
] | [
152,
4
] | [
154,
30
] | python | en | ['en', 'la', 'en'] | True |
EcoNetWaterHeater.device_state_attributes | (self) | Return the optional device state attributes. | Return the optional device state attributes. | def device_state_attributes(self):
"""Return the optional device state attributes."""
data = {}
vacations = self.water_heater.get_vacations()
if vacations:
data[ATTR_VACATION_START] = vacations[0].start_date
data[ATTR_VACATION_END] = vacations[0].end_date
data[ATTR_ON_VACATION] = self.water_heater.is_on_vacation
todays_usage = self.water_heater.total_usage_for_today
if todays_usage:
data[ATTR_TODAYS_ENERGY_USAGE] = todays_usage
data[ATTR_IN_USE] = self.water_heater.in_use
if self.water_heater.lower_temp is not None:
data[ATTR_LOWER_TEMP] = round(self.water_heater.lower_temp, 2)
if self.water_heater.upper_temp is not None:
data[ATTR_UPPER_TEMP] = round(self.water_heater.upper_temp, 2)
if self.water_heater.is_enabled is not None:
data[ATTR_IS_ENABLED] = self.water_heater.is_enabled
return data | [
"def",
"device_state_attributes",
"(",
"self",
")",
":",
"data",
"=",
"{",
"}",
"vacations",
"=",
"self",
".",
"water_heater",
".",
"get_vacations",
"(",
")",
"if",
"vacations",
":",
"data",
"[",
"ATTR_VACATION_START",
"]",
"=",
"vacations",
"[",
"0",
"]",
".",
"start_date",
"data",
"[",
"ATTR_VACATION_END",
"]",
"=",
"vacations",
"[",
"0",
"]",
".",
"end_date",
"data",
"[",
"ATTR_ON_VACATION",
"]",
"=",
"self",
".",
"water_heater",
".",
"is_on_vacation",
"todays_usage",
"=",
"self",
".",
"water_heater",
".",
"total_usage_for_today",
"if",
"todays_usage",
":",
"data",
"[",
"ATTR_TODAYS_ENERGY_USAGE",
"]",
"=",
"todays_usage",
"data",
"[",
"ATTR_IN_USE",
"]",
"=",
"self",
".",
"water_heater",
".",
"in_use",
"if",
"self",
".",
"water_heater",
".",
"lower_temp",
"is",
"not",
"None",
":",
"data",
"[",
"ATTR_LOWER_TEMP",
"]",
"=",
"round",
"(",
"self",
".",
"water_heater",
".",
"lower_temp",
",",
"2",
")",
"if",
"self",
".",
"water_heater",
".",
"upper_temp",
"is",
"not",
"None",
":",
"data",
"[",
"ATTR_UPPER_TEMP",
"]",
"=",
"round",
"(",
"self",
".",
"water_heater",
".",
"upper_temp",
",",
"2",
")",
"if",
"self",
".",
"water_heater",
".",
"is_enabled",
"is",
"not",
"None",
":",
"data",
"[",
"ATTR_IS_ENABLED",
"]",
"=",
"self",
".",
"water_heater",
".",
"is_enabled",
"return",
"data"
] | [
157,
4
] | [
177,
19
] | python | en | ['en', 'en', 'en'] | True |
EcoNetWaterHeater.current_operation | (self) |
Return current operation as one of the following.
["eco", "heat_pump", "high_demand", "electric_only"]
|
Return current operation as one of the following. | def current_operation(self):
"""
Return current operation as one of the following.
["eco", "heat_pump", "high_demand", "electric_only"]
"""
current_op = self.econet_state_to_ha.get(self.water_heater.mode)
return current_op | [
"def",
"current_operation",
"(",
"self",
")",
":",
"current_op",
"=",
"self",
".",
"econet_state_to_ha",
".",
"get",
"(",
"self",
".",
"water_heater",
".",
"mode",
")",
"return",
"current_op"
] | [
180,
4
] | [
187,
25
] | python | en | ['en', 'error', 'th'] | False |
EcoNetWaterHeater.operation_list | (self) | List of available operation modes. | List of available operation modes. | def operation_list(self):
"""List of available operation modes."""
op_list = []
for mode in self.supported_modes:
ha_mode = self.econet_state_to_ha.get(mode)
if ha_mode is not None:
op_list.append(ha_mode)
return op_list | [
"def",
"operation_list",
"(",
"self",
")",
":",
"op_list",
"=",
"[",
"]",
"for",
"mode",
"in",
"self",
".",
"supported_modes",
":",
"ha_mode",
"=",
"self",
".",
"econet_state_to_ha",
".",
"get",
"(",
"mode",
")",
"if",
"ha_mode",
"is",
"not",
"None",
":",
"op_list",
".",
"append",
"(",
"ha_mode",
")",
"return",
"op_list"
] | [
190,
4
] | [
197,
22
] | python | en | ['en', 'en', 'en'] | True |
EcoNetWaterHeater.supported_features | (self) | Return the list of supported features. | Return the list of supported features. | def supported_features(self):
"""Return the list of supported features."""
return SUPPORT_FLAGS_HEATER | [
"def",
"supported_features",
"(",
"self",
")",
":",
"return",
"SUPPORT_FLAGS_HEATER"
] | [
200,
4
] | [
202,
35
] | python | en | ['en', 'en', 'en'] | True |
EcoNetWaterHeater.set_temperature | (self, **kwargs) | Set new target temperature. | Set new target temperature. | def set_temperature(self, **kwargs):
"""Set new target temperature."""
target_temp = kwargs.get(ATTR_TEMPERATURE)
if target_temp is not None:
self.water_heater.set_target_set_point(target_temp)
else:
_LOGGER.error("A target temperature must be provided") | [
"def",
"set_temperature",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"target_temp",
"=",
"kwargs",
".",
"get",
"(",
"ATTR_TEMPERATURE",
")",
"if",
"target_temp",
"is",
"not",
"None",
":",
"self",
".",
"water_heater",
".",
"set_target_set_point",
"(",
"target_temp",
")",
"else",
":",
"_LOGGER",
".",
"error",
"(",
"\"A target temperature must be provided\"",
")"
] | [
204,
4
] | [
210,
66
] | python | en | ['en', 'ca', 'en'] | True |
EcoNetWaterHeater.set_operation_mode | (self, operation_mode) | Set operation mode. | Set operation mode. | def set_operation_mode(self, operation_mode):
"""Set operation mode."""
op_mode_to_set = self.ha_state_to_econet.get(operation_mode)
if op_mode_to_set is not None:
self.water_heater.set_mode(op_mode_to_set)
else:
_LOGGER.error("An operation mode must be provided") | [
"def",
"set_operation_mode",
"(",
"self",
",",
"operation_mode",
")",
":",
"op_mode_to_set",
"=",
"self",
".",
"ha_state_to_econet",
".",
"get",
"(",
"operation_mode",
")",
"if",
"op_mode_to_set",
"is",
"not",
"None",
":",
"self",
".",
"water_heater",
".",
"set_mode",
"(",
"op_mode_to_set",
")",
"else",
":",
"_LOGGER",
".",
"error",
"(",
"\"An operation mode must be provided\"",
")"
] | [
212,
4
] | [
218,
63
] | python | en | ['nl', 'ny', 'en'] | False |
EcoNetWaterHeater.add_vacation | (self, start, end) | Add a vacation to this water heater. | Add a vacation to this water heater. | def add_vacation(self, start, end):
"""Add a vacation to this water heater."""
if not start:
start = datetime.datetime.now()
else:
start = datetime.datetime.fromtimestamp(start)
end = datetime.datetime.fromtimestamp(end)
self.water_heater.set_vacation_mode(start, end) | [
"def",
"add_vacation",
"(",
"self",
",",
"start",
",",
"end",
")",
":",
"if",
"not",
"start",
":",
"start",
"=",
"datetime",
".",
"datetime",
".",
"now",
"(",
")",
"else",
":",
"start",
"=",
"datetime",
".",
"datetime",
".",
"fromtimestamp",
"(",
"start",
")",
"end",
"=",
"datetime",
".",
"datetime",
".",
"fromtimestamp",
"(",
"end",
")",
"self",
".",
"water_heater",
".",
"set_vacation_mode",
"(",
"start",
",",
"end",
")"
] | [
220,
4
] | [
227,
55
] | python | en | ['en', 'en', 'en'] | True |
EcoNetWaterHeater.update | (self) | Get the latest date. | Get the latest date. | def update(self):
"""Get the latest date."""
self.water_heater.update_state() | [
"def",
"update",
"(",
"self",
")",
":",
"self",
".",
"water_heater",
".",
"update_state",
"(",
")"
] | [
229,
4
] | [
231,
40
] | python | en | ['en', 'en', 'en'] | True |
EcoNetWaterHeater.target_temperature | (self) | Return the temperature we try to reach. | Return the temperature we try to reach. | def target_temperature(self):
"""Return the temperature we try to reach."""
return self.water_heater.set_point | [
"def",
"target_temperature",
"(",
"self",
")",
":",
"return",
"self",
".",
"water_heater",
".",
"set_point"
] | [
234,
4
] | [
236,
42
] | python | en | ['en', 'en', 'en'] | True |
EcoNetWaterHeater.min_temp | (self) | Return the minimum temperature. | Return the minimum temperature. | def min_temp(self):
"""Return the minimum temperature."""
return self.water_heater.min_set_point | [
"def",
"min_temp",
"(",
"self",
")",
":",
"return",
"self",
".",
"water_heater",
".",
"min_set_point"
] | [
239,
4
] | [
241,
46
] | python | en | ['en', 'la', 'en'] | True |
EcoNetWaterHeater.max_temp | (self) | Return the maximum temperature. | Return the maximum temperature. | def max_temp(self):
"""Return the maximum temperature."""
return self.water_heater.max_set_point | [
"def",
"max_temp",
"(",
"self",
")",
":",
"return",
"self",
".",
"water_heater",
".",
"max_set_point"
] | [
244,
4
] | [
246,
46
] | python | en | ['en', 'la', 'en'] | True |
AbsStore.get | (self, indexes: Sequence) | Get contents.
Args:
indexes: A sequence of indexes to retrieve contents at.
Returns:
Retrieved contents.
| Get contents. | def get(self, indexes: Sequence):
"""Get contents.
Args:
indexes: A sequence of indexes to retrieve contents at.
Returns:
Retrieved contents.
"""
pass | [
"def",
"get",
"(",
"self",
",",
"indexes",
":",
"Sequence",
")",
":",
"pass"
] | [
13,
4
] | [
21,
12
] | python | en | ['en', 'nl', 'en'] | False |
AbsStore.put | (self, contents: Sequence) | Put new contents.
Args:
contents (Sequence): Contents to be added to the store.
Returns:
The indexes where the newly added entries reside in the store.
| Put new contents. | def put(self, contents: Sequence):
"""Put new contents.
Args:
contents (Sequence): Contents to be added to the store.
Returns:
The indexes where the newly added entries reside in the store.
"""
pass | [
"def",
"put",
"(",
"self",
",",
"contents",
":",
"Sequence",
")",
":",
"pass"
] | [
23,
4
] | [
31,
12
] | python | en | ['en', 'ca', 'en'] | True |
AbsStore.update | (self, indexes: Sequence, contents: Sequence) | Update the store contents at given positions.
Args:
indexes (Sequence): Positions where updates are to be made.
contents (Sequence): Item list, which has the same length as indexes.
Returns:
The indexes where store contents are updated.
| Update the store contents at given positions. | def update(self, indexes: Sequence, contents: Sequence):
"""Update the store contents at given positions.
Args:
indexes (Sequence): Positions where updates are to be made.
contents (Sequence): Item list, which has the same length as indexes.
Returns:
The indexes where store contents are updated.
"""
pass | [
"def",
"update",
"(",
"self",
",",
"indexes",
":",
"Sequence",
",",
"contents",
":",
"Sequence",
")",
":",
"pass"
] | [
34,
4
] | [
43,
12
] | python | en | ['en', 'en', 'en'] | True |
AbsStore.filter | (self, filters: Sequence[Callable]) | Multi-filter method.
The input to one filter is the output from the previous filter.
Args:
filters (Sequence[Callable]): Filter list, each item is a lambda function,
e.g., [lambda d: d['a'] == 1 and d['b'] == 1].
Returns:
Filtered indexes and corresponding objects.
| Multi-filter method. | def filter(self, filters: Sequence[Callable]):
"""Multi-filter method.
The input to one filter is the output from the previous filter.
Args:
filters (Sequence[Callable]): Filter list, each item is a lambda function,
e.g., [lambda d: d['a'] == 1 and d['b'] == 1].
Returns:
Filtered indexes and corresponding objects.
"""
pass | [
"def",
"filter",
"(",
"self",
",",
"filters",
":",
"Sequence",
"[",
"Callable",
"]",
")",
":",
"pass"
] | [
45,
4
] | [
56,
12
] | python | en | ['en', 'et', 'en'] | False |
AbsStore.sample | (self, size: int, weights: Sequence, replace: bool = True) | Obtain a random sample from the experience pool.
Args:
size (int): Sample sizes for each round of sampling in the chain. If this is a single integer, it is
used as the sample size for all samplers in the chain.
weights (Sequence): A sequence of sampling weights.
replace (bool): If True, sampling is performed with replacement. Defaults to True.
Returns:
A random sample from the experience pool.
| Obtain a random sample from the experience pool. | def sample(self, size: int, weights: Sequence, replace: bool = True):
"""Obtain a random sample from the experience pool.
Args:
size (int): Sample sizes for each round of sampling in the chain. If this is a single integer, it is
used as the sample size for all samplers in the chain.
weights (Sequence): A sequence of sampling weights.
replace (bool): If True, sampling is performed with replacement. Defaults to True.
Returns:
A random sample from the experience pool.
"""
pass | [
"def",
"sample",
"(",
"self",
",",
"size",
":",
"int",
",",
"weights",
":",
"Sequence",
",",
"replace",
":",
"bool",
"=",
"True",
")",
":",
"pass"
] | [
59,
4
] | [
70,
12
] | python | en | ['en', 'ga', 'en'] | True |
import_from_snapshot_dump | (streamit, folder: str, npy_name: str, meta_name: str, category: str) | Import specified category from snapshot dump file into data service.
Args:
streamit (streamit) : Streamit instance.
folder (str): Folder name of snapshot dump file.
npy_name (str): Name of .npy file that hold dumped numpy array data.
meta_name (str): File name of the meta file.
category (str): Category name to save into database.
| Import specified category from snapshot dump file into data service. | def import_from_snapshot_dump(streamit, folder: str, npy_name: str, meta_name: str, category: str):
"""Import specified category from snapshot dump file into data service.
Args:
streamit (streamit) : Streamit instance.
folder (str): Folder name of snapshot dump file.
npy_name (str): Name of .npy file that hold dumped numpy array data.
meta_name (str): File name of the meta file.
category (str): Category name to save into database.
"""
npy_path = os.path.join(folder, npy_name)
meta_path = os.path.join(folder, meta_name)
# Read meta file to get names and length of each field.
with open(meta_path, "r") as fp:
field_name_list = fp.readline().split(",")
field_length_list = [int(line) for line in fp.readline().split(",")]
instance_list: np.ndarray = np.load(npy_path)
# Instance number will be same for numpy backend.
instance_number = len(instance_list[0])
for tick in range(len(instance_list)):
streamit.tick(tick)
for instance_index in range(instance_number):
field_dict = {}
field_slot_index = 0
for field_index in range(len(field_name_list)):
field_name = field_name_list[field_index].strip()
field_length = field_length_list[field_index]
field_dict["index"] = instance_index
if field_length == 1:
field_dict[field_name] = instance_list[tick][instance_index][field_name].item()
else:
field_dict[field_name] = list(
[v.item() for v in instance_list[tick][instance_index][field_name]]
)
field_slot_index += field_length
streamit.data(category, **field_dict)
return instance_number | [
"def",
"import_from_snapshot_dump",
"(",
"streamit",
",",
"folder",
":",
"str",
",",
"npy_name",
":",
"str",
",",
"meta_name",
":",
"str",
",",
"category",
":",
"str",
")",
":",
"npy_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"folder",
",",
"npy_name",
")",
"meta_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"folder",
",",
"meta_name",
")",
"# Read meta file to get names and length of each field.",
"with",
"open",
"(",
"meta_path",
",",
"\"r\"",
")",
"as",
"fp",
":",
"field_name_list",
"=",
"fp",
".",
"readline",
"(",
")",
".",
"split",
"(",
"\",\"",
")",
"field_length_list",
"=",
"[",
"int",
"(",
"line",
")",
"for",
"line",
"in",
"fp",
".",
"readline",
"(",
")",
".",
"split",
"(",
"\",\"",
")",
"]",
"instance_list",
":",
"np",
".",
"ndarray",
"=",
"np",
".",
"load",
"(",
"npy_path",
")",
"# Instance number will be same for numpy backend.",
"instance_number",
"=",
"len",
"(",
"instance_list",
"[",
"0",
"]",
")",
"for",
"tick",
"in",
"range",
"(",
"len",
"(",
"instance_list",
")",
")",
":",
"streamit",
".",
"tick",
"(",
"tick",
")",
"for",
"instance_index",
"in",
"range",
"(",
"instance_number",
")",
":",
"field_dict",
"=",
"{",
"}",
"field_slot_index",
"=",
"0",
"for",
"field_index",
"in",
"range",
"(",
"len",
"(",
"field_name_list",
")",
")",
":",
"field_name",
"=",
"field_name_list",
"[",
"field_index",
"]",
".",
"strip",
"(",
")",
"field_length",
"=",
"field_length_list",
"[",
"field_index",
"]",
"field_dict",
"[",
"\"index\"",
"]",
"=",
"instance_index",
"if",
"field_length",
"==",
"1",
":",
"field_dict",
"[",
"field_name",
"]",
"=",
"instance_list",
"[",
"tick",
"]",
"[",
"instance_index",
"]",
"[",
"field_name",
"]",
".",
"item",
"(",
")",
"else",
":",
"field_dict",
"[",
"field_name",
"]",
"=",
"list",
"(",
"[",
"v",
".",
"item",
"(",
")",
"for",
"v",
"in",
"instance_list",
"[",
"tick",
"]",
"[",
"instance_index",
"]",
"[",
"field_name",
"]",
"]",
")",
"field_slot_index",
"+=",
"field_length",
"streamit",
".",
"data",
"(",
"category",
",",
"*",
"*",
"field_dict",
")",
"return",
"instance_number"
] | [
11,
0
] | [
59,
26
] | python | en | ['en', 'en', 'en'] | True |
import_port_details | (streamit, folder: str) | Import port details into database from specified folder.
Args:
streamit (streamit) : Streamit instance.
folder (str): Folder path that contains the port detail file.
| Import port details into database from specified folder. | def import_port_details(streamit, folder: str):
"""Import port details into database from specified folder.
Args:
streamit (streamit) : Streamit instance.
folder (str): Folder path that contains the port detail file.
"""
port_npy_name = "ports.npy"
port_meta_name = "ports.meta"
category = "port_details"
return import_from_snapshot_dump(streamit, folder, port_npy_name, port_meta_name, category) | [
"def",
"import_port_details",
"(",
"streamit",
",",
"folder",
":",
"str",
")",
":",
"port_npy_name",
"=",
"\"ports.npy\"",
"port_meta_name",
"=",
"\"ports.meta\"",
"category",
"=",
"\"port_details\"",
"return",
"import_from_snapshot_dump",
"(",
"streamit",
",",
"folder",
",",
"port_npy_name",
",",
"port_meta_name",
",",
"category",
")"
] | [
62,
0
] | [
73,
95
] | python | en | ['en', 'en', 'en'] | True |
import_vessel_details | (streamit, folder: str) | Import vessel details into database.
Args:
streamit (streamit) : Streamit instance.
folder (str): Folder path that contains vessel details.
| Import vessel details into database. | def import_vessel_details(streamit, folder: str):
"""Import vessel details into database.
Args:
streamit (streamit) : Streamit instance.
folder (str): Folder path that contains vessel details.
"""
vessels_npy_name = "vessels.npy"
vessels_meta_name = "vessels.meta"
category = "vessel_details"
return import_from_snapshot_dump(streamit, folder, vessels_npy_name, vessels_meta_name, category) | [
"def",
"import_vessel_details",
"(",
"streamit",
",",
"folder",
":",
"str",
")",
":",
"vessels_npy_name",
"=",
"\"vessels.npy\"",
"vessels_meta_name",
"=",
"\"vessels.meta\"",
"category",
"=",
"\"vessel_details\"",
"return",
"import_from_snapshot_dump",
"(",
"streamit",
",",
"folder",
",",
"vessels_npy_name",
",",
"vessels_meta_name",
",",
"category",
")"
] | [
76,
0
] | [
87,
101
] | python | da | ['pt', 'da', 'en'] | False |
import_full_on_ports | (streamit, data: np.ndarray, port_number: int) | Import full_on_ports information into database.
Args:
streamit (streamit) : Streamit instance.
data (numpy.ndarray): Data of full_on_ports.
port_number (int): Number of ports.
| Import full_on_ports information into database. | def import_full_on_ports(streamit, data: np.ndarray, port_number: int):
"""Import full_on_ports information into database.
Args:
streamit (streamit) : Streamit instance.
data (numpy.ndarray): Data of full_on_ports.
port_number (int): Number of ports.
"""
for tick in range(len(data)):
streamit.tick(tick)
m = data[tick][0].reshape(port_number, -1)
# We only save cells that value > 0.
a, b = np.where(m > 0)
for from_port_index, to_port_index in list(zip(a, b)):
streamit.data(
"full_on_ports",
from_port_index=from_port_index,
dest_port_index=to_port_index,
quantity=m[from_port_index, to_port_index]
) | [
"def",
"import_full_on_ports",
"(",
"streamit",
",",
"data",
":",
"np",
".",
"ndarray",
",",
"port_number",
":",
"int",
")",
":",
"for",
"tick",
"in",
"range",
"(",
"len",
"(",
"data",
")",
")",
":",
"streamit",
".",
"tick",
"(",
"tick",
")",
"m",
"=",
"data",
"[",
"tick",
"]",
"[",
"0",
"]",
".",
"reshape",
"(",
"port_number",
",",
"-",
"1",
")",
"# We only save cells that value > 0.",
"a",
",",
"b",
"=",
"np",
".",
"where",
"(",
"m",
">",
"0",
")",
"for",
"from_port_index",
",",
"to_port_index",
"in",
"list",
"(",
"zip",
"(",
"a",
",",
"b",
")",
")",
":",
"streamit",
".",
"data",
"(",
"\"full_on_ports\"",
",",
"from_port_index",
"=",
"from_port_index",
",",
"dest_port_index",
"=",
"to_port_index",
",",
"quantity",
"=",
"m",
"[",
"from_port_index",
",",
"to_port_index",
"]",
")"
] | [
90,
0
] | [
112,
13
] | python | en | ['pt', 'zu', 'en'] | False |
import_full_on_vessels | (streamit, data: np.ndarray, port_number: int, vessel_number: int) | Import full_on_vessels data into database.
Args:
streamit (streamit) : Streamit instance.
data (numpy.ndarray): Data that contains full_on_vessels matrix.
port_number (int): Number of ports.
vessel_number (int): Number of vessels.
| Import full_on_vessels data into database. | def import_full_on_vessels(streamit, data: np.ndarray, port_number: int, vessel_number: int):
"""Import full_on_vessels data into database.
Args:
streamit (streamit) : Streamit instance.
data (numpy.ndarray): Data that contains full_on_vessels matrix.
port_number (int): Number of ports.
vessel_number (int): Number of vessels.
"""
for tick in range(len(data)):
streamit.tick(tick)
m = data[tick][0].reshape(vessel_number, port_number)
a, b = np.where(m > 0)
for vessel_index, port_index in list(zip(a, b)):
streamit.data(
"full_on_vessels",
vessel_index=vessel_index,
port_index=port_index,
quantity=m[vessel_index, port_index]
) | [
"def",
"import_full_on_vessels",
"(",
"streamit",
",",
"data",
":",
"np",
".",
"ndarray",
",",
"port_number",
":",
"int",
",",
"vessel_number",
":",
"int",
")",
":",
"for",
"tick",
"in",
"range",
"(",
"len",
"(",
"data",
")",
")",
":",
"streamit",
".",
"tick",
"(",
"tick",
")",
"m",
"=",
"data",
"[",
"tick",
"]",
"[",
"0",
"]",
".",
"reshape",
"(",
"vessel_number",
",",
"port_number",
")",
"a",
",",
"b",
"=",
"np",
".",
"where",
"(",
"m",
">",
"0",
")",
"for",
"vessel_index",
",",
"port_index",
"in",
"list",
"(",
"zip",
"(",
"a",
",",
"b",
")",
")",
":",
"streamit",
".",
"data",
"(",
"\"full_on_vessels\"",
",",
"vessel_index",
"=",
"vessel_index",
",",
"port_index",
"=",
"port_index",
",",
"quantity",
"=",
"m",
"[",
"vessel_index",
",",
"port_index",
"]",
")"
] | [
115,
0
] | [
137,
13
] | python | en | ['pt', 'en', 'en'] | True |
import_vessel_plans | (streamit, data: np.ndarray, port_number: int, vessel_number: int) | Import vessel_plans matrix into database.
Args:
streamit (streamit) : Streamit instance.
data (numpy.ndarray): Data that contains vessel_plans matrix.
port_number (int): Number of ports.
vessel_number (int): Number of vessels.
| Import vessel_plans matrix into database. | def import_vessel_plans(streamit, data: np.ndarray, port_number: int, vessel_number: int):
"""Import vessel_plans matrix into database.
Args:
streamit (streamit) : Streamit instance.
data (numpy.ndarray): Data that contains vessel_plans matrix.
port_number (int): Number of ports.
vessel_number (int): Number of vessels.
"""
for tick in range(len(data)):
streamit.tick(tick)
m = data[tick][0].reshape(vessel_number, port_number)
a, b = np.where(m > -1)
for vessel_index, port_index in list(zip(a, b)):
streamit.data(
"vessel_plans",
vessel_index=vessel_index,
port_index=port_index,
planed_arrival_tick=m[vessel_index, port_index]
) | [
"def",
"import_vessel_plans",
"(",
"streamit",
",",
"data",
":",
"np",
".",
"ndarray",
",",
"port_number",
":",
"int",
",",
"vessel_number",
":",
"int",
")",
":",
"for",
"tick",
"in",
"range",
"(",
"len",
"(",
"data",
")",
")",
":",
"streamit",
".",
"tick",
"(",
"tick",
")",
"m",
"=",
"data",
"[",
"tick",
"]",
"[",
"0",
"]",
".",
"reshape",
"(",
"vessel_number",
",",
"port_number",
")",
"a",
",",
"b",
"=",
"np",
".",
"where",
"(",
"m",
">",
"-",
"1",
")",
"for",
"vessel_index",
",",
"port_index",
"in",
"list",
"(",
"zip",
"(",
"a",
",",
"b",
")",
")",
":",
"streamit",
".",
"data",
"(",
"\"vessel_plans\"",
",",
"vessel_index",
"=",
"vessel_index",
",",
"port_index",
"=",
"port_index",
",",
"planed_arrival_tick",
"=",
"m",
"[",
"vessel_index",
",",
"port_index",
"]",
")"
] | [
140,
0
] | [
162,
13
] | python | en | ['it', 'fr', 'en'] | False |
import_metrics | (streamit, epoch_full_path: str, port_number: int, vessel_number: int) | Import matrix into database.
Args:
streamit (streamit) : Streamit instance.
epoch_full_path (str): Path that for target epoch.
port_number (int): Number of ports.
vessel_number (int): Number of vessels.
| Import matrix into database. | def import_metrics(streamit, epoch_full_path: str, port_number: int, vessel_number: int):
"""Import matrix into database.
Args:
streamit (streamit) : Streamit instance.
epoch_full_path (str): Path that for target epoch.
port_number (int): Number of ports.
vessel_number (int): Number of vessels.
"""
matrics_path = os.path.join(epoch_full_path, "matrices.npy")
matrics = np.load(matrics_path)
import_full_on_ports(streamit, matrics["full_on_ports"], port_number)
import_full_on_vessels(streamit, matrics["full_on_vessels"], port_number, vessel_number)
import_vessel_plans(streamit, matrics["vessel_plans"], port_number, vessel_number) | [
"def",
"import_metrics",
"(",
"streamit",
",",
"epoch_full_path",
":",
"str",
",",
"port_number",
":",
"int",
",",
"vessel_number",
":",
"int",
")",
":",
"matrics_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"epoch_full_path",
",",
"\"matrices.npy\"",
")",
"matrics",
"=",
"np",
".",
"load",
"(",
"matrics_path",
")",
"import_full_on_ports",
"(",
"streamit",
",",
"matrics",
"[",
"\"full_on_ports\"",
"]",
",",
"port_number",
")",
"import_full_on_vessels",
"(",
"streamit",
",",
"matrics",
"[",
"\"full_on_vessels\"",
"]",
",",
"port_number",
",",
"vessel_number",
")",
"import_vessel_plans",
"(",
"streamit",
",",
"matrics",
"[",
"\"vessel_plans\"",
"]",
",",
"port_number",
",",
"vessel_number",
")"
] | [
165,
0
] | [
180,
86
] | python | en | ['it', 'zu', 'en'] | False |
import_attention | (streamit, atts_path: str) | Import attaention data.
Args:
streamit (streamit) : Streamit instance.
atts_path (str): Path to attention file.
| Import attaention data. | def import_attention(streamit, atts_path: str):
"""Import attaention data.
Args:
streamit (streamit) : Streamit instance.
atts_path (str): Path to attention file.
"""
with open(atts_path, "rb") as fp:
attentions = pickle.load(fp)
attention_index = -1
# List of tuple (tick, attention dict contains:"p2p", "p2v", "v2p").
for tick, attention in attentions:
attention_index += 1
tick = int(tick)
streamit.tick(tick)
streamit.complex("attentions", attention) | [
"def",
"import_attention",
"(",
"streamit",
",",
"atts_path",
":",
"str",
")",
":",
"with",
"open",
"(",
"atts_path",
",",
"\"rb\"",
")",
"as",
"fp",
":",
"attentions",
"=",
"pickle",
".",
"load",
"(",
"fp",
")",
"attention_index",
"=",
"-",
"1",
"# List of tuple (tick, attention dict contains:\"p2p\", \"p2v\", \"v2p\").",
"for",
"tick",
",",
"attention",
"in",
"attentions",
":",
"attention_index",
"+=",
"1",
"tick",
"=",
"int",
"(",
"tick",
")",
"streamit",
".",
"tick",
"(",
"tick",
")",
"streamit",
".",
"complex",
"(",
"\"attentions\"",
",",
"attention",
")"
] | [
183,
0
] | [
203,
49
] | python | en | ['fr', 'ja', 'en'] | False |
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.
"""
try:
tado = await hass.async_add_executor_job(
Tado, data[CONF_USERNAME], data[CONF_PASSWORD]
)
tado_me = await hass.async_add_executor_job(tado.getMe)
except KeyError as ex:
raise InvalidAuth from ex
except RuntimeError as ex:
raise CannotConnect from ex
except requests.exceptions.HTTPError as ex:
if ex.response.status_code > 400 and ex.response.status_code < 500:
raise InvalidAuth from ex
raise CannotConnect from ex
if "homes" not in tado_me or len(tado_me["homes"]) == 0:
raise NoHomes
home = tado_me["homes"][0]
unique_id = str(home["id"])
name = home["name"]
return {"title": name, UNIQUE_ID: unique_id} | [
"async",
"def",
"validate_input",
"(",
"hass",
":",
"core",
".",
"HomeAssistant",
",",
"data",
")",
":",
"try",
":",
"tado",
"=",
"await",
"hass",
".",
"async_add_executor_job",
"(",
"Tado",
",",
"data",
"[",
"CONF_USERNAME",
"]",
",",
"data",
"[",
"CONF_PASSWORD",
"]",
")",
"tado_me",
"=",
"await",
"hass",
".",
"async_add_executor_job",
"(",
"tado",
".",
"getMe",
")",
"except",
"KeyError",
"as",
"ex",
":",
"raise",
"InvalidAuth",
"from",
"ex",
"except",
"RuntimeError",
"as",
"ex",
":",
"raise",
"CannotConnect",
"from",
"ex",
"except",
"requests",
".",
"exceptions",
".",
"HTTPError",
"as",
"ex",
":",
"if",
"ex",
".",
"response",
".",
"status_code",
">",
"400",
"and",
"ex",
".",
"response",
".",
"status_code",
"<",
"500",
":",
"raise",
"InvalidAuth",
"from",
"ex",
"raise",
"CannotConnect",
"from",
"ex",
"if",
"\"homes\"",
"not",
"in",
"tado_me",
"or",
"len",
"(",
"tado_me",
"[",
"\"homes\"",
"]",
")",
"==",
"0",
":",
"raise",
"NoHomes",
"home",
"=",
"tado_me",
"[",
"\"homes\"",
"]",
"[",
"0",
"]",
"unique_id",
"=",
"str",
"(",
"home",
"[",
"\"id\"",
"]",
")",
"name",
"=",
"home",
"[",
"\"name\"",
"]",
"return",
"{",
"\"title\"",
":",
"name",
",",
"UNIQUE_ID",
":",
"unique_id",
"}"
] | [
21,
0
] | [
48,
48
] | 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:
validated = await validate_input(self.hass, user_input)
except CannotConnect:
errors["base"] = "cannot_connect"
except InvalidAuth:
errors["base"] = "invalid_auth"
except NoHomes:
errors["base"] = "no_homes"
except Exception: # pylint: disable=broad-except
_LOGGER.exception("Unexpected exception")
errors["base"] = "unknown"
if "base" not in errors:
await self.async_set_unique_id(validated[UNIQUE_ID])
self._abort_if_unique_id_configured()
return self.async_create_entry(
title=validated["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",
":",
"validated",
"=",
"await",
"validate_input",
"(",
"self",
".",
"hass",
",",
"user_input",
")",
"except",
"CannotConnect",
":",
"errors",
"[",
"\"base\"",
"]",
"=",
"\"cannot_connect\"",
"except",
"InvalidAuth",
":",
"errors",
"[",
"\"base\"",
"]",
"=",
"\"invalid_auth\"",
"except",
"NoHomes",
":",
"errors",
"[",
"\"base\"",
"]",
"=",
"\"no_homes\"",
"except",
"Exception",
":",
"# pylint: disable=broad-except",
"_LOGGER",
".",
"exception",
"(",
"\"Unexpected exception\"",
")",
"errors",
"[",
"\"base\"",
"]",
"=",
"\"unknown\"",
"if",
"\"base\"",
"not",
"in",
"errors",
":",
"await",
"self",
".",
"async_set_unique_id",
"(",
"validated",
"[",
"UNIQUE_ID",
"]",
")",
"self",
".",
"_abort_if_unique_id_configured",
"(",
")",
"return",
"self",
".",
"async_create_entry",
"(",
"title",
"=",
"validated",
"[",
"\"title\"",
"]",
",",
"data",
"=",
"user_input",
")",
"return",
"self",
".",
"async_show_form",
"(",
"step_id",
"=",
"\"user\"",
",",
"data_schema",
"=",
"DATA_SCHEMA",
",",
"errors",
"=",
"errors",
")"
] | [
57,
4
] | [
82,
9
] | python | en | ['en', 'en', 'en'] | True |
ConfigFlow.async_step_homekit | (self, homekit_info) | Handle HomeKit discovery. | Handle HomeKit discovery. | async def async_step_homekit(self, homekit_info):
"""Handle HomeKit discovery."""
if self._async_current_entries():
# We can see tado on the network to tell them to configure
# it, but since the device will not give up the account it is
# bound to and there can be multiple tado devices on a single
# account, we avoid showing the device as discovered once
# they already have one configured as they can always
# add a new one via "+"
return self.async_abort(reason="already_configured")
properties = {
key.lower(): value for (key, value) in homekit_info["properties"].items()
}
await self.async_set_unique_id(properties["id"])
return await self.async_step_user() | [
"async",
"def",
"async_step_homekit",
"(",
"self",
",",
"homekit_info",
")",
":",
"if",
"self",
".",
"_async_current_entries",
"(",
")",
":",
"# We can see tado on the network to tell them to configure",
"# it, but since the device will not give up the account it is",
"# bound to and there can be multiple tado devices on a single",
"# account, we avoid showing the device as discovered once",
"# they already have one configured as they can always",
"# add a new one via \"+\"",
"return",
"self",
".",
"async_abort",
"(",
"reason",
"=",
"\"already_configured\"",
")",
"properties",
"=",
"{",
"key",
".",
"lower",
"(",
")",
":",
"value",
"for",
"(",
"key",
",",
"value",
")",
"in",
"homekit_info",
"[",
"\"properties\"",
"]",
".",
"items",
"(",
")",
"}",
"await",
"self",
".",
"async_set_unique_id",
"(",
"properties",
"[",
"\"id\"",
"]",
")",
"return",
"await",
"self",
".",
"async_step_user",
"(",
")"
] | [
84,
4
] | [
98,
43
] | python | en | ['fr', 'xh', 'en'] | False |
ConfigFlow.async_step_import | (self, user_input) | Handle import. | Handle import. | async def async_step_import(self, user_input):
"""Handle import."""
if self._username_already_configured(user_input):
return self.async_abort(reason="already_configured")
return await self.async_step_user(user_input) | [
"async",
"def",
"async_step_import",
"(",
"self",
",",
"user_input",
")",
":",
"if",
"self",
".",
"_username_already_configured",
"(",
"user_input",
")",
":",
"return",
"self",
".",
"async_abort",
"(",
"reason",
"=",
"\"already_configured\"",
")",
"return",
"await",
"self",
".",
"async_step_user",
"(",
"user_input",
")"
] | [
100,
4
] | [
104,
53
] | python | en | ['en', 'ja', 'en'] | False |
ConfigFlow._username_already_configured | (self, user_input) | See if we already have a username matching user input configured. | See if we already have a username matching user input configured. | def _username_already_configured(self, user_input):
"""See if we already have a username matching user input configured."""
existing_username = {
entry.data[CONF_USERNAME] for entry in self._async_current_entries()
}
return user_input[CONF_USERNAME] in existing_username | [
"def",
"_username_already_configured",
"(",
"self",
",",
"user_input",
")",
":",
"existing_username",
"=",
"{",
"entry",
".",
"data",
"[",
"CONF_USERNAME",
"]",
"for",
"entry",
"in",
"self",
".",
"_async_current_entries",
"(",
")",
"}",
"return",
"user_input",
"[",
"CONF_USERNAME",
"]",
"in",
"existing_username"
] | [
106,
4
] | [
111,
61
] | python | en | ['en', 'en', 'en'] | True |
ConfigFlow.async_get_options_flow | (config_entry) | Get the options flow for this handler. | Get the options flow for this handler. | def async_get_options_flow(config_entry):
"""Get the options flow for this handler."""
return OptionsFlowHandler(config_entry) | [
"def",
"async_get_options_flow",
"(",
"config_entry",
")",
":",
"return",
"OptionsFlowHandler",
"(",
"config_entry",
")"
] | [
115,
4
] | [
117,
47
] | python | en | ['en', 'en', 'en'] | True |
OptionsFlowHandler.__init__ | (self, config_entry: config_entries.ConfigEntry) | Initialize options flow. | Initialize options flow. | def __init__(self, config_entry: config_entries.ConfigEntry):
"""Initialize options flow."""
self.config_entry = config_entry | [
"def",
"__init__",
"(",
"self",
",",
"config_entry",
":",
"config_entries",
".",
"ConfigEntry",
")",
":",
"self",
".",
"config_entry",
"=",
"config_entry"
] | [
123,
4
] | [
125,
40
] | python | en | ['en', 'en', 'en'] | True |
OptionsFlowHandler.async_step_init | (self, user_input=None) | Handle options flow. | Handle options flow. | async def async_step_init(self, user_input=None):
"""Handle options flow."""
if user_input is not None:
return self.async_create_entry(title="", data=user_input)
data_schema = vol.Schema(
{
vol.Required(
CONF_FALLBACK, default=self.config_entry.options.get(CONF_FALLBACK)
): bool,
}
)
return self.async_show_form(step_id="init", data_schema=data_schema) | [
"async",
"def",
"async_step_init",
"(",
"self",
",",
"user_input",
"=",
"None",
")",
":",
"if",
"user_input",
"is",
"not",
"None",
":",
"return",
"self",
".",
"async_create_entry",
"(",
"title",
"=",
"\"\"",
",",
"data",
"=",
"user_input",
")",
"data_schema",
"=",
"vol",
".",
"Schema",
"(",
"{",
"vol",
".",
"Required",
"(",
"CONF_FALLBACK",
",",
"default",
"=",
"self",
".",
"config_entry",
".",
"options",
".",
"get",
"(",
"CONF_FALLBACK",
")",
")",
":",
"bool",
",",
"}",
")",
"return",
"self",
".",
"async_show_form",
"(",
"step_id",
"=",
"\"init\"",
",",
"data_schema",
"=",
"data_schema",
")"
] | [
127,
4
] | [
139,
76
] | python | en | ['en', 'nl', 'en'] | True |
setup | (hass, config) | Listen for keyboard events. | Listen for keyboard events. | def setup(hass, config):
"""Listen for keyboard events."""
keyboard = PyKeyboard()
keyboard.special_key_assignment()
hass.services.register(
DOMAIN,
SERVICE_VOLUME_UP,
lambda service: keyboard.tap_key(keyboard.volume_up_key),
schema=TAP_KEY_SCHEMA,
)
hass.services.register(
DOMAIN,
SERVICE_VOLUME_DOWN,
lambda service: keyboard.tap_key(keyboard.volume_down_key),
schema=TAP_KEY_SCHEMA,
)
hass.services.register(
DOMAIN,
SERVICE_VOLUME_MUTE,
lambda service: keyboard.tap_key(keyboard.volume_mute_key),
schema=TAP_KEY_SCHEMA,
)
hass.services.register(
DOMAIN,
SERVICE_MEDIA_PLAY_PAUSE,
lambda service: keyboard.tap_key(keyboard.media_play_pause_key),
schema=TAP_KEY_SCHEMA,
)
hass.services.register(
DOMAIN,
SERVICE_MEDIA_NEXT_TRACK,
lambda service: keyboard.tap_key(keyboard.media_next_track_key),
schema=TAP_KEY_SCHEMA,
)
hass.services.register(
DOMAIN,
SERVICE_MEDIA_PREVIOUS_TRACK,
lambda service: keyboard.tap_key(keyboard.media_prev_track_key),
schema=TAP_KEY_SCHEMA,
)
return True | [
"def",
"setup",
"(",
"hass",
",",
"config",
")",
":",
"keyboard",
"=",
"PyKeyboard",
"(",
")",
"keyboard",
".",
"special_key_assignment",
"(",
")",
"hass",
".",
"services",
".",
"register",
"(",
"DOMAIN",
",",
"SERVICE_VOLUME_UP",
",",
"lambda",
"service",
":",
"keyboard",
".",
"tap_key",
"(",
"keyboard",
".",
"volume_up_key",
")",
",",
"schema",
"=",
"TAP_KEY_SCHEMA",
",",
")",
"hass",
".",
"services",
".",
"register",
"(",
"DOMAIN",
",",
"SERVICE_VOLUME_DOWN",
",",
"lambda",
"service",
":",
"keyboard",
".",
"tap_key",
"(",
"keyboard",
".",
"volume_down_key",
")",
",",
"schema",
"=",
"TAP_KEY_SCHEMA",
",",
")",
"hass",
".",
"services",
".",
"register",
"(",
"DOMAIN",
",",
"SERVICE_VOLUME_MUTE",
",",
"lambda",
"service",
":",
"keyboard",
".",
"tap_key",
"(",
"keyboard",
".",
"volume_mute_key",
")",
",",
"schema",
"=",
"TAP_KEY_SCHEMA",
",",
")",
"hass",
".",
"services",
".",
"register",
"(",
"DOMAIN",
",",
"SERVICE_MEDIA_PLAY_PAUSE",
",",
"lambda",
"service",
":",
"keyboard",
".",
"tap_key",
"(",
"keyboard",
".",
"media_play_pause_key",
")",
",",
"schema",
"=",
"TAP_KEY_SCHEMA",
",",
")",
"hass",
".",
"services",
".",
"register",
"(",
"DOMAIN",
",",
"SERVICE_MEDIA_NEXT_TRACK",
",",
"lambda",
"service",
":",
"keyboard",
".",
"tap_key",
"(",
"keyboard",
".",
"media_next_track_key",
")",
",",
"schema",
"=",
"TAP_KEY_SCHEMA",
",",
")",
"hass",
".",
"services",
".",
"register",
"(",
"DOMAIN",
",",
"SERVICE_MEDIA_PREVIOUS_TRACK",
",",
"lambda",
"service",
":",
"keyboard",
".",
"tap_key",
"(",
"keyboard",
".",
"media_prev_track_key",
")",
",",
"schema",
"=",
"TAP_KEY_SCHEMA",
",",
")",
"return",
"True"
] | [
18,
0
] | [
65,
15
] | python | en | ['en', 'en', 'en'] | True |
setup_platform | (hass, config, add_entities, discovery_info=None) | Set up the IHC binary sensor platform. | Set up the IHC binary sensor platform. | def setup_platform(hass, config, add_entities, discovery_info=None):
"""Set up the IHC binary sensor platform."""
if discovery_info is None:
return
devices = []
for name, device in discovery_info.items():
ihc_id = device["ihc_id"]
product_cfg = device["product_cfg"]
product = device["product"]
# Find controller that corresponds with device id
ctrl_id = device["ctrl_id"]
ihc_key = f"ihc{ctrl_id}"
info = hass.data[ihc_key][IHC_INFO]
ihc_controller = hass.data[ihc_key][IHC_CONTROLLER]
sensor = IHCBinarySensor(
ihc_controller,
name,
ihc_id,
info,
product_cfg.get(CONF_TYPE),
product_cfg[CONF_INVERTING],
product,
)
devices.append(sensor)
add_entities(devices) | [
"def",
"setup_platform",
"(",
"hass",
",",
"config",
",",
"add_entities",
",",
"discovery_info",
"=",
"None",
")",
":",
"if",
"discovery_info",
"is",
"None",
":",
"return",
"devices",
"=",
"[",
"]",
"for",
"name",
",",
"device",
"in",
"discovery_info",
".",
"items",
"(",
")",
":",
"ihc_id",
"=",
"device",
"[",
"\"ihc_id\"",
"]",
"product_cfg",
"=",
"device",
"[",
"\"product_cfg\"",
"]",
"product",
"=",
"device",
"[",
"\"product\"",
"]",
"# Find controller that corresponds with device id",
"ctrl_id",
"=",
"device",
"[",
"\"ctrl_id\"",
"]",
"ihc_key",
"=",
"f\"ihc{ctrl_id}\"",
"info",
"=",
"hass",
".",
"data",
"[",
"ihc_key",
"]",
"[",
"IHC_INFO",
"]",
"ihc_controller",
"=",
"hass",
".",
"data",
"[",
"ihc_key",
"]",
"[",
"IHC_CONTROLLER",
"]",
"sensor",
"=",
"IHCBinarySensor",
"(",
"ihc_controller",
",",
"name",
",",
"ihc_id",
",",
"info",
",",
"product_cfg",
".",
"get",
"(",
"CONF_TYPE",
")",
",",
"product_cfg",
"[",
"CONF_INVERTING",
"]",
",",
"product",
",",
")",
"devices",
".",
"append",
"(",
"sensor",
")",
"add_entities",
"(",
"devices",
")"
] | [
9,
0
] | [
34,
25
] | python | en | ['en', 'bs', 'en'] | True |
IHCBinarySensor.__init__ | (
self,
ihc_controller,
name,
ihc_id: int,
info: bool,
sensor_type: str,
inverting: bool,
product=None,
) | Initialize the IHC binary sensor. | Initialize the IHC binary sensor. | def __init__(
self,
ihc_controller,
name,
ihc_id: int,
info: bool,
sensor_type: str,
inverting: bool,
product=None,
) -> None:
"""Initialize the IHC binary sensor."""
super().__init__(ihc_controller, name, ihc_id, info, product)
self._state = None
self._sensor_type = sensor_type
self.inverting = inverting | [
"def",
"__init__",
"(",
"self",
",",
"ihc_controller",
",",
"name",
",",
"ihc_id",
":",
"int",
",",
"info",
":",
"bool",
",",
"sensor_type",
":",
"str",
",",
"inverting",
":",
"bool",
",",
"product",
"=",
"None",
",",
")",
"->",
"None",
":",
"super",
"(",
")",
".",
"__init__",
"(",
"ihc_controller",
",",
"name",
",",
"ihc_id",
",",
"info",
",",
"product",
")",
"self",
".",
"_state",
"=",
"None",
"self",
".",
"_sensor_type",
"=",
"sensor_type",
"self",
".",
"inverting",
"=",
"inverting"
] | [
44,
4
] | [
58,
34
] | python | en | ['en', 'pl', 'en'] | True |
IHCBinarySensor.device_class | (self) | Return the class of this sensor. | Return the class of this sensor. | def device_class(self):
"""Return the class of this sensor."""
return self._sensor_type | [
"def",
"device_class",
"(",
"self",
")",
":",
"return",
"self",
".",
"_sensor_type"
] | [
61,
4
] | [
63,
32
] | python | en | ['en', 'en', 'en'] | True |
IHCBinarySensor.is_on | (self) | Return true if the binary sensor is on/open. | Return true if the binary sensor is on/open. | def is_on(self):
"""Return true if the binary sensor is on/open."""
return self._state | [
"def",
"is_on",
"(",
"self",
")",
":",
"return",
"self",
".",
"_state"
] | [
66,
4
] | [
68,
26
] | python | en | ['en', 'fy', 'en'] | True |
IHCBinarySensor.on_ihc_change | (self, ihc_id, value) | IHC resource has changed. | IHC resource has changed. | def on_ihc_change(self, ihc_id, value):
"""IHC resource has changed."""
if self.inverting:
self._state = not value
else:
self._state = value
self.schedule_update_ha_state() | [
"def",
"on_ihc_change",
"(",
"self",
",",
"ihc_id",
",",
"value",
")",
":",
"if",
"self",
".",
"inverting",
":",
"self",
".",
"_state",
"=",
"not",
"value",
"else",
":",
"self",
".",
"_state",
"=",
"value",
"self",
".",
"schedule_update_ha_state",
"(",
")"
] | [
70,
4
] | [
76,
39
] | python | en | ['en', 'sn', 'en'] | True |
test_platform_manually_configured | (hass) | Test that nothing happens when platform is manually configured. | Test that nothing happens when platform is manually configured. | async def test_platform_manually_configured(hass):
"""Test that nothing happens when platform is manually configured."""
assert (
await async_setup_component(
hass,
BINARY_SENSOR_DOMAIN,
{BINARY_SENSOR_DOMAIN: {"platform": AXIS_DOMAIN}},
)
is True
)
assert AXIS_DOMAIN not in hass.data | [
"async",
"def",
"test_platform_manually_configured",
"(",
"hass",
")",
":",
"assert",
"(",
"await",
"async_setup_component",
"(",
"hass",
",",
"BINARY_SENSOR_DOMAIN",
",",
"{",
"BINARY_SENSOR_DOMAIN",
":",
"{",
"\"platform\"",
":",
"AXIS_DOMAIN",
"}",
"}",
",",
")",
"is",
"True",
")",
"assert",
"AXIS_DOMAIN",
"not",
"in",
"hass",
".",
"data"
] | [
30,
0
] | [
41,
39
] | python | en | ['en', 'en', 'en'] | True |
test_no_binary_sensors | (hass) | Test that no sensors in Axis results in no sensor entities. | Test that no sensors in Axis results in no sensor entities. | async def test_no_binary_sensors(hass):
"""Test that no sensors in Axis results in no sensor entities."""
await setup_axis_integration(hass)
assert not hass.states.async_entity_ids(BINARY_SENSOR_DOMAIN) | [
"async",
"def",
"test_no_binary_sensors",
"(",
"hass",
")",
":",
"await",
"setup_axis_integration",
"(",
"hass",
")",
"assert",
"not",
"hass",
".",
"states",
".",
"async_entity_ids",
"(",
"BINARY_SENSOR_DOMAIN",
")"
] | [
44,
0
] | [
48,
65
] | python | en | ['en', 'en', 'en'] | True |
test_binary_sensors | (hass) | Test that sensors are loaded properly. | Test that sensors are loaded properly. | async def test_binary_sensors(hass):
"""Test that sensors are loaded properly."""
config_entry = await setup_axis_integration(hass)
device = hass.data[AXIS_DOMAIN][config_entry.unique_id]
for event in EVENTS:
device.api.event.process_event(event)
await hass.async_block_till_done()
assert len(hass.states.async_entity_ids(BINARY_SENSOR_DOMAIN)) == 2
pir = hass.states.get(f"{BINARY_SENSOR_DOMAIN}.{NAME}_pir_0")
assert pir.state == STATE_OFF
assert pir.name == f"{NAME} PIR 0"
assert pir.attributes["device_class"] == DEVICE_CLASS_MOTION
vmd4 = hass.states.get(f"{BINARY_SENSOR_DOMAIN}.{NAME}_vmd4_profile_1")
assert vmd4.state == STATE_ON
assert vmd4.name == f"{NAME} VMD4 Profile 1"
assert vmd4.attributes["device_class"] == DEVICE_CLASS_MOTION | [
"async",
"def",
"test_binary_sensors",
"(",
"hass",
")",
":",
"config_entry",
"=",
"await",
"setup_axis_integration",
"(",
"hass",
")",
"device",
"=",
"hass",
".",
"data",
"[",
"AXIS_DOMAIN",
"]",
"[",
"config_entry",
".",
"unique_id",
"]",
"for",
"event",
"in",
"EVENTS",
":",
"device",
".",
"api",
".",
"event",
".",
"process_event",
"(",
"event",
")",
"await",
"hass",
".",
"async_block_till_done",
"(",
")",
"assert",
"len",
"(",
"hass",
".",
"states",
".",
"async_entity_ids",
"(",
"BINARY_SENSOR_DOMAIN",
")",
")",
"==",
"2",
"pir",
"=",
"hass",
".",
"states",
".",
"get",
"(",
"f\"{BINARY_SENSOR_DOMAIN}.{NAME}_pir_0\"",
")",
"assert",
"pir",
".",
"state",
"==",
"STATE_OFF",
"assert",
"pir",
".",
"name",
"==",
"f\"{NAME} PIR 0\"",
"assert",
"pir",
".",
"attributes",
"[",
"\"device_class\"",
"]",
"==",
"DEVICE_CLASS_MOTION",
"vmd4",
"=",
"hass",
".",
"states",
".",
"get",
"(",
"f\"{BINARY_SENSOR_DOMAIN}.{NAME}_vmd4_profile_1\"",
")",
"assert",
"vmd4",
".",
"state",
"==",
"STATE_ON",
"assert",
"vmd4",
".",
"name",
"==",
"f\"{NAME} VMD4 Profile 1\"",
"assert",
"vmd4",
".",
"attributes",
"[",
"\"device_class\"",
"]",
"==",
"DEVICE_CLASS_MOTION"
] | [
51,
0
] | [
70,
65
] | python | en | ['en', 'en', 'en'] | True |
ActorCritic.choose_action | (self, state: np.ndarray) | Use the actor (policy) model to generate stochastic actions.
Args:
state: Input to the actor model.
Returns:
Actions and corresponding log probabilities.
| Use the actor (policy) model to generate stochastic actions. | def choose_action(self, state: np.ndarray) -> Tuple[np.ndarray, np.ndarray]:
"""Use the actor (policy) model to generate stochastic actions.
Args:
state: Input to the actor model.
Returns:
Actions and corresponding log probabilities.
"""
state = torch.from_numpy(state).to(self.device)
is_single = len(state.shape) == 1
if is_single:
state = state.unsqueeze(dim=0)
action_prob = Categorical(self.model(state, task_name="actor", training=False))
action = action_prob.sample()
log_p = action_prob.log_prob(action)
action, log_p = action.cpu().numpy(), log_p.cpu().numpy()
return (action[0], log_p[0]) if is_single else (action, log_p) | [
"def",
"choose_action",
"(",
"self",
",",
"state",
":",
"np",
".",
"ndarray",
")",
"->",
"Tuple",
"[",
"np",
".",
"ndarray",
",",
"np",
".",
"ndarray",
"]",
":",
"state",
"=",
"torch",
".",
"from_numpy",
"(",
"state",
")",
".",
"to",
"(",
"self",
".",
"device",
")",
"is_single",
"=",
"len",
"(",
"state",
".",
"shape",
")",
"==",
"1",
"if",
"is_single",
":",
"state",
"=",
"state",
".",
"unsqueeze",
"(",
"dim",
"=",
"0",
")",
"action_prob",
"=",
"Categorical",
"(",
"self",
".",
"model",
"(",
"state",
",",
"task_name",
"=",
"\"actor\"",
",",
"training",
"=",
"False",
")",
")",
"action",
"=",
"action_prob",
".",
"sample",
"(",
")",
"log_p",
"=",
"action_prob",
".",
"log_prob",
"(",
"action",
")",
"action",
",",
"log_p",
"=",
"action",
".",
"cpu",
"(",
")",
".",
"numpy",
"(",
")",
",",
"log_p",
".",
"cpu",
"(",
")",
".",
"numpy",
"(",
")",
"return",
"(",
"action",
"[",
"0",
"]",
",",
"log_p",
"[",
"0",
"]",
")",
"if",
"is_single",
"else",
"(",
"action",
",",
"log_p",
")"
] | [
73,
4
] | [
91,
70
] | python | en | ['en', 'en', 'en'] | True |
mocked_upb | (sync_complete=True, config_ok=True) | Mock UPB lib. | Mock UPB lib. | def mocked_upb(sync_complete=True, config_ok=True):
"""Mock UPB lib."""
def _upb_lib_connect(callback):
callback()
upb_mock = MagicMock()
type(upb_mock).network_id = PropertyMock(return_value="42")
type(upb_mock).config_ok = PropertyMock(return_value=config_ok)
if sync_complete:
upb_mock.connect.side_effect = _upb_lib_connect
return patch(
"homeassistant.components.upb.config_flow.upb_lib.UpbPim", return_value=upb_mock
) | [
"def",
"mocked_upb",
"(",
"sync_complete",
"=",
"True",
",",
"config_ok",
"=",
"True",
")",
":",
"def",
"_upb_lib_connect",
"(",
"callback",
")",
":",
"callback",
"(",
")",
"upb_mock",
"=",
"MagicMock",
"(",
")",
"type",
"(",
"upb_mock",
")",
".",
"network_id",
"=",
"PropertyMock",
"(",
"return_value",
"=",
"\"42\"",
")",
"type",
"(",
"upb_mock",
")",
".",
"config_ok",
"=",
"PropertyMock",
"(",
"return_value",
"=",
"config_ok",
")",
"if",
"sync_complete",
":",
"upb_mock",
".",
"connect",
".",
"side_effect",
"=",
"_upb_lib_connect",
"return",
"patch",
"(",
"\"homeassistant.components.upb.config_flow.upb_lib.UpbPim\"",
",",
"return_value",
"=",
"upb_mock",
")"
] | [
8,
0
] | [
21,
5
] | python | en | ['nl', 'uz', 'en'] | False |
valid_tcp_flow | (hass, sync_complete=True, config_ok=True) | Get result dict that are standard for most tests. | Get result dict that are standard for most tests. | async def valid_tcp_flow(hass, sync_complete=True, config_ok=True):
"""Get result dict that are standard for most tests."""
await setup.async_setup_component(hass, "persistent_notification", {})
with mocked_upb(sync_complete, config_ok), patch(
"homeassistant.components.upb.async_setup_entry", return_value=True
):
flow = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_USER}
)
result = await hass.config_entries.flow.async_configure(
flow["flow_id"],
{"protocol": "TCP", "address": "1.2.3.4", "file_path": "upb.upe"},
)
return result | [
"async",
"def",
"valid_tcp_flow",
"(",
"hass",
",",
"sync_complete",
"=",
"True",
",",
"config_ok",
"=",
"True",
")",
":",
"await",
"setup",
".",
"async_setup_component",
"(",
"hass",
",",
"\"persistent_notification\"",
",",
"{",
"}",
")",
"with",
"mocked_upb",
"(",
"sync_complete",
",",
"config_ok",
")",
",",
"patch",
"(",
"\"homeassistant.components.upb.async_setup_entry\"",
",",
"return_value",
"=",
"True",
")",
":",
"flow",
"=",
"await",
"hass",
".",
"config_entries",
".",
"flow",
".",
"async_init",
"(",
"DOMAIN",
",",
"context",
"=",
"{",
"\"source\"",
":",
"config_entries",
".",
"SOURCE_USER",
"}",
")",
"result",
"=",
"await",
"hass",
".",
"config_entries",
".",
"flow",
".",
"async_configure",
"(",
"flow",
"[",
"\"flow_id\"",
"]",
",",
"{",
"\"protocol\"",
":",
"\"TCP\"",
",",
"\"address\"",
":",
"\"1.2.3.4\"",
",",
"\"file_path\"",
":",
"\"upb.upe\"",
"}",
",",
")",
"return",
"result"
] | [
24,
0
] | [
37,
17
] | python | en | ['en', 'en', 'en'] | True |
test_full_upb_flow_with_serial_port | (hass) | Test a full UPB config flow with serial port. | Test a full UPB config flow with serial port. | async def test_full_upb_flow_with_serial_port(hass):
"""Test a full UPB config flow with serial port."""
await setup.async_setup_component(hass, "persistent_notification", {})
with mocked_upb(), patch(
"homeassistant.components.upb.async_setup", return_value=True
) as mock_setup, patch(
"homeassistant.components.upb.async_setup_entry", return_value=True
) as mock_setup_entry:
flow = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_USER}
)
result = await hass.config_entries.flow.async_configure(
flow["flow_id"],
{
"protocol": "Serial port",
"address": "/dev/ttyS0:115200",
"file_path": "upb.upe",
},
)
await hass.async_block_till_done()
assert flow["type"] == "form"
assert flow["errors"] == {}
assert result["type"] == "create_entry"
assert result["title"] == "UPB"
assert result["data"] == {
"host": "serial:///dev/ttyS0:115200",
"file_path": "upb.upe",
}
assert len(mock_setup.mock_calls) == 1
assert len(mock_setup_entry.mock_calls) == 1 | [
"async",
"def",
"test_full_upb_flow_with_serial_port",
"(",
"hass",
")",
":",
"await",
"setup",
".",
"async_setup_component",
"(",
"hass",
",",
"\"persistent_notification\"",
",",
"{",
"}",
")",
"with",
"mocked_upb",
"(",
")",
",",
"patch",
"(",
"\"homeassistant.components.upb.async_setup\"",
",",
"return_value",
"=",
"True",
")",
"as",
"mock_setup",
",",
"patch",
"(",
"\"homeassistant.components.upb.async_setup_entry\"",
",",
"return_value",
"=",
"True",
")",
"as",
"mock_setup_entry",
":",
"flow",
"=",
"await",
"hass",
".",
"config_entries",
".",
"flow",
".",
"async_init",
"(",
"DOMAIN",
",",
"context",
"=",
"{",
"\"source\"",
":",
"config_entries",
".",
"SOURCE_USER",
"}",
")",
"result",
"=",
"await",
"hass",
".",
"config_entries",
".",
"flow",
".",
"async_configure",
"(",
"flow",
"[",
"\"flow_id\"",
"]",
",",
"{",
"\"protocol\"",
":",
"\"Serial port\"",
",",
"\"address\"",
":",
"\"/dev/ttyS0:115200\"",
",",
"\"file_path\"",
":",
"\"upb.upe\"",
",",
"}",
",",
")",
"await",
"hass",
".",
"async_block_till_done",
"(",
")",
"assert",
"flow",
"[",
"\"type\"",
"]",
"==",
"\"form\"",
"assert",
"flow",
"[",
"\"errors\"",
"]",
"==",
"{",
"}",
"assert",
"result",
"[",
"\"type\"",
"]",
"==",
"\"create_entry\"",
"assert",
"result",
"[",
"\"title\"",
"]",
"==",
"\"UPB\"",
"assert",
"result",
"[",
"\"data\"",
"]",
"==",
"{",
"\"host\"",
":",
"\"serial:///dev/ttyS0:115200\"",
",",
"\"file_path\"",
":",
"\"upb.upe\"",
",",
"}",
"assert",
"len",
"(",
"mock_setup",
".",
"mock_calls",
")",
"==",
"1",
"assert",
"len",
"(",
"mock_setup_entry",
".",
"mock_calls",
")",
"==",
"1"
] | [
40,
0
] | [
72,
48
] | python | en | ['en', 'en', 'en'] | True |
test_form_user_with_tcp_upb | (hass) | Test we can setup a serial upb. | Test we can setup a serial upb. | async def test_form_user_with_tcp_upb(hass):
"""Test we can setup a serial upb."""
result = await valid_tcp_flow(hass)
assert result["type"] == "create_entry"
assert result["data"] == {"host": "tcp://1.2.3.4", "file_path": "upb.upe"}
await hass.async_block_till_done() | [
"async",
"def",
"test_form_user_with_tcp_upb",
"(",
"hass",
")",
":",
"result",
"=",
"await",
"valid_tcp_flow",
"(",
"hass",
")",
"assert",
"result",
"[",
"\"type\"",
"]",
"==",
"\"create_entry\"",
"assert",
"result",
"[",
"\"data\"",
"]",
"==",
"{",
"\"host\"",
":",
"\"tcp://1.2.3.4\"",
",",
"\"file_path\"",
":",
"\"upb.upe\"",
"}",
"await",
"hass",
".",
"async_block_till_done",
"(",
")"
] | [
75,
0
] | [
80,
38
] | python | en | ['en', 'en', 'en'] | True |
test_form_cannot_connect | (hass) | Test we handle cannot connect error. | Test we handle cannot connect error. | async def test_form_cannot_connect(hass):
"""Test we handle cannot connect error."""
from asyncio import TimeoutError
with patch(
"homeassistant.components.upb.config_flow.async_timeout.timeout",
side_effect=TimeoutError,
):
result = await valid_tcp_flow(hass, sync_complete=False)
assert result["type"] == "form"
assert result["errors"] == {"base": "cannot_connect"} | [
"async",
"def",
"test_form_cannot_connect",
"(",
"hass",
")",
":",
"from",
"asyncio",
"import",
"TimeoutError",
"with",
"patch",
"(",
"\"homeassistant.components.upb.config_flow.async_timeout.timeout\"",
",",
"side_effect",
"=",
"TimeoutError",
",",
")",
":",
"result",
"=",
"await",
"valid_tcp_flow",
"(",
"hass",
",",
"sync_complete",
"=",
"False",
")",
"assert",
"result",
"[",
"\"type\"",
"]",
"==",
"\"form\"",
"assert",
"result",
"[",
"\"errors\"",
"]",
"==",
"{",
"\"base\"",
":",
"\"cannot_connect\"",
"}"
] | [
83,
0
] | [
94,
57
] | python | en | ['en', 'en', 'en'] | True |
test_form_missing_upb_file | (hass) | Test we handle cannot connect error. | Test we handle cannot connect error. | async def test_form_missing_upb_file(hass):
"""Test we handle cannot connect error."""
result = await valid_tcp_flow(hass, config_ok=False)
assert result["type"] == "form"
assert result["errors"] == {"base": "invalid_upb_file"} | [
"async",
"def",
"test_form_missing_upb_file",
"(",
"hass",
")",
":",
"result",
"=",
"await",
"valid_tcp_flow",
"(",
"hass",
",",
"config_ok",
"=",
"False",
")",
"assert",
"result",
"[",
"\"type\"",
"]",
"==",
"\"form\"",
"assert",
"result",
"[",
"\"errors\"",
"]",
"==",
"{",
"\"base\"",
":",
"\"invalid_upb_file\"",
"}"
] | [
97,
0
] | [
101,
59
] | python | en | ['en', 'en', 'en'] | True |
test_form_user_with_already_configured | (hass) | Test we can setup a TCP upb. | Test we can setup a TCP upb. | async def test_form_user_with_already_configured(hass):
"""Test we can setup a TCP upb."""
_ = await valid_tcp_flow(hass)
result2 = await valid_tcp_flow(hass)
assert result2["type"] == "abort"
assert result2["reason"] == "already_configured"
await hass.async_block_till_done() | [
"async",
"def",
"test_form_user_with_already_configured",
"(",
"hass",
")",
":",
"_",
"=",
"await",
"valid_tcp_flow",
"(",
"hass",
")",
"result2",
"=",
"await",
"valid_tcp_flow",
"(",
"hass",
")",
"assert",
"result2",
"[",
"\"type\"",
"]",
"==",
"\"abort\"",
"assert",
"result2",
"[",
"\"reason\"",
"]",
"==",
"\"already_configured\"",
"await",
"hass",
".",
"async_block_till_done",
"(",
")"
] | [
104,
0
] | [
110,
38
] | python | en | ['en', 'bg', 'en'] | True |
test_form_import | (hass) | Test we get the form with import source. | Test we get the form with import source. | async def test_form_import(hass):
"""Test we get the form with import source."""
await setup.async_setup_component(hass, "persistent_notification", {})
with mocked_upb(), patch(
"homeassistant.components.upb.async_setup", return_value=True
) as mock_setup, patch(
"homeassistant.components.upb.async_setup_entry", return_value=True
) as mock_setup_entry:
result = await hass.config_entries.flow.async_init(
DOMAIN,
context={"source": config_entries.SOURCE_IMPORT},
data={"host": "tcp://42.4.2.42", "file_path": "upb.upe"},
)
await hass.async_block_till_done()
assert result["type"] == "create_entry"
assert result["title"] == "UPB"
assert result["data"] == {"host": "tcp://42.4.2.42", "file_path": "upb.upe"}
assert len(mock_setup.mock_calls) == 1
assert len(mock_setup_entry.mock_calls) == 1 | [
"async",
"def",
"test_form_import",
"(",
"hass",
")",
":",
"await",
"setup",
".",
"async_setup_component",
"(",
"hass",
",",
"\"persistent_notification\"",
",",
"{",
"}",
")",
"with",
"mocked_upb",
"(",
")",
",",
"patch",
"(",
"\"homeassistant.components.upb.async_setup\"",
",",
"return_value",
"=",
"True",
")",
"as",
"mock_setup",
",",
"patch",
"(",
"\"homeassistant.components.upb.async_setup_entry\"",
",",
"return_value",
"=",
"True",
")",
"as",
"mock_setup_entry",
":",
"result",
"=",
"await",
"hass",
".",
"config_entries",
".",
"flow",
".",
"async_init",
"(",
"DOMAIN",
",",
"context",
"=",
"{",
"\"source\"",
":",
"config_entries",
".",
"SOURCE_IMPORT",
"}",
",",
"data",
"=",
"{",
"\"host\"",
":",
"\"tcp://42.4.2.42\"",
",",
"\"file_path\"",
":",
"\"upb.upe\"",
"}",
",",
")",
"await",
"hass",
".",
"async_block_till_done",
"(",
")",
"assert",
"result",
"[",
"\"type\"",
"]",
"==",
"\"create_entry\"",
"assert",
"result",
"[",
"\"title\"",
"]",
"==",
"\"UPB\"",
"assert",
"result",
"[",
"\"data\"",
"]",
"==",
"{",
"\"host\"",
":",
"\"tcp://42.4.2.42\"",
",",
"\"file_path\"",
":",
"\"upb.upe\"",
"}",
"assert",
"len",
"(",
"mock_setup",
".",
"mock_calls",
")",
"==",
"1",
"assert",
"len",
"(",
"mock_setup_entry",
".",
"mock_calls",
")",
"==",
"1"
] | [
113,
0
] | [
134,
48
] | python | en | ['en', 'en', 'en'] | True |
test_form_junk_input | (hass) | Test we get the form with import source. | Test we get the form with import source. | async def test_form_junk_input(hass):
"""Test we get the form with import source."""
await setup.async_setup_component(hass, "persistent_notification", {})
with mocked_upb():
result = await hass.config_entries.flow.async_init(
DOMAIN,
context={"source": config_entries.SOURCE_IMPORT},
data={"foo": "goo", "goo": "foo"},
)
assert result["type"] == "form"
assert result["errors"] == {"base": "unknown"}
await hass.async_block_till_done() | [
"async",
"def",
"test_form_junk_input",
"(",
"hass",
")",
":",
"await",
"setup",
".",
"async_setup_component",
"(",
"hass",
",",
"\"persistent_notification\"",
",",
"{",
"}",
")",
"with",
"mocked_upb",
"(",
")",
":",
"result",
"=",
"await",
"hass",
".",
"config_entries",
".",
"flow",
".",
"async_init",
"(",
"DOMAIN",
",",
"context",
"=",
"{",
"\"source\"",
":",
"config_entries",
".",
"SOURCE_IMPORT",
"}",
",",
"data",
"=",
"{",
"\"foo\"",
":",
"\"goo\"",
",",
"\"goo\"",
":",
"\"foo\"",
"}",
",",
")",
"assert",
"result",
"[",
"\"type\"",
"]",
"==",
"\"form\"",
"assert",
"result",
"[",
"\"errors\"",
"]",
"==",
"{",
"\"base\"",
":",
"\"unknown\"",
"}",
"await",
"hass",
".",
"async_block_till_done",
"(",
")"
] | [
137,
0
] | [
151,
38
] | python | en | ['en', 'en', 'en'] | True |
setup | (hass, config) | Listen for download events to download files. | Listen for download events to download files. | def setup(hass, config):
"""Listen for download events to download files."""
download_path = config[DOMAIN][CONF_DOWNLOAD_DIR]
# If path is relative, we assume relative to Home Assistant config dir
if not os.path.isabs(download_path):
download_path = hass.config.path(download_path)
if not os.path.isdir(download_path):
_LOGGER.error(
"Download path %s does not exist. File Downloader not active", download_path
)
return False
def download_file(service):
"""Start thread to download file specified in the URL."""
def do_download():
"""Download the file."""
try:
url = service.data[ATTR_URL]
subdir = service.data.get(ATTR_SUBDIR)
filename = service.data.get(ATTR_FILENAME)
overwrite = service.data.get(ATTR_OVERWRITE)
if subdir:
subdir = sanitize_filename(subdir)
final_path = None
req = requests.get(url, stream=True, timeout=10)
if req.status_code != HTTP_OK:
_LOGGER.warning(
"downloading '%s' failed, status_code=%d", url, req.status_code
)
hass.bus.fire(
f"{DOMAIN}_{DOWNLOAD_FAILED_EVENT}",
{"url": url, "filename": filename},
)
else:
if filename is None and "content-disposition" in req.headers:
match = re.findall(
r"filename=(\S+)", req.headers["content-disposition"]
)
if match:
filename = match[0].strip("'\" ")
if not filename:
filename = os.path.basename(url).strip()
if not filename:
filename = "ha_download"
# Remove stuff to ruin paths
filename = sanitize_filename(filename)
# Do we want to download to subdir, create if needed
if subdir:
subdir_path = os.path.join(download_path, subdir)
# Ensure subdir exist
if not os.path.isdir(subdir_path):
os.makedirs(subdir_path)
final_path = os.path.join(subdir_path, filename)
else:
final_path = os.path.join(download_path, filename)
path, ext = os.path.splitext(final_path)
# If file exist append a number.
# We test filename, filename_2..
if not overwrite:
tries = 1
final_path = path + ext
while os.path.isfile(final_path):
tries += 1
final_path = f"{path}_{tries}.{ext}"
_LOGGER.debug("%s -> %s", url, final_path)
with open(final_path, "wb") as fil:
for chunk in req.iter_content(1024):
fil.write(chunk)
_LOGGER.debug("Downloading of %s done", url)
hass.bus.fire(
f"{DOMAIN}_{DOWNLOAD_COMPLETED_EVENT}",
{"url": url, "filename": filename},
)
except requests.exceptions.ConnectionError:
_LOGGER.exception("ConnectionError occurred for %s", url)
hass.bus.fire(
f"{DOMAIN}_{DOWNLOAD_FAILED_EVENT}",
{"url": url, "filename": filename},
)
# Remove file if we started downloading but failed
if final_path and os.path.isfile(final_path):
os.remove(final_path)
threading.Thread(target=do_download).start()
hass.services.register(
DOMAIN,
SERVICE_DOWNLOAD_FILE,
download_file,
schema=SERVICE_DOWNLOAD_FILE_SCHEMA,
)
return True | [
"def",
"setup",
"(",
"hass",
",",
"config",
")",
":",
"download_path",
"=",
"config",
"[",
"DOMAIN",
"]",
"[",
"CONF_DOWNLOAD_DIR",
"]",
"# If path is relative, we assume relative to Home Assistant config dir",
"if",
"not",
"os",
".",
"path",
".",
"isabs",
"(",
"download_path",
")",
":",
"download_path",
"=",
"hass",
".",
"config",
".",
"path",
"(",
"download_path",
")",
"if",
"not",
"os",
".",
"path",
".",
"isdir",
"(",
"download_path",
")",
":",
"_LOGGER",
".",
"error",
"(",
"\"Download path %s does not exist. File Downloader not active\"",
",",
"download_path",
")",
"return",
"False",
"def",
"download_file",
"(",
"service",
")",
":",
"\"\"\"Start thread to download file specified in the URL.\"\"\"",
"def",
"do_download",
"(",
")",
":",
"\"\"\"Download the file.\"\"\"",
"try",
":",
"url",
"=",
"service",
".",
"data",
"[",
"ATTR_URL",
"]",
"subdir",
"=",
"service",
".",
"data",
".",
"get",
"(",
"ATTR_SUBDIR",
")",
"filename",
"=",
"service",
".",
"data",
".",
"get",
"(",
"ATTR_FILENAME",
")",
"overwrite",
"=",
"service",
".",
"data",
".",
"get",
"(",
"ATTR_OVERWRITE",
")",
"if",
"subdir",
":",
"subdir",
"=",
"sanitize_filename",
"(",
"subdir",
")",
"final_path",
"=",
"None",
"req",
"=",
"requests",
".",
"get",
"(",
"url",
",",
"stream",
"=",
"True",
",",
"timeout",
"=",
"10",
")",
"if",
"req",
".",
"status_code",
"!=",
"HTTP_OK",
":",
"_LOGGER",
".",
"warning",
"(",
"\"downloading '%s' failed, status_code=%d\"",
",",
"url",
",",
"req",
".",
"status_code",
")",
"hass",
".",
"bus",
".",
"fire",
"(",
"f\"{DOMAIN}_{DOWNLOAD_FAILED_EVENT}\"",
",",
"{",
"\"url\"",
":",
"url",
",",
"\"filename\"",
":",
"filename",
"}",
",",
")",
"else",
":",
"if",
"filename",
"is",
"None",
"and",
"\"content-disposition\"",
"in",
"req",
".",
"headers",
":",
"match",
"=",
"re",
".",
"findall",
"(",
"r\"filename=(\\S+)\"",
",",
"req",
".",
"headers",
"[",
"\"content-disposition\"",
"]",
")",
"if",
"match",
":",
"filename",
"=",
"match",
"[",
"0",
"]",
".",
"strip",
"(",
"\"'\\\" \"",
")",
"if",
"not",
"filename",
":",
"filename",
"=",
"os",
".",
"path",
".",
"basename",
"(",
"url",
")",
".",
"strip",
"(",
")",
"if",
"not",
"filename",
":",
"filename",
"=",
"\"ha_download\"",
"# Remove stuff to ruin paths",
"filename",
"=",
"sanitize_filename",
"(",
"filename",
")",
"# Do we want to download to subdir, create if needed",
"if",
"subdir",
":",
"subdir_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"download_path",
",",
"subdir",
")",
"# Ensure subdir exist",
"if",
"not",
"os",
".",
"path",
".",
"isdir",
"(",
"subdir_path",
")",
":",
"os",
".",
"makedirs",
"(",
"subdir_path",
")",
"final_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"subdir_path",
",",
"filename",
")",
"else",
":",
"final_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"download_path",
",",
"filename",
")",
"path",
",",
"ext",
"=",
"os",
".",
"path",
".",
"splitext",
"(",
"final_path",
")",
"# If file exist append a number.",
"# We test filename, filename_2..",
"if",
"not",
"overwrite",
":",
"tries",
"=",
"1",
"final_path",
"=",
"path",
"+",
"ext",
"while",
"os",
".",
"path",
".",
"isfile",
"(",
"final_path",
")",
":",
"tries",
"+=",
"1",
"final_path",
"=",
"f\"{path}_{tries}.{ext}\"",
"_LOGGER",
".",
"debug",
"(",
"\"%s -> %s\"",
",",
"url",
",",
"final_path",
")",
"with",
"open",
"(",
"final_path",
",",
"\"wb\"",
")",
"as",
"fil",
":",
"for",
"chunk",
"in",
"req",
".",
"iter_content",
"(",
"1024",
")",
":",
"fil",
".",
"write",
"(",
"chunk",
")",
"_LOGGER",
".",
"debug",
"(",
"\"Downloading of %s done\"",
",",
"url",
")",
"hass",
".",
"bus",
".",
"fire",
"(",
"f\"{DOMAIN}_{DOWNLOAD_COMPLETED_EVENT}\"",
",",
"{",
"\"url\"",
":",
"url",
",",
"\"filename\"",
":",
"filename",
"}",
",",
")",
"except",
"requests",
".",
"exceptions",
".",
"ConnectionError",
":",
"_LOGGER",
".",
"exception",
"(",
"\"ConnectionError occurred for %s\"",
",",
"url",
")",
"hass",
".",
"bus",
".",
"fire",
"(",
"f\"{DOMAIN}_{DOWNLOAD_FAILED_EVENT}\"",
",",
"{",
"\"url\"",
":",
"url",
",",
"\"filename\"",
":",
"filename",
"}",
",",
")",
"# Remove file if we started downloading but failed",
"if",
"final_path",
"and",
"os",
".",
"path",
".",
"isfile",
"(",
"final_path",
")",
":",
"os",
".",
"remove",
"(",
"final_path",
")",
"threading",
".",
"Thread",
"(",
"target",
"=",
"do_download",
")",
".",
"start",
"(",
")",
"hass",
".",
"services",
".",
"register",
"(",
"DOMAIN",
",",
"SERVICE_DOWNLOAD_FILE",
",",
"download_file",
",",
"schema",
"=",
"SERVICE_DOWNLOAD_FILE_SCHEMA",
",",
")",
"return",
"True"
] | [
43,
0
] | [
163,
15
] | python | en | ['en', 'en', 'en'] | True |
async_setup_platform | (hass, config, async_add_entities, discovery_info=None) | Set up the Orange Pi GPIO platform. | Set up the Orange Pi GPIO platform. | async def async_setup_platform(hass, config, async_add_entities, discovery_info=None):
"""Set up the Orange Pi GPIO platform."""
binary_sensors = []
invert_logic = config[CONF_INVERT_LOGIC]
pin_mode = config[CONF_PIN_MODE]
ports = config[CONF_PORTS]
setup_mode(pin_mode)
for port_num, port_name in ports.items():
binary_sensors.append(
OPiGPIOBinarySensor(hass, port_name, port_num, invert_logic)
)
async_add_entities(binary_sensors) | [
"async",
"def",
"async_setup_platform",
"(",
"hass",
",",
"config",
",",
"async_add_entities",
",",
"discovery_info",
"=",
"None",
")",
":",
"binary_sensors",
"=",
"[",
"]",
"invert_logic",
"=",
"config",
"[",
"CONF_INVERT_LOGIC",
"]",
"pin_mode",
"=",
"config",
"[",
"CONF_PIN_MODE",
"]",
"ports",
"=",
"config",
"[",
"CONF_PORTS",
"]",
"setup_mode",
"(",
"pin_mode",
")",
"for",
"port_num",
",",
"port_name",
"in",
"ports",
".",
"items",
"(",
")",
":",
"binary_sensors",
".",
"append",
"(",
"OPiGPIOBinarySensor",
"(",
"hass",
",",
"port_name",
",",
"port_num",
",",
"invert_logic",
")",
")",
"async_add_entities",
"(",
"binary_sensors",
")"
] | [
10,
0
] | [
23,
38
] | python | en | ['en', 'hr', 'en'] | True |
OPiGPIOBinarySensor.__init__ | (self, hass, name, port, invert_logic) | Initialize the Orange Pi binary sensor. | Initialize the Orange Pi binary sensor. | def __init__(self, hass, name, port, invert_logic):
"""Initialize the Orange Pi binary sensor."""
self._name = name
self._port = port
self._invert_logic = invert_logic
self._state = None | [
"def",
"__init__",
"(",
"self",
",",
"hass",
",",
"name",
",",
"port",
",",
"invert_logic",
")",
":",
"self",
".",
"_name",
"=",
"name",
"self",
".",
"_port",
"=",
"port",
"self",
".",
"_invert_logic",
"=",
"invert_logic",
"self",
".",
"_state",
"=",
"None"
] | [
29,
4
] | [
34,
26
] | python | en | ['en', 'hr', 'en'] | True |
OPiGPIOBinarySensor.async_added_to_hass | (self) | Run when entity about to be added to hass. | Run when entity about to be added to hass. | async def async_added_to_hass(self):
"""Run when entity about to be added to hass."""
def gpio_edge_listener(port):
"""Update GPIO when edge change is detected."""
self.schedule_update_ha_state(True)
def setup_entity():
setup_input(self._port)
edge_detect(self._port, gpio_edge_listener)
self.schedule_update_ha_state(True)
await self.hass.async_add_executor_job(setup_entity) | [
"async",
"def",
"async_added_to_hass",
"(",
"self",
")",
":",
"def",
"gpio_edge_listener",
"(",
"port",
")",
":",
"\"\"\"Update GPIO when edge change is detected.\"\"\"",
"self",
".",
"schedule_update_ha_state",
"(",
"True",
")",
"def",
"setup_entity",
"(",
")",
":",
"setup_input",
"(",
"self",
".",
"_port",
")",
"edge_detect",
"(",
"self",
".",
"_port",
",",
"gpio_edge_listener",
")",
"self",
".",
"schedule_update_ha_state",
"(",
"True",
")",
"await",
"self",
".",
"hass",
".",
"async_add_executor_job",
"(",
"setup_entity",
")"
] | [
36,
4
] | [
48,
60
] | python | en | ['en', 'en', 'en'] | True |
OPiGPIOBinarySensor.should_poll | (self) | No polling needed. | No polling needed. | def should_poll(self):
"""No polling needed."""
return False | [
"def",
"should_poll",
"(",
"self",
")",
":",
"return",
"False"
] | [
51,
4
] | [
53,
20
] | python | en | ['en', 'en', 'en'] | True |
OPiGPIOBinarySensor.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"
] | [
56,
4
] | [
58,
25
] | python | en | ['en', 'mi', 'en'] | True |
OPiGPIOBinarySensor.is_on | (self) | Return the state of the entity. | Return the state of the entity. | def is_on(self):
"""Return the state of the entity."""
return self._state != self._invert_logic | [
"def",
"is_on",
"(",
"self",
")",
":",
"return",
"self",
".",
"_state",
"!=",
"self",
".",
"_invert_logic"
] | [
61,
4
] | [
63,
48
] | python | en | ['en', 'en', 'en'] | True |
OPiGPIOBinarySensor.update | (self) | Update state with new GPIO data. | Update state with new GPIO data. | def update(self):
"""Update state with new GPIO data."""
self._state = read_input(self._port) | [
"def",
"update",
"(",
"self",
")",
":",
"self",
".",
"_state",
"=",
"read_input",
"(",
"self",
".",
"_port",
")"
] | [
65,
4
] | [
67,
44
] | python | en | ['en', 'en', 'en'] | True |
async_setup_entry | (hass, entry, async_add_entities) | Set up the Netatmo camera light platform. | Set up the Netatmo camera light platform. | async def async_setup_entry(hass, entry, async_add_entities):
"""Set up the Netatmo camera light platform."""
if "access_camera" not in entry.data["token"]["scope"]:
_LOGGER.info(
"Cameras are currently not supported with this authentication method"
)
return
data_handler = hass.data[DOMAIN][entry.entry_id][DATA_HANDLER]
async def get_entities():
"""Retrieve Netatmo entities."""
await data_handler.register_data_class(
CAMERA_DATA_CLASS_NAME, CAMERA_DATA_CLASS_NAME, None
)
entities = []
all_cameras = []
if CAMERA_DATA_CLASS_NAME not in data_handler.data:
raise PlatformNotReady
try:
for home in data_handler.data[CAMERA_DATA_CLASS_NAME].cameras.values():
for camera in home.values():
all_cameras.append(camera)
except pyatmo.NoDevice:
_LOGGER.debug("No cameras found")
for camera in all_cameras:
if camera["type"] == "NOC":
if not data_handler.webhook:
raise PlatformNotReady
_LOGGER.debug("Adding camera light %s %s", camera["id"], camera["name"])
entities.append(
NetatmoLight(
data_handler,
camera["id"],
camera["type"],
camera["home_id"],
)
)
return entities
async_add_entities(await get_entities(), True) | [
"async",
"def",
"async_setup_entry",
"(",
"hass",
",",
"entry",
",",
"async_add_entities",
")",
":",
"if",
"\"access_camera\"",
"not",
"in",
"entry",
".",
"data",
"[",
"\"token\"",
"]",
"[",
"\"scope\"",
"]",
":",
"_LOGGER",
".",
"info",
"(",
"\"Cameras are currently not supported with this authentication method\"",
")",
"return",
"data_handler",
"=",
"hass",
".",
"data",
"[",
"DOMAIN",
"]",
"[",
"entry",
".",
"entry_id",
"]",
"[",
"DATA_HANDLER",
"]",
"async",
"def",
"get_entities",
"(",
")",
":",
"\"\"\"Retrieve Netatmo entities.\"\"\"",
"await",
"data_handler",
".",
"register_data_class",
"(",
"CAMERA_DATA_CLASS_NAME",
",",
"CAMERA_DATA_CLASS_NAME",
",",
"None",
")",
"entities",
"=",
"[",
"]",
"all_cameras",
"=",
"[",
"]",
"if",
"CAMERA_DATA_CLASS_NAME",
"not",
"in",
"data_handler",
".",
"data",
":",
"raise",
"PlatformNotReady",
"try",
":",
"for",
"home",
"in",
"data_handler",
".",
"data",
"[",
"CAMERA_DATA_CLASS_NAME",
"]",
".",
"cameras",
".",
"values",
"(",
")",
":",
"for",
"camera",
"in",
"home",
".",
"values",
"(",
")",
":",
"all_cameras",
".",
"append",
"(",
"camera",
")",
"except",
"pyatmo",
".",
"NoDevice",
":",
"_LOGGER",
".",
"debug",
"(",
"\"No cameras found\"",
")",
"for",
"camera",
"in",
"all_cameras",
":",
"if",
"camera",
"[",
"\"type\"",
"]",
"==",
"\"NOC\"",
":",
"if",
"not",
"data_handler",
".",
"webhook",
":",
"raise",
"PlatformNotReady",
"_LOGGER",
".",
"debug",
"(",
"\"Adding camera light %s %s\"",
",",
"camera",
"[",
"\"id\"",
"]",
",",
"camera",
"[",
"\"name\"",
"]",
")",
"entities",
".",
"append",
"(",
"NetatmoLight",
"(",
"data_handler",
",",
"camera",
"[",
"\"id\"",
"]",
",",
"camera",
"[",
"\"type\"",
"]",
",",
"camera",
"[",
"\"home_id\"",
"]",
",",
")",
")",
"return",
"entities",
"async_add_entities",
"(",
"await",
"get_entities",
"(",
")",
",",
"True",
")"
] | [
23,
0
] | [
70,
50
] | python | en | ['en', 'pt', 'en'] | True |
NetatmoLight.__init__ | (
self,
data_handler: NetatmoDataHandler,
camera_id: str,
camera_type: str,
home_id: str,
) | Initialize a Netatmo Presence camera light. | Initialize a Netatmo Presence camera light. | def __init__(
self,
data_handler: NetatmoDataHandler,
camera_id: str,
camera_type: str,
home_id: str,
):
"""Initialize a Netatmo Presence camera light."""
LightEntity.__init__(self)
super().__init__(data_handler)
self._data_classes.append(
{"name": CAMERA_DATA_CLASS_NAME, SIGNAL_NAME: CAMERA_DATA_CLASS_NAME}
)
self._id = camera_id
self._home_id = home_id
self._model = camera_type
self._device_name = self._data.get_camera(camera_id).get("name")
self._name = f"{MANUFACTURER} {self._device_name}"
self._is_on = False
self._unique_id = f"{self._id}-light" | [
"def",
"__init__",
"(",
"self",
",",
"data_handler",
":",
"NetatmoDataHandler",
",",
"camera_id",
":",
"str",
",",
"camera_type",
":",
"str",
",",
"home_id",
":",
"str",
",",
")",
":",
"LightEntity",
".",
"__init__",
"(",
"self",
")",
"super",
"(",
")",
".",
"__init__",
"(",
"data_handler",
")",
"self",
".",
"_data_classes",
".",
"append",
"(",
"{",
"\"name\"",
":",
"CAMERA_DATA_CLASS_NAME",
",",
"SIGNAL_NAME",
":",
"CAMERA_DATA_CLASS_NAME",
"}",
")",
"self",
".",
"_id",
"=",
"camera_id",
"self",
".",
"_home_id",
"=",
"home_id",
"self",
".",
"_model",
"=",
"camera_type",
"self",
".",
"_device_name",
"=",
"self",
".",
"_data",
".",
"get_camera",
"(",
"camera_id",
")",
".",
"get",
"(",
"\"name\"",
")",
"self",
".",
"_name",
"=",
"f\"{MANUFACTURER} {self._device_name}\"",
"self",
".",
"_is_on",
"=",
"False",
"self",
".",
"_unique_id",
"=",
"f\"{self._id}-light\""
] | [
76,
4
] | [
96,
45
] | python | cs | ['es', 'cs', 'it'] | False |
NetatmoLight.async_added_to_hass | (self) | Entity created. | Entity created. | async def async_added_to_hass(self) -> None:
"""Entity created."""
await super().async_added_to_hass()
self._listeners.append(
async_dispatcher_connect(
self.hass,
f"signal-{DOMAIN}-webhook-{EVENT_TYPE_LIGHT_MODE}",
self.handle_event,
)
) | [
"async",
"def",
"async_added_to_hass",
"(",
"self",
")",
"->",
"None",
":",
"await",
"super",
"(",
")",
".",
"async_added_to_hass",
"(",
")",
"self",
".",
"_listeners",
".",
"append",
"(",
"async_dispatcher_connect",
"(",
"self",
".",
"hass",
",",
"f\"signal-{DOMAIN}-webhook-{EVENT_TYPE_LIGHT_MODE}\"",
",",
"self",
".",
"handle_event",
",",
")",
")"
] | [
98,
4
] | [
108,
9
] | python | en | ['en', 'sm', 'en'] | False |
NetatmoLight.handle_event | (self, event) | Handle webhook events. | Handle webhook events. | def handle_event(self, event):
"""Handle webhook events."""
data = event["data"]
if not data.get("camera_id"):
return
if (
data["home_id"] == self._home_id
and data["camera_id"] == self._id
and data["push_type"] == "NOC-light_mode"
):
self._is_on = bool(data["sub_type"] == "on")
self.async_write_ha_state()
return | [
"def",
"handle_event",
"(",
"self",
",",
"event",
")",
":",
"data",
"=",
"event",
"[",
"\"data\"",
"]",
"if",
"not",
"data",
".",
"get",
"(",
"\"camera_id\"",
")",
":",
"return",
"if",
"(",
"data",
"[",
"\"home_id\"",
"]",
"==",
"self",
".",
"_home_id",
"and",
"data",
"[",
"\"camera_id\"",
"]",
"==",
"self",
".",
"_id",
"and",
"data",
"[",
"\"push_type\"",
"]",
"==",
"\"NOC-light_mode\"",
")",
":",
"self",
".",
"_is_on",
"=",
"bool",
"(",
"data",
"[",
"\"sub_type\"",
"]",
"==",
"\"on\"",
")",
"self",
".",
"async_write_ha_state",
"(",
")",
"return"
] | [
111,
4
] | [
126,
18
] | python | en | ['eu', 'xh', 'en'] | False |
NetatmoLight.is_on | (self) | Return true if light is on. | Return true if light is on. | def is_on(self):
"""Return true if light is on."""
return self._is_on | [
"def",
"is_on",
"(",
"self",
")",
":",
"return",
"self",
".",
"_is_on"
] | [
129,
4
] | [
131,
26
] | python | en | ['en', 'et', 'en'] | True |
NetatmoLight.turn_on | (self, **kwargs) | Turn camera floodlight on. | Turn camera floodlight on. | def turn_on(self, **kwargs):
"""Turn camera floodlight on."""
_LOGGER.debug("Turn camera '%s' on", self._name)
self._data.set_state(
home_id=self._home_id,
camera_id=self._id,
floodlight="on",
) | [
"def",
"turn_on",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"_LOGGER",
".",
"debug",
"(",
"\"Turn camera '%s' on\"",
",",
"self",
".",
"_name",
")",
"self",
".",
"_data",
".",
"set_state",
"(",
"home_id",
"=",
"self",
".",
"_home_id",
",",
"camera_id",
"=",
"self",
".",
"_id",
",",
"floodlight",
"=",
"\"on\"",
",",
")"
] | [
133,
4
] | [
140,
9
] | python | en | ['en', 'et', 'en'] | True |
NetatmoLight.turn_off | (self, **kwargs) | Turn camera floodlight into auto mode. | Turn camera floodlight into auto mode. | def turn_off(self, **kwargs):
"""Turn camera floodlight into auto mode."""
_LOGGER.debug("Turn camera '%s' to auto mode", self._name)
self._data.set_state(
home_id=self._home_id,
camera_id=self._id,
floodlight="auto",
) | [
"def",
"turn_off",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"_LOGGER",
".",
"debug",
"(",
"\"Turn camera '%s' to auto mode\"",
",",
"self",
".",
"_name",
")",
"self",
".",
"_data",
".",
"set_state",
"(",
"home_id",
"=",
"self",
".",
"_home_id",
",",
"camera_id",
"=",
"self",
".",
"_id",
",",
"floodlight",
"=",
"\"auto\"",
",",
")"
] | [
142,
4
] | [
149,
9
] | python | en | ['it', 'pt', 'en'] | False |
NetatmoLight.async_update_callback | (self) | Update the entity's state. | Update the entity's state. | def async_update_callback(self):
"""Update the entity's state."""
self._is_on = bool(self._data.get_light_state(self._id) == "on") | [
"def",
"async_update_callback",
"(",
"self",
")",
":",
"self",
".",
"_is_on",
"=",
"bool",
"(",
"self",
".",
"_data",
".",
"get_light_state",
"(",
"self",
".",
"_id",
")",
"==",
"\"on\"",
")"
] | [
152,
4
] | [
154,
72
] | python | en | ['en', 'en', 'en'] | True |
handle_error | (func) | Handle tradfri api call error. | Handle tradfri api call error. | def handle_error(func):
"""Handle tradfri api call error."""
@wraps(func)
async def wrapper(command):
"""Decorate api call."""
try:
await func(command)
except PytradfriError as err:
_LOGGER.error("Unable to execute command %s: %s", command, err)
return wrapper | [
"def",
"handle_error",
"(",
"func",
")",
":",
"@",
"wraps",
"(",
"func",
")",
"async",
"def",
"wrapper",
"(",
"command",
")",
":",
"\"\"\"Decorate api call.\"\"\"",
"try",
":",
"await",
"func",
"(",
"command",
")",
"except",
"PytradfriError",
"as",
"err",
":",
"_LOGGER",
".",
"error",
"(",
"\"Unable to execute command %s: %s\"",
",",
"command",
",",
"err",
")",
"return",
"wrapper"
] | [
14,
0
] | [
25,
18
] | python | cy | ['cy', 'pt', 'en'] | False |
TradfriBaseClass.__init__ | (self, device, api, gateway_id) | Initialize a device. | Initialize a device. | def __init__(self, device, api, gateway_id):
"""Initialize a device."""
self._api = handle_error(api)
self._device = None
self._device_control = None
self._device_data = None
self._gateway_id = gateway_id
self._name = None
self._unique_id = None
self._refresh(device) | [
"def",
"__init__",
"(",
"self",
",",
"device",
",",
"api",
",",
"gateway_id",
")",
":",
"self",
".",
"_api",
"=",
"handle_error",
"(",
"api",
")",
"self",
".",
"_device",
"=",
"None",
"self",
".",
"_device_control",
"=",
"None",
"self",
".",
"_device_data",
"=",
"None",
"self",
".",
"_gateway_id",
"=",
"gateway_id",
"self",
".",
"_name",
"=",
"None",
"self",
".",
"_unique_id",
"=",
"None",
"self",
".",
"_refresh",
"(",
"device",
")"
] | [
34,
4
] | [
44,
29
] | python | en | ['es', 'en', 'en'] | True |
TradfriBaseClass._async_start_observe | (self, exc=None) | Start observation of device. | Start observation of device. | def _async_start_observe(self, exc=None):
"""Start observation of device."""
if exc:
self.async_write_ha_state()
_LOGGER.warning("Observation failed for %s", self._name, exc_info=exc)
try:
cmd = self._device.observe(
callback=self._observe_update,
err_callback=self._async_start_observe,
duration=0,
)
self.hass.async_create_task(self._api(cmd))
except PytradfriError as err:
_LOGGER.warning("Observation failed, trying again", exc_info=err)
self._async_start_observe() | [
"def",
"_async_start_observe",
"(",
"self",
",",
"exc",
"=",
"None",
")",
":",
"if",
"exc",
":",
"self",
".",
"async_write_ha_state",
"(",
")",
"_LOGGER",
".",
"warning",
"(",
"\"Observation failed for %s\"",
",",
"self",
".",
"_name",
",",
"exc_info",
"=",
"exc",
")",
"try",
":",
"cmd",
"=",
"self",
".",
"_device",
".",
"observe",
"(",
"callback",
"=",
"self",
".",
"_observe_update",
",",
"err_callback",
"=",
"self",
".",
"_async_start_observe",
",",
"duration",
"=",
"0",
",",
")",
"self",
".",
"hass",
".",
"async_create_task",
"(",
"self",
".",
"_api",
"(",
"cmd",
")",
")",
"except",
"PytradfriError",
"as",
"err",
":",
"_LOGGER",
".",
"warning",
"(",
"\"Observation failed, trying again\"",
",",
"exc_info",
"=",
"err",
")",
"self",
".",
"_async_start_observe",
"(",
")"
] | [
47,
4
] | [
62,
39
] | python | en | ['en', 'da', 'en'] | True |
TradfriBaseClass.async_added_to_hass | (self) | Start thread when added to hass. | Start thread when added to hass. | async def async_added_to_hass(self):
"""Start thread when added to hass."""
self._async_start_observe() | [
"async",
"def",
"async_added_to_hass",
"(",
"self",
")",
":",
"self",
".",
"_async_start_observe",
"(",
")"
] | [
64,
4
] | [
66,
35
] | python | en | ['en', 'en', 'en'] | True |
TradfriBaseClass.name | (self) | Return the display name of this device. | Return the display name of this device. | def name(self):
"""Return the display name of this device."""
return self._name | [
"def",
"name",
"(",
"self",
")",
":",
"return",
"self",
".",
"_name"
] | [
69,
4
] | [
71,
25
] | python | en | ['en', 'en', 'en'] | True |
TradfriBaseClass.should_poll | (self) | No polling needed for tradfri device. | No polling needed for tradfri device. | def should_poll(self):
"""No polling needed for tradfri device."""
return False | [
"def",
"should_poll",
"(",
"self",
")",
":",
"return",
"False"
] | [
74,
4
] | [
76,
20
] | python | en | ['en', 'en', 'en'] | True |
TradfriBaseClass.unique_id | (self) | Return unique ID for device. | Return unique ID for device. | def unique_id(self):
"""Return unique ID for device."""
return self._unique_id | [
"def",
"unique_id",
"(",
"self",
")",
":",
"return",
"self",
".",
"_unique_id"
] | [
79,
4
] | [
81,
30
] | python | en | ['fr', 'en', 'en'] | True |
TradfriBaseClass._observe_update | (self, device) | Receive new state data for this device. | Receive new state data for this device. | def _observe_update(self, device):
"""Receive new state data for this device."""
self._refresh(device)
self.async_write_ha_state() | [
"def",
"_observe_update",
"(",
"self",
",",
"device",
")",
":",
"self",
".",
"_refresh",
"(",
"device",
")",
"self",
".",
"async_write_ha_state",
"(",
")"
] | [
84,
4
] | [
87,
35
] | python | en | ['en', 'en', 'en'] | True |
TradfriBaseClass._refresh | (self, device) | Refresh the device data. | Refresh the device data. | def _refresh(self, device):
"""Refresh the device data."""
self._device = device
self._name = device.name | [
"def",
"_refresh",
"(",
"self",
",",
"device",
")",
":",
"self",
".",
"_device",
"=",
"device",
"self",
".",
"_name",
"=",
"device",
".",
"name"
] | [
89,
4
] | [
92,
32
] | python | en | ['en', 'en', 'en'] | True |
TradfriBaseDevice.__init__ | (self, device, api, gateway_id) | Initialize a device. | Initialize a device. | def __init__(self, device, api, gateway_id):
"""Initialize a device."""
super().__init__(device, api, gateway_id)
self._available = True | [
"def",
"__init__",
"(",
"self",
",",
"device",
",",
"api",
",",
"gateway_id",
")",
":",
"super",
"(",
")",
".",
"__init__",
"(",
"device",
",",
"api",
",",
"gateway_id",
")",
"self",
".",
"_available",
"=",
"True"
] | [
101,
4
] | [
104,
30
] | python | en | ['es', 'en', 'en'] | True |
TradfriBaseDevice.available | (self) | Return True if entity is available. | Return True if entity is available. | def available(self):
"""Return True if entity is available."""
return self._available | [
"def",
"available",
"(",
"self",
")",
":",
"return",
"self",
".",
"_available"
] | [
107,
4
] | [
109,
30
] | python | en | ['en', 'en', 'en'] | True |
TradfriBaseDevice.device_info | (self) | Return the device info. | Return the device info. | def device_info(self):
"""Return the device info."""
info = self._device.device_info
return {
"identifiers": {(DOMAIN, self._device.id)},
"manufacturer": info.manufacturer,
"model": info.model_number,
"name": self._name,
"sw_version": info.firmware_version,
"via_device": (DOMAIN, self._gateway_id),
} | [
"def",
"device_info",
"(",
"self",
")",
":",
"info",
"=",
"self",
".",
"_device",
".",
"device_info",
"return",
"{",
"\"identifiers\"",
":",
"{",
"(",
"DOMAIN",
",",
"self",
".",
"_device",
".",
"id",
")",
"}",
",",
"\"manufacturer\"",
":",
"info",
".",
"manufacturer",
",",
"\"model\"",
":",
"info",
".",
"model_number",
",",
"\"name\"",
":",
"self",
".",
"_name",
",",
"\"sw_version\"",
":",
"info",
".",
"firmware_version",
",",
"\"via_device\"",
":",
"(",
"DOMAIN",
",",
"self",
".",
"_gateway_id",
")",
",",
"}"
] | [
112,
4
] | [
123,
9
] | python | en | ['en', 'en', 'en'] | True |
TradfriBaseDevice._refresh | (self, device) | Refresh the device data. | Refresh the device data. | def _refresh(self, device):
"""Refresh the device data."""
super()._refresh(device)
self._available = device.reachable | [
"def",
"_refresh",
"(",
"self",
",",
"device",
")",
":",
"super",
"(",
")",
".",
"_refresh",
"(",
"device",
")",
"self",
".",
"_available",
"=",
"device",
".",
"reachable"
] | [
125,
4
] | [
128,
42
] | python | en | ['en', 'en', 'en'] | True |
hk_driver | (loop) | Return a custom AccessoryDriver instance for HomeKit accessory init. | Return a custom AccessoryDriver instance for HomeKit accessory init. | def hk_driver(loop):
"""Return a custom AccessoryDriver instance for HomeKit accessory init."""
with patch("pyhap.accessory_driver.Zeroconf"), patch(
"pyhap.accessory_driver.AccessoryEncoder"
), patch("pyhap.accessory_driver.HAPServer"), patch(
"pyhap.accessory_driver.AccessoryDriver.publish"
), patch(
"pyhap.accessory_driver.AccessoryDriver.persist"
):
yield AccessoryDriver(pincode=b"123-45-678", address="127.0.0.1", loop=loop) | [
"def",
"hk_driver",
"(",
"loop",
")",
":",
"with",
"patch",
"(",
"\"pyhap.accessory_driver.Zeroconf\"",
")",
",",
"patch",
"(",
"\"pyhap.accessory_driver.AccessoryEncoder\"",
")",
",",
"patch",
"(",
"\"pyhap.accessory_driver.HAPServer\"",
")",
",",
"patch",
"(",
"\"pyhap.accessory_driver.AccessoryDriver.publish\"",
")",
",",
"patch",
"(",
"\"pyhap.accessory_driver.AccessoryDriver.persist\"",
")",
":",
"yield",
"AccessoryDriver",
"(",
"pincode",
"=",
"b\"123-45-678\"",
",",
"address",
"=",
"\"127.0.0.1\"",
",",
"loop",
"=",
"loop",
")"
] | [
11,
0
] | [
20,
84
] | python | en | ['en', 'en', 'en'] | True |
events | (hass) | Yield caught homekit_changed events. | Yield caught homekit_changed events. | def events(hass):
"""Yield caught homekit_changed events."""
events = []
hass.bus.async_listen(
EVENT_HOMEKIT_CHANGED, ha_callback(lambda e: events.append(e))
)
yield events | [
"def",
"events",
"(",
"hass",
")",
":",
"events",
"=",
"[",
"]",
"hass",
".",
"bus",
".",
"async_listen",
"(",
"EVENT_HOMEKIT_CHANGED",
",",
"ha_callback",
"(",
"lambda",
"e",
":",
"events",
".",
"append",
"(",
"e",
")",
")",
")",
"yield",
"events"
] | [
24,
0
] | [
30,
16
] | python | en | ['en', 'en', 'en'] | True |
async_setup_platform | (
hass, config, async_add_entities, discovery_info=None
) | Set up Sure PetCare Flaps sensors based on a config entry. | Set up Sure PetCare Flaps sensors based on a config entry. | async def async_setup_platform(
hass, config, async_add_entities, discovery_info=None
) -> None:
"""Set up Sure PetCare Flaps sensors based on a config entry."""
if discovery_info is None:
return
entities = []
spc = hass.data[DATA_SURE_PETCARE][SPC]
for thing in spc.ids:
sure_id = thing[CONF_ID]
sure_type = thing[CONF_TYPE]
# connectivity
if sure_type in [
SureProductID.CAT_FLAP,
SureProductID.PET_FLAP,
SureProductID.FEEDER,
]:
entities.append(DeviceConnectivity(sure_id, sure_type, spc))
if sure_type == SureProductID.PET:
entity = Pet(sure_id, spc)
elif sure_type == SureProductID.HUB:
entity = Hub(sure_id, spc)
else:
continue
entities.append(entity)
async_add_entities(entities, True) | [
"async",
"def",
"async_setup_platform",
"(",
"hass",
",",
"config",
",",
"async_add_entities",
",",
"discovery_info",
"=",
"None",
")",
"->",
"None",
":",
"if",
"discovery_info",
"is",
"None",
":",
"return",
"entities",
"=",
"[",
"]",
"spc",
"=",
"hass",
".",
"data",
"[",
"DATA_SURE_PETCARE",
"]",
"[",
"SPC",
"]",
"for",
"thing",
"in",
"spc",
".",
"ids",
":",
"sure_id",
"=",
"thing",
"[",
"CONF_ID",
"]",
"sure_type",
"=",
"thing",
"[",
"CONF_TYPE",
"]",
"# connectivity",
"if",
"sure_type",
"in",
"[",
"SureProductID",
".",
"CAT_FLAP",
",",
"SureProductID",
".",
"PET_FLAP",
",",
"SureProductID",
".",
"FEEDER",
",",
"]",
":",
"entities",
".",
"append",
"(",
"DeviceConnectivity",
"(",
"sure_id",
",",
"sure_type",
",",
"spc",
")",
")",
"if",
"sure_type",
"==",
"SureProductID",
".",
"PET",
":",
"entity",
"=",
"Pet",
"(",
"sure_id",
",",
"spc",
")",
"elif",
"sure_type",
"==",
"SureProductID",
".",
"HUB",
":",
"entity",
"=",
"Hub",
"(",
"sure_id",
",",
"spc",
")",
"else",
":",
"continue",
"entities",
".",
"append",
"(",
"entity",
")",
"async_add_entities",
"(",
"entities",
",",
"True",
")"
] | [
22,
0
] | [
54,
38
] | python | en | ['en', 'en', 'en'] | True |
SurePetcareBinarySensor.__init__ | (
self,
_id: int,
spc: SurePetcareAPI,
device_class: str,
sure_type: SureProductID,
) | Initialize a Sure Petcare binary sensor. | Initialize a Sure Petcare binary sensor. | def __init__(
self,
_id: int,
spc: SurePetcareAPI,
device_class: str,
sure_type: SureProductID,
):
"""Initialize a Sure Petcare binary sensor."""
self._id = _id
self._sure_type = sure_type
self._device_class = device_class
self._spc: SurePetcareAPI = spc
self._spc_data: Dict[str, Any] = self._spc.states[self._sure_type].get(self._id)
self._state: Dict[str, Any] = {}
# cover special case where a device has no name set
if "name" in self._spc_data:
name = self._spc_data["name"]
else:
name = f"Unnamed {self._sure_type.name.capitalize()}"
self._name = f"{self._sure_type.name.capitalize()} {name.capitalize()}"
self._async_unsub_dispatcher_connect = None | [
"def",
"__init__",
"(",
"self",
",",
"_id",
":",
"int",
",",
"spc",
":",
"SurePetcareAPI",
",",
"device_class",
":",
"str",
",",
"sure_type",
":",
"SureProductID",
",",
")",
":",
"self",
".",
"_id",
"=",
"_id",
"self",
".",
"_sure_type",
"=",
"sure_type",
"self",
".",
"_device_class",
"=",
"device_class",
"self",
".",
"_spc",
":",
"SurePetcareAPI",
"=",
"spc",
"self",
".",
"_spc_data",
":",
"Dict",
"[",
"str",
",",
"Any",
"]",
"=",
"self",
".",
"_spc",
".",
"states",
"[",
"self",
".",
"_sure_type",
"]",
".",
"get",
"(",
"self",
".",
"_id",
")",
"self",
".",
"_state",
":",
"Dict",
"[",
"str",
",",
"Any",
"]",
"=",
"{",
"}",
"# cover special case where a device has no name set",
"if",
"\"name\"",
"in",
"self",
".",
"_spc_data",
":",
"name",
"=",
"self",
".",
"_spc_data",
"[",
"\"name\"",
"]",
"else",
":",
"name",
"=",
"f\"Unnamed {self._sure_type.name.capitalize()}\"",
"self",
".",
"_name",
"=",
"f\"{self._sure_type.name.capitalize()} {name.capitalize()}\"",
"self",
".",
"_async_unsub_dispatcher_connect",
"=",
"None"
] | [
60,
4
] | [
84,
51
] | python | en | ['en', 'pt', 'en'] | True |
SurePetcareBinarySensor.is_on | (self) | Return true if entity is on/unlocked. | Return true if entity is on/unlocked. | def is_on(self) -> Optional[bool]:
"""Return true if entity is on/unlocked."""
return bool(self._state) | [
"def",
"is_on",
"(",
"self",
")",
"->",
"Optional",
"[",
"bool",
"]",
":",
"return",
"bool",
"(",
"self",
".",
"_state",
")"
] | [
87,
4
] | [
89,
32
] | python | en | ['en', 'fy', 'en'] | True |
SurePetcareBinarySensor.should_poll | (self) | Return true. | Return true. | def should_poll(self) -> bool:
"""Return true."""
return False | [
"def",
"should_poll",
"(",
"self",
")",
"->",
"bool",
":",
"return",
"False"
] | [
92,
4
] | [
94,
20
] | python | en | ['en', 'mt', 'en'] | False |
SurePetcareBinarySensor.name | (self) | Return the name of the device if any. | Return the name of the device if any. | def name(self) -> str:
"""Return the name of the device if any."""
return self._name | [
"def",
"name",
"(",
"self",
")",
"->",
"str",
":",
"return",
"self",
".",
"_name"
] | [
97,
4
] | [
99,
25
] | python | en | ['en', 'en', 'en'] | True |
SurePetcareBinarySensor.device_class | (self) | Return the device class. | Return the device class. | def device_class(self) -> str:
"""Return the device class."""
return None if not self._device_class else self._device_class | [
"def",
"device_class",
"(",
"self",
")",
"->",
"str",
":",
"return",
"None",
"if",
"not",
"self",
".",
"_device_class",
"else",
"self",
".",
"_device_class"
] | [
102,
4
] | [
104,
69
] | python | en | ['en', 'en', 'en'] | True |
SurePetcareBinarySensor.unique_id | (self) | Return an unique ID. | Return an unique ID. | def unique_id(self) -> str:
"""Return an unique ID."""
return f"{self._spc_data['household_id']}-{self._id}" | [
"def",
"unique_id",
"(",
"self",
")",
"->",
"str",
":",
"return",
"f\"{self._spc_data['household_id']}-{self._id}\""
] | [
107,
4
] | [
109,
61
] | python | fr | ['fr', 'fr', 'en'] | True |
SurePetcareBinarySensor.async_update | (self) | Get the latest data and update the state. | Get the latest data and update the state. | async def async_update(self) -> None:
"""Get the latest data and update the state."""
self._spc_data = self._spc.states[self._sure_type].get(self._id)
self._state = self._spc_data.get("status")
_LOGGER.debug("%s -> self._state: %s", self._name, self._state) | [
"async",
"def",
"async_update",
"(",
"self",
")",
"->",
"None",
":",
"self",
".",
"_spc_data",
"=",
"self",
".",
"_spc",
".",
"states",
"[",
"self",
".",
"_sure_type",
"]",
".",
"get",
"(",
"self",
".",
"_id",
")",
"self",
".",
"_state",
"=",
"self",
".",
"_spc_data",
".",
"get",
"(",
"\"status\"",
")",
"_LOGGER",
".",
"debug",
"(",
"\"%s -> self._state: %s\"",
",",
"self",
".",
"_name",
",",
"self",
".",
"_state",
")"
] | [
111,
4
] | [
115,
71
] | python | en | ['en', 'en', 'en'] | True |
SurePetcareBinarySensor.async_added_to_hass | (self) | Register callbacks. | Register callbacks. | async def async_added_to_hass(self) -> None:
"""Register callbacks."""
@callback
def update() -> None:
"""Update the state."""
self.async_schedule_update_ha_state(True)
self._async_unsub_dispatcher_connect = async_dispatcher_connect(
self.hass, TOPIC_UPDATE, update
) | [
"async",
"def",
"async_added_to_hass",
"(",
"self",
")",
"->",
"None",
":",
"@",
"callback",
"def",
"update",
"(",
")",
"->",
"None",
":",
"\"\"\"Update the state.\"\"\"",
"self",
".",
"async_schedule_update_ha_state",
"(",
"True",
")",
"self",
".",
"_async_unsub_dispatcher_connect",
"=",
"async_dispatcher_connect",
"(",
"self",
".",
"hass",
",",
"TOPIC_UPDATE",
",",
"update",
")"
] | [
117,
4
] | [
127,
9
] | python | en | ['en', 'no', 'en'] | False |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.