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
expand
(hass: HomeAssistantType, *args: Any)
Expand out any groups into entity states.
Expand out any groups into entity states.
def expand(hass: HomeAssistantType, *args: Any) -> Iterable[State]: """Expand out any groups into entity states.""" search = list(args) found = {} while search: entity = search.pop() if isinstance(entity, str): entity_id = entity entity = _get_state(hass, entity) if entity is None: continue elif isinstance(entity, State): entity_id = entity.entity_id elif isinstance(entity, collections.abc.Iterable): search += entity continue else: # ignore other types continue if entity_id.startswith(_GROUP_DOMAIN_PREFIX): # Collect state will be called in here since it's wrapped group_entities = entity.attributes.get(ATTR_ENTITY_ID) if group_entities: search += group_entities else: _collect_state(hass, entity_id) found[entity_id] = entity return sorted(found.values(), key=lambda a: a.entity_id)
[ "def", "expand", "(", "hass", ":", "HomeAssistantType", ",", "*", "args", ":", "Any", ")", "->", "Iterable", "[", "State", "]", ":", "search", "=", "list", "(", "args", ")", "found", "=", "{", "}", "while", "search", ":", "entity", "=", "search", ".", "pop", "(", ")", "if", "isinstance", "(", "entity", ",", "str", ")", ":", "entity_id", "=", "entity", "entity", "=", "_get_state", "(", "hass", ",", "entity", ")", "if", "entity", "is", "None", ":", "continue", "elif", "isinstance", "(", "entity", ",", "State", ")", ":", "entity_id", "=", "entity", ".", "entity_id", "elif", "isinstance", "(", "entity", ",", "collections", ".", "abc", ".", "Iterable", ")", ":", "search", "+=", "entity", "continue", "else", ":", "# ignore other types", "continue", "if", "entity_id", ".", "startswith", "(", "_GROUP_DOMAIN_PREFIX", ")", ":", "# Collect state will be called in here since it's wrapped", "group_entities", "=", "entity", ".", "attributes", ".", "get", "(", "ATTR_ENTITY_ID", ")", "if", "group_entities", ":", "search", "+=", "group_entities", "else", ":", "_collect_state", "(", "hass", ",", "entity_id", ")", "found", "[", "entity_id", "]", "=", "entity", "return", "sorted", "(", "found", ".", "values", "(", ")", ",", "key", "=", "lambda", "a", ":", "a", ".", "entity_id", ")" ]
[ 817, 0 ]
[ 846, 60 ]
python
en
['en', 'en', 'en']
True
closest
(hass, *args)
Find closest entity. Closest to home: closest(states) closest(states.device_tracker) closest('group.children') closest(states.group.children) Closest to a point: closest(23.456, 23.456, 'group.children') closest('zone.school', 'group.children') closest(states.zone.school, 'group.children') As a filter: states | closest states.device_tracker | closest ['group.children', states.device_tracker] | closest 'group.children' | closest(23.456, 23.456) states.device_tracker | closest('zone.school') 'group.children' | closest(states.zone.school)
Find closest entity.
def closest(hass, *args): """Find closest entity. Closest to home: closest(states) closest(states.device_tracker) closest('group.children') closest(states.group.children) Closest to a point: closest(23.456, 23.456, 'group.children') closest('zone.school', 'group.children') closest(states.zone.school, 'group.children') As a filter: states | closest states.device_tracker | closest ['group.children', states.device_tracker] | closest 'group.children' | closest(23.456, 23.456) states.device_tracker | closest('zone.school') 'group.children' | closest(states.zone.school) """ if len(args) == 1: latitude = hass.config.latitude longitude = hass.config.longitude entities = args[0] elif len(args) == 2: point_state = _resolve_state(hass, args[0]) if point_state is None: _LOGGER.warning("Closest:Unable to find state %s", args[0]) return None if not loc_helper.has_location(point_state): _LOGGER.warning( "Closest:State does not contain valid location: %s", point_state ) return None latitude = point_state.attributes.get(ATTR_LATITUDE) longitude = point_state.attributes.get(ATTR_LONGITUDE) entities = args[1] else: latitude = convert(args[0], float) longitude = convert(args[1], float) if latitude is None or longitude is None: _LOGGER.warning( "Closest:Received invalid coordinates: %s, %s", args[0], args[1] ) return None entities = args[2] states = expand(hass, entities) # state will already be wrapped here return loc_helper.closest(latitude, longitude, states)
[ "def", "closest", "(", "hass", ",", "*", "args", ")", ":", "if", "len", "(", "args", ")", "==", "1", ":", "latitude", "=", "hass", ".", "config", ".", "latitude", "longitude", "=", "hass", ".", "config", ".", "longitude", "entities", "=", "args", "[", "0", "]", "elif", "len", "(", "args", ")", "==", "2", ":", "point_state", "=", "_resolve_state", "(", "hass", ",", "args", "[", "0", "]", ")", "if", "point_state", "is", "None", ":", "_LOGGER", ".", "warning", "(", "\"Closest:Unable to find state %s\"", ",", "args", "[", "0", "]", ")", "return", "None", "if", "not", "loc_helper", ".", "has_location", "(", "point_state", ")", ":", "_LOGGER", ".", "warning", "(", "\"Closest:State does not contain valid location: %s\"", ",", "point_state", ")", "return", "None", "latitude", "=", "point_state", ".", "attributes", ".", "get", "(", "ATTR_LATITUDE", ")", "longitude", "=", "point_state", ".", "attributes", ".", "get", "(", "ATTR_LONGITUDE", ")", "entities", "=", "args", "[", "1", "]", "else", ":", "latitude", "=", "convert", "(", "args", "[", "0", "]", ",", "float", ")", "longitude", "=", "convert", "(", "args", "[", "1", "]", ",", "float", ")", "if", "latitude", "is", "None", "or", "longitude", "is", "None", ":", "_LOGGER", ".", "warning", "(", "\"Closest:Received invalid coordinates: %s, %s\"", ",", "args", "[", "0", "]", ",", "args", "[", "1", "]", ")", "return", "None", "entities", "=", "args", "[", "2", "]", "states", "=", "expand", "(", "hass", ",", "entities", ")", "# state will already be wrapped here", "return", "loc_helper", ".", "closest", "(", "latitude", ",", "longitude", ",", "states", ")" ]
[ 849, 0 ]
[ 909, 58 ]
python
en
['en', 'en', 'en']
True
closest_filter
(hass, *args)
Call closest as a filter. Need to reorder arguments.
Call closest as a filter. Need to reorder arguments.
def closest_filter(hass, *args): """Call closest as a filter. Need to reorder arguments.""" new_args = list(args[1:]) new_args.append(args[0]) return closest(hass, *new_args)
[ "def", "closest_filter", "(", "hass", ",", "*", "args", ")", ":", "new_args", "=", "list", "(", "args", "[", "1", ":", "]", ")", "new_args", ".", "append", "(", "args", "[", "0", "]", ")", "return", "closest", "(", "hass", ",", "*", "new_args", ")" ]
[ 912, 0 ]
[ 916, 35 ]
python
en
['en', 'en', 'en']
True
distance
(hass, *args)
Calculate distance. Will calculate distance from home to a point or between points. Points can be passed in using state objects or lat/lng coordinates.
Calculate distance.
def distance(hass, *args): """Calculate distance. Will calculate distance from home to a point or between points. Points can be passed in using state objects or lat/lng coordinates. """ locations = [] to_process = list(args) while to_process: value = to_process.pop(0) if isinstance(value, str) and not valid_entity_id(value): point_state = None else: point_state = _resolve_state(hass, value) if point_state is None: # We expect this and next value to be lat&lng if not to_process: _LOGGER.warning( "Distance:Expected latitude and longitude, got %s", value ) return None value_2 = to_process.pop(0) latitude = convert(value, float) longitude = convert(value_2, float) if latitude is None or longitude is None: _LOGGER.warning( "Distance:Unable to process latitude and longitude: %s, %s", value, value_2, ) return None else: if not loc_helper.has_location(point_state): _LOGGER.warning( "distance:State does not contain valid location: %s", point_state ) return None latitude = point_state.attributes.get(ATTR_LATITUDE) longitude = point_state.attributes.get(ATTR_LONGITUDE) locations.append((latitude, longitude)) if len(locations) == 1: return hass.config.distance(*locations[0]) return hass.config.units.length( loc_util.distance(*locations[0] + locations[1]), LENGTH_METERS )
[ "def", "distance", "(", "hass", ",", "*", "args", ")", ":", "locations", "=", "[", "]", "to_process", "=", "list", "(", "args", ")", "while", "to_process", ":", "value", "=", "to_process", ".", "pop", "(", "0", ")", "if", "isinstance", "(", "value", ",", "str", ")", "and", "not", "valid_entity_id", "(", "value", ")", ":", "point_state", "=", "None", "else", ":", "point_state", "=", "_resolve_state", "(", "hass", ",", "value", ")", "if", "point_state", "is", "None", ":", "# We expect this and next value to be lat&lng", "if", "not", "to_process", ":", "_LOGGER", ".", "warning", "(", "\"Distance:Expected latitude and longitude, got %s\"", ",", "value", ")", "return", "None", "value_2", "=", "to_process", ".", "pop", "(", "0", ")", "latitude", "=", "convert", "(", "value", ",", "float", ")", "longitude", "=", "convert", "(", "value_2", ",", "float", ")", "if", "latitude", "is", "None", "or", "longitude", "is", "None", ":", "_LOGGER", ".", "warning", "(", "\"Distance:Unable to process latitude and longitude: %s, %s\"", ",", "value", ",", "value_2", ",", ")", "return", "None", "else", ":", "if", "not", "loc_helper", ".", "has_location", "(", "point_state", ")", ":", "_LOGGER", ".", "warning", "(", "\"distance:State does not contain valid location: %s\"", ",", "point_state", ")", "return", "None", "latitude", "=", "point_state", ".", "attributes", ".", "get", "(", "ATTR_LATITUDE", ")", "longitude", "=", "point_state", ".", "attributes", ".", "get", "(", "ATTR_LONGITUDE", ")", "locations", ".", "append", "(", "(", "latitude", ",", "longitude", ")", ")", "if", "len", "(", "locations", ")", "==", "1", ":", "return", "hass", ".", "config", ".", "distance", "(", "*", "locations", "[", "0", "]", ")", "return", "hass", ".", "config", ".", "units", ".", "length", "(", "loc_util", ".", "distance", "(", "*", "locations", "[", "0", "]", "+", "locations", "[", "1", "]", ")", ",", "LENGTH_METERS", ")" ]
[ 919, 0 ]
[ 973, 5 ]
python
en
['it', 'en', 'en']
False
is_state
(hass: HomeAssistantType, entity_id: str, state: State)
Test if a state is a specific value.
Test if a state is a specific value.
def is_state(hass: HomeAssistantType, entity_id: str, state: State) -> bool: """Test if a state is a specific value.""" state_obj = _get_state(hass, entity_id) return state_obj is not None and state_obj.state == state
[ "def", "is_state", "(", "hass", ":", "HomeAssistantType", ",", "entity_id", ":", "str", ",", "state", ":", "State", ")", "->", "bool", ":", "state_obj", "=", "_get_state", "(", "hass", ",", "entity_id", ")", "return", "state_obj", "is", "not", "None", "and", "state_obj", ".", "state", "==", "state" ]
[ 976, 0 ]
[ 979, 61 ]
python
en
['en', 'en', 'en']
True
is_state_attr
(hass, entity_id, name, value)
Test if a state's attribute is a specific value.
Test if a state's attribute is a specific value.
def is_state_attr(hass, entity_id, name, value): """Test if a state's attribute is a specific value.""" attr = state_attr(hass, entity_id, name) return attr is not None and attr == value
[ "def", "is_state_attr", "(", "hass", ",", "entity_id", ",", "name", ",", "value", ")", ":", "attr", "=", "state_attr", "(", "hass", ",", "entity_id", ",", "name", ")", "return", "attr", "is", "not", "None", "and", "attr", "==", "value" ]
[ 982, 0 ]
[ 985, 45 ]
python
en
['en', 'en', 'en']
True
state_attr
(hass, entity_id, name)
Get a specific attribute from a state.
Get a specific attribute from a state.
def state_attr(hass, entity_id, name): """Get a specific attribute from a state.""" state_obj = _get_state(hass, entity_id) if state_obj is not None: return state_obj.attributes.get(name) return None
[ "def", "state_attr", "(", "hass", ",", "entity_id", ",", "name", ")", ":", "state_obj", "=", "_get_state", "(", "hass", ",", "entity_id", ")", "if", "state_obj", "is", "not", "None", ":", "return", "state_obj", ".", "attributes", ".", "get", "(", "name", ")", "return", "None" ]
[ 988, 0 ]
[ 993, 15 ]
python
en
['en', 'en', 'en']
True
now
(hass)
Record fetching now.
Record fetching now.
def now(hass): """Record fetching now.""" render_info = hass.data.get(_RENDER_INFO) if render_info is not None: render_info.has_time = True return dt_util.now()
[ "def", "now", "(", "hass", ")", ":", "render_info", "=", "hass", ".", "data", ".", "get", "(", "_RENDER_INFO", ")", "if", "render_info", "is", "not", "None", ":", "render_info", ".", "has_time", "=", "True", "return", "dt_util", ".", "now", "(", ")" ]
[ 996, 0 ]
[ 1002, 24 ]
python
en
['en', 'en', 'en']
True
utcnow
(hass)
Record fetching utcnow.
Record fetching utcnow.
def utcnow(hass): """Record fetching utcnow.""" render_info = hass.data.get(_RENDER_INFO) if render_info is not None: render_info.has_time = True return dt_util.utcnow()
[ "def", "utcnow", "(", "hass", ")", ":", "render_info", "=", "hass", ".", "data", ".", "get", "(", "_RENDER_INFO", ")", "if", "render_info", "is", "not", "None", ":", "render_info", ".", "has_time", "=", "True", "return", "dt_util", ".", "utcnow", "(", ")" ]
[ 1005, 0 ]
[ 1011, 27 ]
python
en
['en', 'hmn', 'en']
True
forgiving_round
(value, precision=0, method="common")
Round accepted strings.
Round accepted strings.
def forgiving_round(value, precision=0, method="common"): """Round accepted strings.""" try: # support rounding methods like jinja multiplier = float(10 ** precision) if method == "ceil": value = math.ceil(float(value) * multiplier) / multiplier elif method == "floor": value = math.floor(float(value) * multiplier) / multiplier elif method == "half": value = round(float(value) * 2) / 2 else: # if method is common or something else, use common rounding value = round(float(value), precision) return int(value) if precision == 0 else value except (ValueError, TypeError): # If value can't be converted to float return value
[ "def", "forgiving_round", "(", "value", ",", "precision", "=", "0", ",", "method", "=", "\"common\"", ")", ":", "try", ":", "# support rounding methods like jinja", "multiplier", "=", "float", "(", "10", "**", "precision", ")", "if", "method", "==", "\"ceil\"", ":", "value", "=", "math", ".", "ceil", "(", "float", "(", "value", ")", "*", "multiplier", ")", "/", "multiplier", "elif", "method", "==", "\"floor\"", ":", "value", "=", "math", ".", "floor", "(", "float", "(", "value", ")", "*", "multiplier", ")", "/", "multiplier", "elif", "method", "==", "\"half\"", ":", "value", "=", "round", "(", "float", "(", "value", ")", "*", "2", ")", "/", "2", "else", ":", "# if method is common or something else, use common rounding", "value", "=", "round", "(", "float", "(", "value", ")", ",", "precision", ")", "return", "int", "(", "value", ")", "if", "precision", "==", "0", "else", "value", "except", "(", "ValueError", ",", "TypeError", ")", ":", "# If value can't be converted to float", "return", "value" ]
[ 1014, 0 ]
[ 1031, 20 ]
python
en
['en', 'en', 'en']
True
multiply
(value, amount)
Filter to convert value to float and multiply it.
Filter to convert value to float and multiply it.
def multiply(value, amount): """Filter to convert value to float and multiply it.""" try: return float(value) * amount except (ValueError, TypeError): # If value can't be converted to float return value
[ "def", "multiply", "(", "value", ",", "amount", ")", ":", "try", ":", "return", "float", "(", "value", ")", "*", "amount", "except", "(", "ValueError", ",", "TypeError", ")", ":", "# If value can't be converted to float", "return", "value" ]
[ 1034, 0 ]
[ 1040, 20 ]
python
en
['en', 'en', 'en']
True
logarithm
(value, base=math.e)
Filter to get logarithm of the value with a specific base.
Filter to get logarithm of the value with a specific base.
def logarithm(value, base=math.e): """Filter to get logarithm of the value with a specific base.""" try: return math.log(float(value), float(base)) except (ValueError, TypeError): return value
[ "def", "logarithm", "(", "value", ",", "base", "=", "math", ".", "e", ")", ":", "try", ":", "return", "math", ".", "log", "(", "float", "(", "value", ")", ",", "float", "(", "base", ")", ")", "except", "(", "ValueError", ",", "TypeError", ")", ":", "return", "value" ]
[ 1043, 0 ]
[ 1048, 20 ]
python
en
['en', 'en', 'en']
True
sine
(value)
Filter to get sine of the value.
Filter to get sine of the value.
def sine(value): """Filter to get sine of the value.""" try: return math.sin(float(value)) except (ValueError, TypeError): return value
[ "def", "sine", "(", "value", ")", ":", "try", ":", "return", "math", ".", "sin", "(", "float", "(", "value", ")", ")", "except", "(", "ValueError", ",", "TypeError", ")", ":", "return", "value" ]
[ 1051, 0 ]
[ 1056, 20 ]
python
en
['en', 'en', 'en']
True
cosine
(value)
Filter to get cosine of the value.
Filter to get cosine of the value.
def cosine(value): """Filter to get cosine of the value.""" try: return math.cos(float(value)) except (ValueError, TypeError): return value
[ "def", "cosine", "(", "value", ")", ":", "try", ":", "return", "math", ".", "cos", "(", "float", "(", "value", ")", ")", "except", "(", "ValueError", ",", "TypeError", ")", ":", "return", "value" ]
[ 1059, 0 ]
[ 1064, 20 ]
python
en
['en', 'en', 'en']
True
tangent
(value)
Filter to get tangent of the value.
Filter to get tangent of the value.
def tangent(value): """Filter to get tangent of the value.""" try: return math.tan(float(value)) except (ValueError, TypeError): return value
[ "def", "tangent", "(", "value", ")", ":", "try", ":", "return", "math", ".", "tan", "(", "float", "(", "value", ")", ")", "except", "(", "ValueError", ",", "TypeError", ")", ":", "return", "value" ]
[ 1067, 0 ]
[ 1072, 20 ]
python
en
['en', 'en', 'en']
True
arc_sine
(value)
Filter to get arc sine of the value.
Filter to get arc sine of the value.
def arc_sine(value): """Filter to get arc sine of the value.""" try: return math.asin(float(value)) except (ValueError, TypeError): return value
[ "def", "arc_sine", "(", "value", ")", ":", "try", ":", "return", "math", ".", "asin", "(", "float", "(", "value", ")", ")", "except", "(", "ValueError", ",", "TypeError", ")", ":", "return", "value" ]
[ 1075, 0 ]
[ 1080, 20 ]
python
en
['en', 'en', 'en']
True
arc_cosine
(value)
Filter to get arc cosine of the value.
Filter to get arc cosine of the value.
def arc_cosine(value): """Filter to get arc cosine of the value.""" try: return math.acos(float(value)) except (ValueError, TypeError): return value
[ "def", "arc_cosine", "(", "value", ")", ":", "try", ":", "return", "math", ".", "acos", "(", "float", "(", "value", ")", ")", "except", "(", "ValueError", ",", "TypeError", ")", ":", "return", "value" ]
[ 1083, 0 ]
[ 1088, 20 ]
python
en
['en', 'en', 'en']
True
arc_tangent
(value)
Filter to get arc tangent of the value.
Filter to get arc tangent of the value.
def arc_tangent(value): """Filter to get arc tangent of the value.""" try: return math.atan(float(value)) except (ValueError, TypeError): return value
[ "def", "arc_tangent", "(", "value", ")", ":", "try", ":", "return", "math", ".", "atan", "(", "float", "(", "value", ")", ")", "except", "(", "ValueError", ",", "TypeError", ")", ":", "return", "value" ]
[ 1091, 0 ]
[ 1096, 20 ]
python
en
['en', 'en', 'en']
True
arc_tangent2
(*args)
Filter to calculate four quadrant arc tangent of y / x.
Filter to calculate four quadrant arc tangent of y / x.
def arc_tangent2(*args): """Filter to calculate four quadrant arc tangent of y / x.""" try: if len(args) == 1 and isinstance(args[0], (list, tuple)): args = args[0] return math.atan2(float(args[0]), float(args[1])) except (ValueError, TypeError): return args
[ "def", "arc_tangent2", "(", "*", "args", ")", ":", "try", ":", "if", "len", "(", "args", ")", "==", "1", "and", "isinstance", "(", "args", "[", "0", "]", ",", "(", "list", ",", "tuple", ")", ")", ":", "args", "=", "args", "[", "0", "]", "return", "math", ".", "atan2", "(", "float", "(", "args", "[", "0", "]", ")", ",", "float", "(", "args", "[", "1", "]", ")", ")", "except", "(", "ValueError", ",", "TypeError", ")", ":", "return", "args" ]
[ 1099, 0 ]
[ 1107, 19 ]
python
en
['en', 'en', 'en']
True
square_root
(value)
Filter to get square root of the value.
Filter to get square root of the value.
def square_root(value): """Filter to get square root of the value.""" try: return math.sqrt(float(value)) except (ValueError, TypeError): return value
[ "def", "square_root", "(", "value", ")", ":", "try", ":", "return", "math", ".", "sqrt", "(", "float", "(", "value", ")", ")", "except", "(", "ValueError", ",", "TypeError", ")", ":", "return", "value" ]
[ 1110, 0 ]
[ 1115, 20 ]
python
en
['en', 'en', 'en']
True
timestamp_custom
(value, date_format=DATE_STR_FORMAT, local=True)
Filter to convert given timestamp to format.
Filter to convert given timestamp to format.
def timestamp_custom(value, date_format=DATE_STR_FORMAT, local=True): """Filter to convert given timestamp to format.""" try: date = dt_util.utc_from_timestamp(value) if local: date = dt_util.as_local(date) return date.strftime(date_format) except (ValueError, TypeError): # If timestamp can't be converted return value
[ "def", "timestamp_custom", "(", "value", ",", "date_format", "=", "DATE_STR_FORMAT", ",", "local", "=", "True", ")", ":", "try", ":", "date", "=", "dt_util", ".", "utc_from_timestamp", "(", "value", ")", "if", "local", ":", "date", "=", "dt_util", ".", "as_local", "(", "date", ")", "return", "date", ".", "strftime", "(", "date_format", ")", "except", "(", "ValueError", ",", "TypeError", ")", ":", "# If timestamp can't be converted", "return", "value" ]
[ 1118, 0 ]
[ 1129, 20 ]
python
en
['en', 'en', 'en']
True
timestamp_local
(value)
Filter to convert given timestamp to local date/time.
Filter to convert given timestamp to local date/time.
def timestamp_local(value): """Filter to convert given timestamp to local date/time.""" try: return dt_util.as_local(dt_util.utc_from_timestamp(value)).strftime( DATE_STR_FORMAT ) except (ValueError, TypeError): # If timestamp can't be converted return value
[ "def", "timestamp_local", "(", "value", ")", ":", "try", ":", "return", "dt_util", ".", "as_local", "(", "dt_util", ".", "utc_from_timestamp", "(", "value", ")", ")", ".", "strftime", "(", "DATE_STR_FORMAT", ")", "except", "(", "ValueError", ",", "TypeError", ")", ":", "# If timestamp can't be converted", "return", "value" ]
[ 1132, 0 ]
[ 1140, 20 ]
python
en
['en', 'en', 'en']
True
timestamp_utc
(value)
Filter to convert given timestamp to UTC date/time.
Filter to convert given timestamp to UTC date/time.
def timestamp_utc(value): """Filter to convert given timestamp to UTC date/time.""" try: return dt_util.utc_from_timestamp(value).strftime(DATE_STR_FORMAT) except (ValueError, TypeError): # If timestamp can't be converted return value
[ "def", "timestamp_utc", "(", "value", ")", ":", "try", ":", "return", "dt_util", ".", "utc_from_timestamp", "(", "value", ")", ".", "strftime", "(", "DATE_STR_FORMAT", ")", "except", "(", "ValueError", ",", "TypeError", ")", ":", "# If timestamp can't be converted", "return", "value" ]
[ 1143, 0 ]
[ 1149, 20 ]
python
en
['en', 'en', 'en']
True
forgiving_as_timestamp
(value)
Try to convert value to timestamp.
Try to convert value to timestamp.
def forgiving_as_timestamp(value): """Try to convert value to timestamp.""" try: return dt_util.as_timestamp(value) except (ValueError, TypeError): return None
[ "def", "forgiving_as_timestamp", "(", "value", ")", ":", "try", ":", "return", "dt_util", ".", "as_timestamp", "(", "value", ")", "except", "(", "ValueError", ",", "TypeError", ")", ":", "return", "None" ]
[ 1152, 0 ]
[ 1157, 19 ]
python
en
['en', 'en', 'en']
True
strptime
(string, fmt)
Parse a time string to datetime.
Parse a time string to datetime.
def strptime(string, fmt): """Parse a time string to datetime.""" try: return datetime.strptime(string, fmt) except (ValueError, AttributeError, TypeError): return string
[ "def", "strptime", "(", "string", ",", "fmt", ")", ":", "try", ":", "return", "datetime", ".", "strptime", "(", "string", ",", "fmt", ")", "except", "(", "ValueError", ",", "AttributeError", ",", "TypeError", ")", ":", "return", "string" ]
[ 1160, 0 ]
[ 1165, 21 ]
python
en
['en', 'en', 'en']
True
fail_when_undefined
(value)
Filter to force a failure when the value is undefined.
Filter to force a failure when the value is undefined.
def fail_when_undefined(value): """Filter to force a failure when the value is undefined.""" if isinstance(value, jinja2.Undefined): value() return value
[ "def", "fail_when_undefined", "(", "value", ")", ":", "if", "isinstance", "(", "value", ",", "jinja2", ".", "Undefined", ")", ":", "value", "(", ")", "return", "value" ]
[ 1168, 0 ]
[ 1172, 16 ]
python
en
['en', 'en', 'en']
True
forgiving_float
(value)
Try to convert value to a float.
Try to convert value to a float.
def forgiving_float(value): """Try to convert value to a float.""" try: return float(value) except (ValueError, TypeError): return value
[ "def", "forgiving_float", "(", "value", ")", ":", "try", ":", "return", "float", "(", "value", ")", "except", "(", "ValueError", ",", "TypeError", ")", ":", "return", "value" ]
[ 1175, 0 ]
[ 1180, 20 ]
python
en
['en', 'en', 'en']
True
regex_match
(value, find="", ignorecase=False)
Match value using regex.
Match value using regex.
def regex_match(value, find="", ignorecase=False): """Match value using regex.""" if not isinstance(value, str): value = str(value) flags = re.I if ignorecase else 0 return bool(re.match(find, value, flags))
[ "def", "regex_match", "(", "value", ",", "find", "=", "\"\"", ",", "ignorecase", "=", "False", ")", ":", "if", "not", "isinstance", "(", "value", ",", "str", ")", ":", "value", "=", "str", "(", "value", ")", "flags", "=", "re", ".", "I", "if", "ignorecase", "else", "0", "return", "bool", "(", "re", ".", "match", "(", "find", ",", "value", ",", "flags", ")", ")" ]
[ 1183, 0 ]
[ 1188, 45 ]
python
de
['de', 'ky', 'en']
False
regex_replace
(value="", find="", replace="", ignorecase=False)
Replace using regex.
Replace using regex.
def regex_replace(value="", find="", replace="", ignorecase=False): """Replace using regex.""" if not isinstance(value, str): value = str(value) flags = re.I if ignorecase else 0 regex = re.compile(find, flags) return regex.sub(replace, value)
[ "def", "regex_replace", "(", "value", "=", "\"\"", ",", "find", "=", "\"\"", ",", "replace", "=", "\"\"", ",", "ignorecase", "=", "False", ")", ":", "if", "not", "isinstance", "(", "value", ",", "str", ")", ":", "value", "=", "str", "(", "value", ")", "flags", "=", "re", ".", "I", "if", "ignorecase", "else", "0", "regex", "=", "re", ".", "compile", "(", "find", ",", "flags", ")", "return", "regex", ".", "sub", "(", "replace", ",", "value", ")" ]
[ 1191, 0 ]
[ 1197, 36 ]
python
en
['nl', 'en', 'en']
True
regex_search
(value, find="", ignorecase=False)
Search using regex.
Search using regex.
def regex_search(value, find="", ignorecase=False): """Search using regex.""" if not isinstance(value, str): value = str(value) flags = re.I if ignorecase else 0 return bool(re.search(find, value, flags))
[ "def", "regex_search", "(", "value", ",", "find", "=", "\"\"", ",", "ignorecase", "=", "False", ")", ":", "if", "not", "isinstance", "(", "value", ",", "str", ")", ":", "value", "=", "str", "(", "value", ")", "flags", "=", "re", ".", "I", "if", "ignorecase", "else", "0", "return", "bool", "(", "re", ".", "search", "(", "find", ",", "value", ",", "flags", ")", ")" ]
[ 1200, 0 ]
[ 1205, 46 ]
python
en
['de', 'en', 'en']
True
regex_findall_index
(value, find="", index=0, ignorecase=False)
Find all matches using regex and then pick specific match index.
Find all matches using regex and then pick specific match index.
def regex_findall_index(value, find="", index=0, ignorecase=False): """Find all matches using regex and then pick specific match index.""" if not isinstance(value, str): value = str(value) flags = re.I if ignorecase else 0 return re.findall(find, value, flags)[index]
[ "def", "regex_findall_index", "(", "value", ",", "find", "=", "\"\"", ",", "index", "=", "0", ",", "ignorecase", "=", "False", ")", ":", "if", "not", "isinstance", "(", "value", ",", "str", ")", ":", "value", "=", "str", "(", "value", ")", "flags", "=", "re", ".", "I", "if", "ignorecase", "else", "0", "return", "re", ".", "findall", "(", "find", ",", "value", ",", "flags", ")", "[", "index", "]" ]
[ 1208, 0 ]
[ 1213, 48 ]
python
en
['en', 'en', 'en']
True
bitwise_and
(first_value, second_value)
Perform a bitwise and operation.
Perform a bitwise and operation.
def bitwise_and(first_value, second_value): """Perform a bitwise and operation.""" return first_value & second_value
[ "def", "bitwise_and", "(", "first_value", ",", "second_value", ")", ":", "return", "first_value", "&", "second_value" ]
[ 1216, 0 ]
[ 1218, 37 ]
python
en
['en', 'en', 'en']
True
bitwise_or
(first_value, second_value)
Perform a bitwise or operation.
Perform a bitwise or operation.
def bitwise_or(first_value, second_value): """Perform a bitwise or operation.""" return first_value | second_value
[ "def", "bitwise_or", "(", "first_value", ",", "second_value", ")", ":", "return", "first_value", "|", "second_value" ]
[ 1221, 0 ]
[ 1223, 37 ]
python
en
['en', 'en', 'en']
True
base64_encode
(value)
Perform base64 encode.
Perform base64 encode.
def base64_encode(value): """Perform base64 encode.""" return base64.b64encode(value.encode("utf-8")).decode("utf-8")
[ "def", "base64_encode", "(", "value", ")", ":", "return", "base64", ".", "b64encode", "(", "value", ".", "encode", "(", "\"utf-8\"", ")", ")", ".", "decode", "(", "\"utf-8\"", ")" ]
[ 1226, 0 ]
[ 1228, 66 ]
python
en
['en', 'hmn', 'en']
True
base64_decode
(value)
Perform base64 denode.
Perform base64 denode.
def base64_decode(value): """Perform base64 denode.""" return base64.b64decode(value).decode("utf-8")
[ "def", "base64_decode", "(", "value", ")", ":", "return", "base64", ".", "b64decode", "(", "value", ")", ".", "decode", "(", "\"utf-8\"", ")" ]
[ 1231, 0 ]
[ 1233, 50 ]
python
da
['de', 'da', 'pt']
False
ordinal
(value)
Perform ordinal conversion.
Perform ordinal conversion.
def ordinal(value): """Perform ordinal conversion.""" return str(value) + ( list(["th", "st", "nd", "rd"] + ["th"] * 6)[(int(str(value)[-1])) % 10] if int(str(value)[-2:]) % 100 not in range(11, 14) else "th" )
[ "def", "ordinal", "(", "value", ")", ":", "return", "str", "(", "value", ")", "+", "(", "list", "(", "[", "\"th\"", ",", "\"st\"", ",", "\"nd\"", ",", "\"rd\"", "]", "+", "[", "\"th\"", "]", "*", "6", ")", "[", "(", "int", "(", "str", "(", "value", ")", "[", "-", "1", "]", ")", ")", "%", "10", "]", "if", "int", "(", "str", "(", "value", ")", "[", "-", "2", ":", "]", ")", "%", "100", "not", "in", "range", "(", "11", ",", "14", ")", "else", "\"th\"", ")" ]
[ 1236, 0 ]
[ 1242, 5 ]
python
en
['en', 'ca', 'en']
True
from_json
(value)
Convert a JSON string to an object.
Convert a JSON string to an object.
def from_json(value): """Convert a JSON string to an object.""" return json.loads(value)
[ "def", "from_json", "(", "value", ")", ":", "return", "json", ".", "loads", "(", "value", ")" ]
[ 1245, 0 ]
[ 1247, 28 ]
python
en
['en', 'lb', 'en']
True
to_json
(value)
Convert an object to a JSON string.
Convert an object to a JSON string.
def to_json(value): """Convert an object to a JSON string.""" return json.dumps(value)
[ "def", "to_json", "(", "value", ")", ":", "return", "json", ".", "dumps", "(", "value", ")" ]
[ 1250, 0 ]
[ 1252, 28 ]
python
en
['en', 'lb', 'en']
True
random_every_time
(context, values)
Choose a random value. Unlike Jinja's random filter, this is context-dependent to avoid caching the chosen value.
Choose a random value.
def random_every_time(context, values): """Choose a random value. Unlike Jinja's random filter, this is context-dependent to avoid caching the chosen value. """ return random.choice(values)
[ "def", "random_every_time", "(", "context", ",", "values", ")", ":", "return", "random", ".", "choice", "(", "values", ")" ]
[ 1256, 0 ]
[ 1262, 32 ]
python
en
['en', 'st', 'en']
True
relative_time
(value)
Take a datetime and return its "age" as a string. The age can be in second, minute, hour, day, month or year. Only the biggest unit is considered, e.g. if it's 2 days and 3 hours, "2 days" will be returned. Make sure date is not in the future, or else it will return None. If the input are not a datetime object the input will be returned unmodified.
Take a datetime and return its "age" as a string.
def relative_time(value): """ Take a datetime and return its "age" as a string. The age can be in second, minute, hour, day, month or year. Only the biggest unit is considered, e.g. if it's 2 days and 3 hours, "2 days" will be returned. Make sure date is not in the future, or else it will return None. If the input are not a datetime object the input will be returned unmodified. """ if not isinstance(value, datetime): return value if not value.tzinfo: value = dt_util.as_local(value) if dt_util.now() < value: return value return dt_util.get_age(value)
[ "def", "relative_time", "(", "value", ")", ":", "if", "not", "isinstance", "(", "value", ",", "datetime", ")", ":", "return", "value", "if", "not", "value", ".", "tzinfo", ":", "value", "=", "dt_util", ".", "as_local", "(", "value", ")", "if", "dt_util", ".", "now", "(", ")", "<", "value", ":", "return", "value", "return", "dt_util", ".", "get_age", "(", "value", ")" ]
[ 1265, 0 ]
[ 1283, 33 ]
python
en
['en', 'error', 'th']
False
urlencode
(value)
Urlencode dictionary and return as UTF-8 string.
Urlencode dictionary and return as UTF-8 string.
def urlencode(value): """Urlencode dictionary and return as UTF-8 string.""" return urllib_urlencode(value).encode("utf-8")
[ "def", "urlencode", "(", "value", ")", ":", "return", "urllib_urlencode", "(", "value", ")", ".", "encode", "(", "\"utf-8\"", ")" ]
[ 1286, 0 ]
[ 1288, 50 ]
python
en
['en', 'en', 'en']
True
TupleWrapper.__new__
( cls, value: tuple, *, render_result: Optional[str] = None )
Create a new tuple class.
Create a new tuple class.
def __new__( cls, value: tuple, *, render_result: Optional[str] = None ) -> "TupleWrapper": """Create a new tuple class.""" return super().__new__(cls, tuple(value))
[ "def", "__new__", "(", "cls", ",", "value", ":", "tuple", ",", "*", ",", "render_result", ":", "Optional", "[", "str", "]", "=", "None", ")", "->", "\"TupleWrapper\"", ":", "return", "super", "(", ")", ".", "__new__", "(", "cls", ",", "tuple", "(", "value", ")", ")" ]
[ 154, 4 ]
[ 158, 49 ]
python
en
['en', 'sm', 'en']
True
TupleWrapper.__init__
(self, value: tuple, *, render_result: Optional[str] = None)
Initialize a new tuple class.
Initialize a new tuple class.
def __init__(self, value: tuple, *, render_result: Optional[str] = None): """Initialize a new tuple class.""" self.render_result = render_result
[ "def", "__init__", "(", "self", ",", "value", ":", "tuple", ",", "*", ",", "render_result", ":", "Optional", "[", "str", "]", "=", "None", ")", ":", "self", ".", "render_result", "=", "render_result" ]
[ 162, 4 ]
[ 164, 42 ]
python
en
['en', 'en', 'en']
True
TupleWrapper.__str__
(self)
Return string representation.
Return string representation.
def __str__(self) -> str: """Return string representation.""" if self.render_result is None: return super().__str__() return self.render_result
[ "def", "__str__", "(", "self", ")", "->", "str", ":", "if", "self", ".", "render_result", "is", "None", ":", "return", "super", "(", ")", ".", "__str__", "(", ")", "return", "self", ".", "render_result" ]
[ 166, 4 ]
[ 171, 33 ]
python
en
['en', 'no', 'en']
True
RenderInfo.__init__
(self, template)
Initialise.
Initialise.
def __init__(self, template): """Initialise.""" self.template = template # Will be set sensibly once frozen. self.filter_lifecycle = _true self.filter = _true self._result = None self.is_static = False self.exception = None self.all_states = False self.all_states_lifecycle = False self.domains = set() self.domains_lifecycle = set() self.entities = set() self.rate_limit = None self.has_time = False
[ "def", "__init__", "(", "self", ",", "template", ")", ":", "self", ".", "template", "=", "template", "# Will be set sensibly once frozen.", "self", ".", "filter_lifecycle", "=", "_true", "self", ".", "filter", "=", "_true", "self", ".", "_result", "=", "None", "self", ".", "is_static", "=", "False", "self", ".", "exception", "=", "None", "self", ".", "all_states", "=", "False", "self", ".", "all_states_lifecycle", "=", "False", "self", ".", "domains", "=", "set", "(", ")", "self", ".", "domains_lifecycle", "=", "set", "(", ")", "self", ".", "entities", "=", "set", "(", ")", "self", ".", "rate_limit", "=", "None", "self", ".", "has_time", "=", "False" ]
[ 191, 4 ]
[ 206, 29 ]
python
fr
['fr', 'zu', 'it']
False
RenderInfo.__repr__
(self)
Representation of RenderInfo.
Representation of RenderInfo.
def __repr__(self) -> str: """Representation of RenderInfo.""" return f"<RenderInfo {self.template} all_states={self.all_states} all_states_lifecycle={self.all_states_lifecycle} domains={self.domains} domains_lifecycle={self.domains_lifecycle} entities={self.entities} rate_limit={self.rate_limit}> has_time={self.has_time}"
[ "def", "__repr__", "(", "self", ")", "->", "str", ":", "return", "f\"<RenderInfo {self.template} all_states={self.all_states} all_states_lifecycle={self.all_states_lifecycle} domains={self.domains} domains_lifecycle={self.domains_lifecycle} entities={self.entities} rate_limit={self.rate_limit}> has_time={self.has_time}\"" ]
[ 208, 4 ]
[ 210, 269 ]
python
en
['en', 'nl', 'en']
True
RenderInfo._filter_domains_and_entities
(self, entity_id: str)
Template should re-render if the entity state changes when we match specific domains or entities.
Template should re-render if the entity state changes when we match specific domains or entities.
def _filter_domains_and_entities(self, entity_id: str) -> bool: """Template should re-render if the entity state changes when we match specific domains or entities.""" return ( split_entity_id(entity_id)[0] in self.domains or entity_id in self.entities )
[ "def", "_filter_domains_and_entities", "(", "self", ",", "entity_id", ":", "str", ")", "->", "bool", ":", "return", "(", "split_entity_id", "(", "entity_id", ")", "[", "0", "]", "in", "self", ".", "domains", "or", "entity_id", "in", "self", ".", "entities", ")" ]
[ 212, 4 ]
[ 216, 9 ]
python
en
['en', 'en', 'en']
True
RenderInfo._filter_entities
(self, entity_id: str)
Template should re-render if the entity state changes when we match specific entities.
Template should re-render if the entity state changes when we match specific entities.
def _filter_entities(self, entity_id: str) -> bool: """Template should re-render if the entity state changes when we match specific entities.""" return entity_id in self.entities
[ "def", "_filter_entities", "(", "self", ",", "entity_id", ":", "str", ")", "->", "bool", ":", "return", "entity_id", "in", "self", ".", "entities" ]
[ 218, 4 ]
[ 220, 41 ]
python
en
['en', 'en', 'en']
True
RenderInfo._filter_lifecycle_domains
(self, entity_id: str)
Template should re-render if the entity is added or removed with domains watched.
Template should re-render if the entity is added or removed with domains watched.
def _filter_lifecycle_domains(self, entity_id: str) -> bool: """Template should re-render if the entity is added or removed with domains watched.""" return split_entity_id(entity_id)[0] in self.domains_lifecycle
[ "def", "_filter_lifecycle_domains", "(", "self", ",", "entity_id", ":", "str", ")", "->", "bool", ":", "return", "split_entity_id", "(", "entity_id", ")", "[", "0", "]", "in", "self", ".", "domains_lifecycle" ]
[ 222, 4 ]
[ 224, 70 ]
python
en
['en', 'en', 'en']
True
RenderInfo.result
(self)
Results of the template computation.
Results of the template computation.
def result(self) -> str: """Results of the template computation.""" if self.exception is not None: raise self.exception return self._result
[ "def", "result", "(", "self", ")", "->", "str", ":", "if", "self", ".", "exception", "is", "not", "None", ":", "raise", "self", ".", "exception", "return", "self", ".", "_result" ]
[ 226, 4 ]
[ 230, 27 ]
python
en
['en', 'en', 'en']
True
Template.__init__
(self, template, hass=None)
Instantiate a template.
Instantiate a template.
def __init__(self, template, hass=None): """Instantiate a template.""" if not isinstance(template, str): raise TypeError("Expected template to be a string") self.template: str = template.strip() self._compiled_code = None self._compiled = None self.hass = hass self.is_static = not is_template_string(template)
[ "def", "__init__", "(", "self", ",", "template", ",", "hass", "=", "None", ")", ":", "if", "not", "isinstance", "(", "template", ",", "str", ")", ":", "raise", "TypeError", "(", "\"Expected template to be a string\"", ")", "self", ".", "template", ":", "str", "=", "template", ".", "strip", "(", ")", "self", ".", "_compiled_code", "=", "None", "self", ".", "_compiled", "=", "None", "self", ".", "hass", "=", "hass", "self", ".", "is_static", "=", "not", "is_template_string", "(", "template", ")" ]
[ 283, 4 ]
[ 292, 57 ]
python
en
['en', 'ro', 'en']
True
Template.ensure_valid
(self)
Return if template is valid.
Return if template is valid.
def ensure_valid(self): """Return if template is valid.""" if self._compiled_code is not None: return try: self._compiled_code = self._env.compile(self.template) except jinja2.TemplateError as err: raise TemplateError(err) from err
[ "def", "ensure_valid", "(", "self", ")", ":", "if", "self", ".", "_compiled_code", "is", "not", "None", ":", "return", "try", ":", "self", ".", "_compiled_code", "=", "self", ".", "_env", ".", "compile", "(", "self", ".", "template", ")", "except", "jinja2", ".", "TemplateError", "as", "err", ":", "raise", "TemplateError", "(", "err", ")", "from", "err" ]
[ 303, 4 ]
[ 311, 45 ]
python
en
['en', 'et', 'en']
True
Template.render
( self, variables: TemplateVarsType = None, parse_result: bool = True, **kwargs: Any, )
Render given template.
Render given template.
def render( self, variables: TemplateVarsType = None, parse_result: bool = True, **kwargs: Any, ) -> Any: """Render given template.""" if self.is_static: if self.hass.config.legacy_templates or not parse_result: return self.template return self._parse_result(self.template) return run_callback_threadsafe( self.hass.loop, partial(self.async_render, variables, parse_result, **kwargs), ).result()
[ "def", "render", "(", "self", ",", "variables", ":", "TemplateVarsType", "=", "None", ",", "parse_result", ":", "bool", "=", "True", ",", "*", "*", "kwargs", ":", "Any", ",", ")", "->", "Any", ":", "if", "self", ".", "is_static", ":", "if", "self", ".", "hass", ".", "config", ".", "legacy_templates", "or", "not", "parse_result", ":", "return", "self", ".", "template", "return", "self", ".", "_parse_result", "(", "self", ".", "template", ")", "return", "run_callback_threadsafe", "(", "self", ".", "hass", ".", "loop", ",", "partial", "(", "self", ".", "async_render", ",", "variables", ",", "parse_result", ",", "*", "*", "kwargs", ")", ",", ")", ".", "result", "(", ")" ]
[ 313, 4 ]
[ 328, 18 ]
python
en
['da', 'en', 'en']
True
Template.async_render
( self, variables: TemplateVarsType = None, parse_result: bool = True, **kwargs: Any, )
Render given template. This method must be run in the event loop.
Render given template.
def async_render( self, variables: TemplateVarsType = None, parse_result: bool = True, **kwargs: Any, ) -> Any: """Render given template. This method must be run in the event loop. """ if self.is_static: if self.hass.config.legacy_templates or not parse_result: return self.template return self._parse_result(self.template) compiled = self._compiled or self._ensure_compiled() if variables is not None: kwargs.update(variables) try: render_result = compiled.render(kwargs) except Exception as err: # pylint: disable=broad-except raise TemplateError(err) from err render_result = render_result.strip() if self.hass.config.legacy_templates or not parse_result: return render_result return self._parse_result(render_result)
[ "def", "async_render", "(", "self", ",", "variables", ":", "TemplateVarsType", "=", "None", ",", "parse_result", ":", "bool", "=", "True", ",", "*", "*", "kwargs", ":", "Any", ",", ")", "->", "Any", ":", "if", "self", ".", "is_static", ":", "if", "self", ".", "hass", ".", "config", ".", "legacy_templates", "or", "not", "parse_result", ":", "return", "self", ".", "template", "return", "self", ".", "_parse_result", "(", "self", ".", "template", ")", "compiled", "=", "self", ".", "_compiled", "or", "self", ".", "_ensure_compiled", "(", ")", "if", "variables", "is", "not", "None", ":", "kwargs", ".", "update", "(", "variables", ")", "try", ":", "render_result", "=", "compiled", ".", "render", "(", "kwargs", ")", "except", "Exception", "as", "err", ":", "# pylint: disable=broad-except", "raise", "TemplateError", "(", "err", ")", "from", "err", "render_result", "=", "render_result", ".", "strip", "(", ")", "if", "self", ".", "hass", ".", "config", ".", "legacy_templates", "or", "not", "parse_result", ":", "return", "render_result", "return", "self", ".", "_parse_result", "(", "render_result", ")" ]
[ 331, 4 ]
[ 361, 48 ]
python
en
['da', 'en', 'en']
True
Template._parse_result
(self, render_result: str)
Parse the result.
Parse the result.
def _parse_result(self, render_result: str) -> Any: # pylint: disable=no-self-use """Parse the result.""" try: result = literal_eval(render_result) if type(result) in RESULT_WRAPPERS: result = RESULT_WRAPPERS[type(result)]( result, render_result=render_result ) # If the literal_eval result is a string, use the original # render, by not returning right here. The evaluation of strings # resulting in strings impacts quotes, to avoid unexpected # output; use the original render instead of the evaluated one. # Complex and scientific values are also unexpected. Filter them out. if ( # Filter out string and complex numbers not isinstance(result, (str, complex)) and ( # Pass if not numeric and not a boolean not isinstance(result, (int, float)) # Or it's a boolean (inherit from int) or isinstance(result, bool) # Or if it's a digit or _IS_NUMERIC.match(render_result) is not None ) ): return result except (ValueError, TypeError, SyntaxError, MemoryError): pass return render_result
[ "def", "_parse_result", "(", "self", ",", "render_result", ":", "str", ")", "->", "Any", ":", "# pylint: disable=no-self-use", "try", ":", "result", "=", "literal_eval", "(", "render_result", ")", "if", "type", "(", "result", ")", "in", "RESULT_WRAPPERS", ":", "result", "=", "RESULT_WRAPPERS", "[", "type", "(", "result", ")", "]", "(", "result", ",", "render_result", "=", "render_result", ")", "# If the literal_eval result is a string, use the original", "# render, by not returning right here. The evaluation of strings", "# resulting in strings impacts quotes, to avoid unexpected", "# output; use the original render instead of the evaluated one.", "# Complex and scientific values are also unexpected. Filter them out.", "if", "(", "# Filter out string and complex numbers", "not", "isinstance", "(", "result", ",", "(", "str", ",", "complex", ")", ")", "and", "(", "# Pass if not numeric and not a boolean", "not", "isinstance", "(", "result", ",", "(", "int", ",", "float", ")", ")", "# Or it's a boolean (inherit from int)", "or", "isinstance", "(", "result", ",", "bool", ")", "# Or if it's a digit", "or", "_IS_NUMERIC", ".", "match", "(", "render_result", ")", "is", "not", "None", ")", ")", ":", "return", "result", "except", "(", "ValueError", ",", "TypeError", ",", "SyntaxError", ",", "MemoryError", ")", ":", "pass", "return", "render_result" ]
[ 363, 4 ]
[ 394, 28 ]
python
en
['en', 'en', 'en']
True
Template.async_render_will_timeout
( self, timeout: float, variables: TemplateVarsType = None, **kwargs: Any )
Check to see if rendering a template will timeout during render. This is intended to check for expensive templates that will make the system unstable. The template is rendered in the executor to ensure it does not tie up the event loop. This function is not a security control and is only intended to be used as a safety check when testing templates. This method must be run in the event loop.
Check to see if rendering a template will timeout during render.
async def async_render_will_timeout( self, timeout: float, variables: TemplateVarsType = None, **kwargs: Any ) -> bool: """Check to see if rendering a template will timeout during render. This is intended to check for expensive templates that will make the system unstable. The template is rendered in the executor to ensure it does not tie up the event loop. This function is not a security control and is only intended to be used as a safety check when testing templates. This method must be run in the event loop. """ assert self.hass if self.is_static: return False compiled = self._compiled or self._ensure_compiled() if variables is not None: kwargs.update(variables) finish_event = asyncio.Event() def _render_template(): try: compiled.render(kwargs) except TimeoutError: pass finally: run_callback_threadsafe(self.hass.loop, finish_event.set) try: template_render_thread = ThreadWithException(target=_render_template) template_render_thread.start() await asyncio.wait_for(finish_event.wait(), timeout=timeout) except asyncio.TimeoutError: template_render_thread.raise_exc(TimeoutError) return True finally: template_render_thread.join() return False
[ "async", "def", "async_render_will_timeout", "(", "self", ",", "timeout", ":", "float", ",", "variables", ":", "TemplateVarsType", "=", "None", ",", "*", "*", "kwargs", ":", "Any", ")", "->", "bool", ":", "assert", "self", ".", "hass", "if", "self", ".", "is_static", ":", "return", "False", "compiled", "=", "self", ".", "_compiled", "or", "self", ".", "_ensure_compiled", "(", ")", "if", "variables", "is", "not", "None", ":", "kwargs", ".", "update", "(", "variables", ")", "finish_event", "=", "asyncio", ".", "Event", "(", ")", "def", "_render_template", "(", ")", ":", "try", ":", "compiled", ".", "render", "(", "kwargs", ")", "except", "TimeoutError", ":", "pass", "finally", ":", "run_callback_threadsafe", "(", "self", ".", "hass", ".", "loop", ",", "finish_event", ".", "set", ")", "try", ":", "template_render_thread", "=", "ThreadWithException", "(", "target", "=", "_render_template", ")", "template_render_thread", ".", "start", "(", ")", "await", "asyncio", ".", "wait_for", "(", "finish_event", ".", "wait", "(", ")", ",", "timeout", "=", "timeout", ")", "except", "asyncio", ".", "TimeoutError", ":", "template_render_thread", ".", "raise_exc", "(", "TimeoutError", ")", "return", "True", "finally", ":", "template_render_thread", ".", "join", "(", ")", "return", "False" ]
[ 396, 4 ]
[ 442, 20 ]
python
en
['en', 'en', 'en']
True
Template.async_render_to_info
( self, variables: TemplateVarsType = None, **kwargs: Any )
Render the template and collect an entity filter.
Render the template and collect an entity filter.
def async_render_to_info( self, variables: TemplateVarsType = None, **kwargs: Any ) -> RenderInfo: """Render the template and collect an entity filter.""" assert self.hass and _RENDER_INFO not in self.hass.data render_info = RenderInfo(self) # pylint: disable=protected-access if self.is_static: render_info._result = self.template.strip() render_info._freeze_static() return render_info self.hass.data[_RENDER_INFO] = render_info try: render_info._result = self.async_render(variables, **kwargs) except TemplateError as ex: render_info.exception = ex finally: del self.hass.data[_RENDER_INFO] render_info._freeze() return render_info
[ "def", "async_render_to_info", "(", "self", ",", "variables", ":", "TemplateVarsType", "=", "None", ",", "*", "*", "kwargs", ":", "Any", ")", "->", "RenderInfo", ":", "assert", "self", ".", "hass", "and", "_RENDER_INFO", "not", "in", "self", ".", "hass", ".", "data", "render_info", "=", "RenderInfo", "(", "self", ")", "# pylint: disable=protected-access", "if", "self", ".", "is_static", ":", "render_info", ".", "_result", "=", "self", ".", "template", ".", "strip", "(", ")", "render_info", ".", "_freeze_static", "(", ")", "return", "render_info", "self", ".", "hass", ".", "data", "[", "_RENDER_INFO", "]", "=", "render_info", "try", ":", "render_info", ".", "_result", "=", "self", ".", "async_render", "(", "variables", ",", "*", "*", "kwargs", ")", "except", "TemplateError", "as", "ex", ":", "render_info", ".", "exception", "=", "ex", "finally", ":", "del", "self", ".", "hass", ".", "data", "[", "_RENDER_INFO", "]", "render_info", ".", "_freeze", "(", ")", "return", "render_info" ]
[ 445, 4 ]
[ 468, 26 ]
python
en
['en', 'en', 'en']
True
Template.render_with_possible_json_value
(self, value, error_value=_SENTINEL)
Render template with value exposed. If valid JSON will expose value_json too.
Render template with value exposed.
def render_with_possible_json_value(self, value, error_value=_SENTINEL): """Render template with value exposed. If valid JSON will expose value_json too. """ if self.is_static: return self.template return run_callback_threadsafe( self.hass.loop, self.async_render_with_possible_json_value, value, error_value, ).result()
[ "def", "render_with_possible_json_value", "(", "self", ",", "value", ",", "error_value", "=", "_SENTINEL", ")", ":", "if", "self", ".", "is_static", ":", "return", "self", ".", "template", "return", "run_callback_threadsafe", "(", "self", ".", "hass", ".", "loop", ",", "self", ".", "async_render_with_possible_json_value", ",", "value", ",", "error_value", ",", ")", ".", "result", "(", ")" ]
[ 470, 4 ]
[ 483, 18 ]
python
en
['en', 'en', 'en']
True
Template.async_render_with_possible_json_value
( self, value, error_value=_SENTINEL, variables=None )
Render template with value exposed. If valid JSON will expose value_json too. This method must be run in the event loop.
Render template with value exposed.
def async_render_with_possible_json_value( self, value, error_value=_SENTINEL, variables=None ): """Render template with value exposed. If valid JSON will expose value_json too. This method must be run in the event loop. """ if self.is_static: return self.template if self._compiled is None: self._ensure_compiled() variables = dict(variables or {}) variables["value"] = value try: variables["value_json"] = json.loads(value) except (ValueError, TypeError): pass try: return self._compiled.render(variables).strip() except jinja2.TemplateError as ex: if error_value is _SENTINEL: _LOGGER.error( "Error parsing value: %s (value: %s, template: %s)", ex, value, self.template, ) return value if error_value is _SENTINEL else error_value
[ "def", "async_render_with_possible_json_value", "(", "self", ",", "value", ",", "error_value", "=", "_SENTINEL", ",", "variables", "=", "None", ")", ":", "if", "self", ".", "is_static", ":", "return", "self", ".", "template", "if", "self", ".", "_compiled", "is", "None", ":", "self", ".", "_ensure_compiled", "(", ")", "variables", "=", "dict", "(", "variables", "or", "{", "}", ")", "variables", "[", "\"value\"", "]", "=", "value", "try", ":", "variables", "[", "\"value_json\"", "]", "=", "json", ".", "loads", "(", "value", ")", "except", "(", "ValueError", ",", "TypeError", ")", ":", "pass", "try", ":", "return", "self", ".", "_compiled", ".", "render", "(", "variables", ")", ".", "strip", "(", ")", "except", "jinja2", ".", "TemplateError", "as", "ex", ":", "if", "error_value", "is", "_SENTINEL", ":", "_LOGGER", ".", "error", "(", "\"Error parsing value: %s (value: %s, template: %s)\"", ",", "ex", ",", "value", ",", "self", ".", "template", ",", ")", "return", "value", "if", "error_value", "is", "_SENTINEL", "else", "error_value" ]
[ 486, 4 ]
[ 519, 69 ]
python
en
['en', 'en', 'en']
True
Template._ensure_compiled
(self)
Bind a template to a specific hass instance.
Bind a template to a specific hass instance.
def _ensure_compiled(self): """Bind a template to a specific hass instance.""" self.ensure_valid() assert self.hass is not None, "hass variable not set on template" env = self._env self._compiled = jinja2.Template.from_code( env, self._compiled_code, env.globals, None ) return self._compiled
[ "def", "_ensure_compiled", "(", "self", ")", ":", "self", ".", "ensure_valid", "(", ")", "assert", "self", ".", "hass", "is", "not", "None", ",", "\"hass variable not set on template\"", "env", "=", "self", ".", "_env", "self", ".", "_compiled", "=", "jinja2", ".", "Template", ".", "from_code", "(", "env", ",", "self", ".", "_compiled_code", ",", "env", ".", "globals", ",", "None", ")", "return", "self", ".", "_compiled" ]
[ 521, 4 ]
[ 533, 29 ]
python
en
['en', 'en', 'en']
True
Template.__eq__
(self, other)
Compare template with another.
Compare template with another.
def __eq__(self, other): """Compare template with another.""" return ( self.__class__ == other.__class__ and self.template == other.template and self.hass == other.hass )
[ "def", "__eq__", "(", "self", ",", "other", ")", ":", "return", "(", "self", ".", "__class__", "==", "other", ".", "__class__", "and", "self", ".", "template", "==", "other", ".", "template", "and", "self", ".", "hass", "==", "other", ".", "hass", ")" ]
[ 535, 4 ]
[ 541, 9 ]
python
en
['en', 'en', 'en']
True
Template.__hash__
(self)
Hash code for template.
Hash code for template.
def __hash__(self) -> int: """Hash code for template.""" return hash(self.template)
[ "def", "__hash__", "(", "self", ")", "->", "int", ":", "return", "hash", "(", "self", ".", "template", ")" ]
[ 543, 4 ]
[ 545, 34 ]
python
en
['en', 'en', 'en']
True
Template.__repr__
(self)
Representation of Template.
Representation of Template.
def __repr__(self) -> str: """Representation of Template.""" return 'Template("' + self.template + '")'
[ "def", "__repr__", "(", "self", ")", "->", "str", ":", "return", "'Template(\"'", "+", "self", ".", "template", "+", "'\")'" ]
[ 547, 4 ]
[ 549, 50 ]
python
en
['en', 'en', 'en']
True
AllStates.__init__
(self, hass)
Initialize all states.
Initialize all states.
def __init__(self, hass): """Initialize all states.""" self._hass = hass
[ "def", "__init__", "(", "self", ",", "hass", ")", ":", "self", ".", "_hass", "=", "hass" ]
[ 555, 4 ]
[ 557, 25 ]
python
en
['en', 'en', 'en']
True
AllStates.__getattr__
(self, name)
Return the domain state.
Return the domain state.
def __getattr__(self, name): """Return the domain state.""" if "." in name: return _get_state_if_valid(self._hass, name) if name in _RESERVED_NAMES: return None if not valid_entity_id(f"{name}.entity"): raise TemplateError(f"Invalid domain name '{name}'") return DomainStates(self._hass, name)
[ "def", "__getattr__", "(", "self", ",", "name", ")", ":", "if", "\".\"", "in", "name", ":", "return", "_get_state_if_valid", "(", "self", ".", "_hass", ",", "name", ")", "if", "name", "in", "_RESERVED_NAMES", ":", "return", "None", "if", "not", "valid_entity_id", "(", "f\"{name}.entity\"", ")", ":", "raise", "TemplateError", "(", "f\"Invalid domain name '{name}'\"", ")", "return", "DomainStates", "(", "self", ".", "_hass", ",", "name", ")" ]
[ 559, 4 ]
[ 570, 45 ]
python
en
['en', 'en', 'en']
True
AllStates.__iter__
(self)
Return all states.
Return all states.
def __iter__(self): """Return all states.""" self._collect_all() return _state_generator(self._hass, None)
[ "def", "__iter__", "(", "self", ")", ":", "self", ".", "_collect_all", "(", ")", "return", "_state_generator", "(", "self", ".", "_hass", ",", "None", ")" ]
[ 586, 4 ]
[ 589, 49 ]
python
en
['en', 'ko', 'en']
True
AllStates.__len__
(self)
Return number of states.
Return number of states.
def __len__(self) -> int: """Return number of states.""" self._collect_all_lifecycle() return self._hass.states.async_entity_ids_count()
[ "def", "__len__", "(", "self", ")", "->", "int", ":", "self", ".", "_collect_all_lifecycle", "(", ")", "return", "self", ".", "_hass", ".", "states", ".", "async_entity_ids_count", "(", ")" ]
[ 591, 4 ]
[ 594, 57 ]
python
en
['en', 'en', 'en']
True
AllStates.__call__
(self, entity_id)
Return the states.
Return the states.
def __call__(self, entity_id): """Return the states.""" state = _get_state(self._hass, entity_id) return STATE_UNKNOWN if state is None else state.state
[ "def", "__call__", "(", "self", ",", "entity_id", ")", ":", "state", "=", "_get_state", "(", "self", ".", "_hass", ",", "entity_id", ")", "return", "STATE_UNKNOWN", "if", "state", "is", "None", "else", "state", ".", "state" ]
[ 596, 4 ]
[ 599, 62 ]
python
en
['en', 'ko', 'en']
True
AllStates.__repr__
(self)
Representation of All States.
Representation of All States.
def __repr__(self) -> str: """Representation of All States.""" return "<template AllStates>"
[ "def", "__repr__", "(", "self", ")", "->", "str", ":", "return", "\"<template AllStates>\"" ]
[ 601, 4 ]
[ 603, 37 ]
python
en
['en', 'en', 'en']
True
DomainStates.__init__
(self, hass, domain)
Initialize the domain states.
Initialize the domain states.
def __init__(self, hass, domain): """Initialize the domain states.""" self._hass = hass self._domain = domain
[ "def", "__init__", "(", "self", ",", "hass", ",", "domain", ")", ":", "self", ".", "_hass", "=", "hass", "self", ".", "_domain", "=", "domain" ]
[ 609, 4 ]
[ 612, 29 ]
python
en
['en', 'en', 'en']
True
DomainStates.__getattr__
(self, name)
Return the states.
Return the states.
def __getattr__(self, name): """Return the states.""" return _get_state_if_valid(self._hass, f"{self._domain}.{name}")
[ "def", "__getattr__", "(", "self", ",", "name", ")", ":", "return", "_get_state_if_valid", "(", "self", ".", "_hass", ",", "f\"{self._domain}.{name}\"", ")" ]
[ 614, 4 ]
[ 616, 72 ]
python
en
['en', 'ko', 'en']
True
DomainStates.__iter__
(self)
Return the iteration over all the states.
Return the iteration over all the states.
def __iter__(self): """Return the iteration over all the states.""" self._collect_domain() return _state_generator(self._hass, self._domain)
[ "def", "__iter__", "(", "self", ")", ":", "self", ".", "_collect_domain", "(", ")", "return", "_state_generator", "(", "self", ".", "_hass", ",", "self", ".", "_domain", ")" ]
[ 632, 4 ]
[ 635, 57 ]
python
en
['en', 'en', 'en']
True
DomainStates.__len__
(self)
Return number of states.
Return number of states.
def __len__(self) -> int: """Return number of states.""" self._collect_domain_lifecycle() return self._hass.states.async_entity_ids_count(self._domain)
[ "def", "__len__", "(", "self", ")", "->", "int", ":", "self", ".", "_collect_domain_lifecycle", "(", ")", "return", "self", ".", "_hass", ".", "states", ".", "async_entity_ids_count", "(", "self", ".", "_domain", ")" ]
[ 637, 4 ]
[ 640, 69 ]
python
en
['en', 'en', 'en']
True
DomainStates.__repr__
(self)
Representation of Domain States.
Representation of Domain States.
def __repr__(self) -> str: """Representation of Domain States.""" return f"<template DomainStates('{self._domain}')>"
[ "def", "__repr__", "(", "self", ")", "->", "str", ":", "return", "f\"<template DomainStates('{self._domain}')>\"" ]
[ 642, 4 ]
[ 644, 59 ]
python
en
['en', 'en', 'en']
True
TemplateState.__init__
(self, hass, state, collect=True)
Initialize template state.
Initialize template state.
def __init__(self, hass, state, collect=True): """Initialize template state.""" self._hass = hass self._state = state self._collect = collect
[ "def", "__init__", "(", "self", ",", "hass", ",", "state", ",", "collect", "=", "True", ")", ":", "self", ".", "_hass", "=", "hass", "self", ".", "_state", "=", "state", "self", ".", "_collect", "=", "collect" ]
[ 654, 4 ]
[ 658, 31 ]
python
en
['en', 'en', 'en']
True
TemplateState.__getitem__
(self, item)
Return a property as an attribute for jinja.
Return a property as an attribute for jinja.
def __getitem__(self, item): """Return a property as an attribute for jinja.""" if item in _COLLECTABLE_STATE_ATTRIBUTES: # _collect_state inlined here for performance if self._collect and _RENDER_INFO in self._hass.data: self._hass.data[_RENDER_INFO].entities.add(self._state.entity_id) return getattr(self._state, item) if item == "entity_id": return self._state.entity_id if item == "state_with_unit": return self.state_with_unit raise KeyError
[ "def", "__getitem__", "(", "self", ",", "item", ")", ":", "if", "item", "in", "_COLLECTABLE_STATE_ATTRIBUTES", ":", "# _collect_state inlined here for performance", "if", "self", ".", "_collect", "and", "_RENDER_INFO", "in", "self", ".", "_hass", ".", "data", ":", "self", ".", "_hass", ".", "data", "[", "_RENDER_INFO", "]", ".", "entities", ".", "add", "(", "self", ".", "_state", ".", "entity_id", ")", "return", "getattr", "(", "self", ".", "_state", ",", "item", ")", "if", "item", "==", "\"entity_id\"", ":", "return", "self", ".", "_state", ".", "entity_id", "if", "item", "==", "\"state_with_unit\"", ":", "return", "self", ".", "state_with_unit", "raise", "KeyError" ]
[ 666, 4 ]
[ 677, 22 ]
python
en
['en', 'en', 'en']
True
TemplateState.entity_id
(self)
Wrap State.entity_id. Intentionally does not collect state
Wrap State.entity_id.
def entity_id(self): """Wrap State.entity_id. Intentionally does not collect state """ return self._state.entity_id
[ "def", "entity_id", "(", "self", ")", ":", "return", "self", ".", "_state", ".", "entity_id" ]
[ 680, 4 ]
[ 685, 36 ]
python
en
['en', 'cy', 'en']
False
TemplateState.state
(self)
Wrap State.state.
Wrap State.state.
def state(self): """Wrap State.state.""" self._collect_state() return self._state.state
[ "def", "state", "(", "self", ")", ":", "self", ".", "_collect_state", "(", ")", "return", "self", ".", "_state", ".", "state" ]
[ 688, 4 ]
[ 691, 32 ]
python
en
['en', 'en', 'en']
False
TemplateState.attributes
(self)
Wrap State.attributes.
Wrap State.attributes.
def attributes(self): """Wrap State.attributes.""" self._collect_state() return self._state.attributes
[ "def", "attributes", "(", "self", ")", ":", "self", ".", "_collect_state", "(", ")", "return", "self", ".", "_state", ".", "attributes" ]
[ 694, 4 ]
[ 697, 37 ]
python
en
['en', 'en', 'en']
False
TemplateState.last_changed
(self)
Wrap State.last_changed.
Wrap State.last_changed.
def last_changed(self): """Wrap State.last_changed.""" self._collect_state() return self._state.last_changed
[ "def", "last_changed", "(", "self", ")", ":", "self", ".", "_collect_state", "(", ")", "return", "self", ".", "_state", ".", "last_changed" ]
[ 700, 4 ]
[ 703, 39 ]
python
en
['en', 'en', 'en']
False
TemplateState.last_updated
(self)
Wrap State.last_updated.
Wrap State.last_updated.
def last_updated(self): """Wrap State.last_updated.""" self._collect_state() return self._state.last_updated
[ "def", "last_updated", "(", "self", ")", ":", "self", ".", "_collect_state", "(", ")", "return", "self", ".", "_state", ".", "last_updated" ]
[ 706, 4 ]
[ 709, 39 ]
python
en
['en', 'en', 'en']
False
TemplateState.context
(self)
Wrap State.context.
Wrap State.context.
def context(self): """Wrap State.context.""" self._collect_state() return self._state.context
[ "def", "context", "(", "self", ")", ":", "self", ".", "_collect_state", "(", ")", "return", "self", ".", "_state", ".", "context" ]
[ 712, 4 ]
[ 715, 34 ]
python
en
['en', 'en', 'en']
False
TemplateState.domain
(self)
Wrap State.domain.
Wrap State.domain.
def domain(self): """Wrap State.domain.""" self._collect_state() return self._state.domain
[ "def", "domain", "(", "self", ")", ":", "self", ".", "_collect_state", "(", ")", "return", "self", ".", "_state", ".", "domain" ]
[ 718, 4 ]
[ 721, 33 ]
python
en
['en', 'en', 'en']
False
TemplateState.object_id
(self)
Wrap State.object_id.
Wrap State.object_id.
def object_id(self): """Wrap State.object_id.""" self._collect_state() return self._state.object_id
[ "def", "object_id", "(", "self", ")", ":", "self", ".", "_collect_state", "(", ")", "return", "self", ".", "_state", ".", "object_id" ]
[ 724, 4 ]
[ 727, 36 ]
python
en
['en', 'en', 'en']
False
TemplateState.name
(self)
Wrap State.name.
Wrap State.name.
def name(self): """Wrap State.name.""" self._collect_state() return self._state.name
[ "def", "name", "(", "self", ")", ":", "self", ".", "_collect_state", "(", ")", "return", "self", ".", "_state", ".", "name" ]
[ 730, 4 ]
[ 733, 31 ]
python
en
['en', 'el-Latn', 'en']
False
TemplateState.state_with_unit
(self)
Return the state concatenated with the unit if available.
Return the state concatenated with the unit if available.
def state_with_unit(self) -> str: """Return the state concatenated with the unit if available.""" self._collect_state() unit = self._state.attributes.get(ATTR_UNIT_OF_MEASUREMENT) return f"{self._state.state} {unit}" if unit else self._state.state
[ "def", "state_with_unit", "(", "self", ")", "->", "str", ":", "self", ".", "_collect_state", "(", ")", "unit", "=", "self", ".", "_state", ".", "attributes", ".", "get", "(", "ATTR_UNIT_OF_MEASUREMENT", ")", "return", "f\"{self._state.state} {unit}\"", "if", "unit", "else", "self", ".", "_state", ".", "state" ]
[ 736, 4 ]
[ 740, 75 ]
python
en
['en', 'en', 'en']
True
TemplateState.__eq__
(self, other: Any)
Ensure we collect on equality check.
Ensure we collect on equality check.
def __eq__(self, other: Any) -> bool: """Ensure we collect on equality check.""" self._collect_state() return self._state.__eq__(other)
[ "def", "__eq__", "(", "self", ",", "other", ":", "Any", ")", "->", "bool", ":", "self", ".", "_collect_state", "(", ")", "return", "self", ".", "_state", ".", "__eq__", "(", "other", ")" ]
[ 742, 4 ]
[ 745, 40 ]
python
en
['en', 'en', 'en']
True
TemplateState.__repr__
(self)
Representation of Template State.
Representation of Template State.
def __repr__(self) -> str: """Representation of Template State.""" return f"<template TemplateState({self._state.__repr__()})>"
[ "def", "__repr__", "(", "self", ")", "->", "str", ":", "return", "f\"<template TemplateState({self._state.__repr__()})>\"" ]
[ 747, 4 ]
[ 749, 68 ]
python
en
['en', 'en', 'en']
True
TemplateEnvironment.__init__
(self, hass)
Initialise template environment.
Initialise template environment.
def __init__(self, hass): """Initialise template environment.""" super().__init__() self.hass = hass self.template_cache = weakref.WeakValueDictionary() self.filters["round"] = forgiving_round self.filters["multiply"] = multiply self.filters["log"] = logarithm self.filters["sin"] = sine self.filters["cos"] = cosine self.filters["tan"] = tangent self.filters["asin"] = arc_sine self.filters["acos"] = arc_cosine self.filters["atan"] = arc_tangent self.filters["atan2"] = arc_tangent2 self.filters["sqrt"] = square_root self.filters["as_timestamp"] = forgiving_as_timestamp self.filters["as_local"] = dt_util.as_local self.filters["timestamp_custom"] = timestamp_custom self.filters["timestamp_local"] = timestamp_local self.filters["timestamp_utc"] = timestamp_utc self.filters["to_json"] = to_json self.filters["from_json"] = from_json self.filters["is_defined"] = fail_when_undefined self.filters["max"] = max self.filters["min"] = min self.filters["random"] = random_every_time self.filters["base64_encode"] = base64_encode self.filters["base64_decode"] = base64_decode self.filters["ordinal"] = ordinal self.filters["regex_match"] = regex_match self.filters["regex_replace"] = regex_replace self.filters["regex_search"] = regex_search self.filters["regex_findall_index"] = regex_findall_index self.filters["bitwise_and"] = bitwise_and self.filters["bitwise_or"] = bitwise_or self.filters["ord"] = ord self.globals["log"] = logarithm self.globals["sin"] = sine self.globals["cos"] = cosine self.globals["tan"] = tangent self.globals["sqrt"] = square_root self.globals["pi"] = math.pi self.globals["tau"] = math.pi * 2 self.globals["e"] = math.e self.globals["asin"] = arc_sine self.globals["acos"] = arc_cosine self.globals["atan"] = arc_tangent self.globals["atan2"] = arc_tangent2 self.globals["float"] = forgiving_float self.globals["as_local"] = dt_util.as_local self.globals["as_timestamp"] = forgiving_as_timestamp self.globals["relative_time"] = relative_time self.globals["timedelta"] = timedelta self.globals["strptime"] = strptime self.globals["urlencode"] = urlencode if hass is None: return # We mark these as a context functions to ensure they get # evaluated fresh with every execution, rather than executed # at compile time and the value stored. The context itself # can be discarded, we only need to get at the hass object. def hassfunction(func): """Wrap function that depend on hass.""" @wraps(func) def wrapper(*args, **kwargs): return func(hass, *args[1:], **kwargs) return contextfunction(wrapper) self.globals["expand"] = hassfunction(expand) self.filters["expand"] = contextfilter(self.globals["expand"]) self.globals["closest"] = hassfunction(closest) self.filters["closest"] = contextfilter(hassfunction(closest_filter)) self.globals["distance"] = hassfunction(distance) self.globals["is_state"] = hassfunction(is_state) self.globals["is_state_attr"] = hassfunction(is_state_attr) self.globals["state_attr"] = hassfunction(state_attr) self.globals["states"] = AllStates(hass) self.globals["utcnow"] = hassfunction(utcnow) self.globals["now"] = hassfunction(now)
[ "def", "__init__", "(", "self", ",", "hass", ")", ":", "super", "(", ")", ".", "__init__", "(", ")", "self", ".", "hass", "=", "hass", "self", ".", "template_cache", "=", "weakref", ".", "WeakValueDictionary", "(", ")", "self", ".", "filters", "[", "\"round\"", "]", "=", "forgiving_round", "self", ".", "filters", "[", "\"multiply\"", "]", "=", "multiply", "self", ".", "filters", "[", "\"log\"", "]", "=", "logarithm", "self", ".", "filters", "[", "\"sin\"", "]", "=", "sine", "self", ".", "filters", "[", "\"cos\"", "]", "=", "cosine", "self", ".", "filters", "[", "\"tan\"", "]", "=", "tangent", "self", ".", "filters", "[", "\"asin\"", "]", "=", "arc_sine", "self", ".", "filters", "[", "\"acos\"", "]", "=", "arc_cosine", "self", ".", "filters", "[", "\"atan\"", "]", "=", "arc_tangent", "self", ".", "filters", "[", "\"atan2\"", "]", "=", "arc_tangent2", "self", ".", "filters", "[", "\"sqrt\"", "]", "=", "square_root", "self", ".", "filters", "[", "\"as_timestamp\"", "]", "=", "forgiving_as_timestamp", "self", ".", "filters", "[", "\"as_local\"", "]", "=", "dt_util", ".", "as_local", "self", ".", "filters", "[", "\"timestamp_custom\"", "]", "=", "timestamp_custom", "self", ".", "filters", "[", "\"timestamp_local\"", "]", "=", "timestamp_local", "self", ".", "filters", "[", "\"timestamp_utc\"", "]", "=", "timestamp_utc", "self", ".", "filters", "[", "\"to_json\"", "]", "=", "to_json", "self", ".", "filters", "[", "\"from_json\"", "]", "=", "from_json", "self", ".", "filters", "[", "\"is_defined\"", "]", "=", "fail_when_undefined", "self", ".", "filters", "[", "\"max\"", "]", "=", "max", "self", ".", "filters", "[", "\"min\"", "]", "=", "min", "self", ".", "filters", "[", "\"random\"", "]", "=", "random_every_time", "self", ".", "filters", "[", "\"base64_encode\"", "]", "=", "base64_encode", "self", ".", "filters", "[", "\"base64_decode\"", "]", "=", "base64_decode", "self", ".", "filters", "[", "\"ordinal\"", "]", "=", "ordinal", "self", ".", "filters", "[", "\"regex_match\"", "]", "=", "regex_match", "self", ".", "filters", "[", "\"regex_replace\"", "]", "=", "regex_replace", "self", ".", "filters", "[", "\"regex_search\"", "]", "=", "regex_search", "self", ".", "filters", "[", "\"regex_findall_index\"", "]", "=", "regex_findall_index", "self", ".", "filters", "[", "\"bitwise_and\"", "]", "=", "bitwise_and", "self", ".", "filters", "[", "\"bitwise_or\"", "]", "=", "bitwise_or", "self", ".", "filters", "[", "\"ord\"", "]", "=", "ord", "self", ".", "globals", "[", "\"log\"", "]", "=", "logarithm", "self", ".", "globals", "[", "\"sin\"", "]", "=", "sine", "self", ".", "globals", "[", "\"cos\"", "]", "=", "cosine", "self", ".", "globals", "[", "\"tan\"", "]", "=", "tangent", "self", ".", "globals", "[", "\"sqrt\"", "]", "=", "square_root", "self", ".", "globals", "[", "\"pi\"", "]", "=", "math", ".", "pi", "self", ".", "globals", "[", "\"tau\"", "]", "=", "math", ".", "pi", "*", "2", "self", ".", "globals", "[", "\"e\"", "]", "=", "math", ".", "e", "self", ".", "globals", "[", "\"asin\"", "]", "=", "arc_sine", "self", ".", "globals", "[", "\"acos\"", "]", "=", "arc_cosine", "self", ".", "globals", "[", "\"atan\"", "]", "=", "arc_tangent", "self", ".", "globals", "[", "\"atan2\"", "]", "=", "arc_tangent2", "self", ".", "globals", "[", "\"float\"", "]", "=", "forgiving_float", "self", ".", "globals", "[", "\"as_local\"", "]", "=", "dt_util", ".", "as_local", "self", ".", "globals", "[", "\"as_timestamp\"", "]", "=", "forgiving_as_timestamp", "self", ".", "globals", "[", "\"relative_time\"", "]", "=", "relative_time", "self", ".", "globals", "[", "\"timedelta\"", "]", "=", "timedelta", "self", ".", "globals", "[", "\"strptime\"", "]", "=", "strptime", "self", ".", "globals", "[", "\"urlencode\"", "]", "=", "urlencode", "if", "hass", "is", "None", ":", "return", "# We mark these as a context functions to ensure they get", "# evaluated fresh with every execution, rather than executed", "# at compile time and the value stored. The context itself", "# can be discarded, we only need to get at the hass object.", "def", "hassfunction", "(", "func", ")", ":", "\"\"\"Wrap function that depend on hass.\"\"\"", "@", "wraps", "(", "func", ")", "def", "wrapper", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "func", "(", "hass", ",", "*", "args", "[", "1", ":", "]", ",", "*", "*", "kwargs", ")", "return", "contextfunction", "(", "wrapper", ")", "self", ".", "globals", "[", "\"expand\"", "]", "=", "hassfunction", "(", "expand", ")", "self", ".", "filters", "[", "\"expand\"", "]", "=", "contextfilter", "(", "self", ".", "globals", "[", "\"expand\"", "]", ")", "self", ".", "globals", "[", "\"closest\"", "]", "=", "hassfunction", "(", "closest", ")", "self", ".", "filters", "[", "\"closest\"", "]", "=", "contextfilter", "(", "hassfunction", "(", "closest_filter", ")", ")", "self", ".", "globals", "[", "\"distance\"", "]", "=", "hassfunction", "(", "distance", ")", "self", ".", "globals", "[", "\"is_state\"", "]", "=", "hassfunction", "(", "is_state", ")", "self", ".", "globals", "[", "\"is_state_attr\"", "]", "=", "hassfunction", "(", "is_state_attr", ")", "self", ".", "globals", "[", "\"state_attr\"", "]", "=", "hassfunction", "(", "state_attr", ")", "self", ".", "globals", "[", "\"states\"", "]", "=", "AllStates", "(", "hass", ")", "self", ".", "globals", "[", "\"utcnow\"", "]", "=", "hassfunction", "(", "utcnow", ")", "self", ".", "globals", "[", "\"now\"", "]", "=", "hassfunction", "(", "now", ")" ]
[ 1294, 4 ]
[ 1376, 47 ]
python
en
['fr', 'en', 'en']
True
TemplateEnvironment.is_safe_callable
(self, obj)
Test if callback is safe.
Test if callback is safe.
def is_safe_callable(self, obj): """Test if callback is safe.""" return isinstance(obj, AllStates) or super().is_safe_callable(obj)
[ "def", "is_safe_callable", "(", "self", ",", "obj", ")", ":", "return", "isinstance", "(", "obj", ",", "AllStates", ")", "or", "super", "(", ")", ".", "is_safe_callable", "(", "obj", ")" ]
[ 1378, 4 ]
[ 1380, 74 ]
python
en
['en', 'en', 'en']
True
TemplateEnvironment.is_safe_attribute
(self, obj, attr, value)
Test if attribute is safe.
Test if attribute is safe.
def is_safe_attribute(self, obj, attr, value): """Test if attribute is safe.""" if isinstance(obj, (AllStates, DomainStates, TemplateState)): return not attr[0] == "_" if isinstance(obj, Namespace): return True return super().is_safe_attribute(obj, attr, value)
[ "def", "is_safe_attribute", "(", "self", ",", "obj", ",", "attr", ",", "value", ")", ":", "if", "isinstance", "(", "obj", ",", "(", "AllStates", ",", "DomainStates", ",", "TemplateState", ")", ")", ":", "return", "not", "attr", "[", "0", "]", "==", "\"_\"", "if", "isinstance", "(", "obj", ",", "Namespace", ")", ":", "return", "True", "return", "super", "(", ")", ".", "is_safe_attribute", "(", "obj", ",", "attr", ",", "value", ")" ]
[ 1382, 4 ]
[ 1390, 58 ]
python
en
['en', 'en', 'en']
True
TemplateEnvironment.compile
(self, source, name=None, filename=None, raw=False, defer_init=False)
Compile the template.
Compile the template.
def compile(self, source, name=None, filename=None, raw=False, defer_init=False): """Compile the template.""" if ( name is not None or filename is not None or raw is not False or defer_init is not False ): # If there are any non-default keywords args, we do # not cache. In prodution we currently do not have # any instance of this. return super().compile(source, name, filename, raw, defer_init) cached = self.template_cache.get(source) if cached is None: cached = self.template_cache[source] = super().compile(source) return cached
[ "def", "compile", "(", "self", ",", "source", ",", "name", "=", "None", ",", "filename", "=", "None", ",", "raw", "=", "False", ",", "defer_init", "=", "False", ")", ":", "if", "(", "name", "is", "not", "None", "or", "filename", "is", "not", "None", "or", "raw", "is", "not", "False", "or", "defer_init", "is", "not", "False", ")", ":", "# If there are any non-default keywords args, we do", "# not cache. In prodution we currently do not have", "# any instance of this.", "return", "super", "(", ")", ".", "compile", "(", "source", ",", "name", ",", "filename", ",", "raw", ",", "defer_init", ")", "cached", "=", "self", ".", "template_cache", ".", "get", "(", "source", ")", "if", "cached", "is", "None", ":", "cached", "=", "self", ".", "template_cache", "[", "source", "]", "=", "super", "(", ")", ".", "compile", "(", "source", ")", "return", "cached" ]
[ 1392, 4 ]
[ 1410, 21 ]
python
en
['en', 'en', 'en']
True
PdartsMutator.drop_paths
(self)
This method is called when a PDARTS epoch is finished. It prepares switches for next epoch. candidate operations with False switch will be doppped in next epoch.
This method is called when a PDARTS epoch is finished. It prepares switches for next epoch. candidate operations with False switch will be doppped in next epoch.
def drop_paths(self): """ This method is called when a PDARTS epoch is finished. It prepares switches for next epoch. candidate operations with False switch will be doppped in next epoch. """ all_switches = copy.deepcopy(self.switches) for key in all_switches: switches = all_switches[key] idxs = [] for j in range(len(switches)): if switches[j]: idxs.append(j) sorted_weights = self.choices[key].data.cpu().numpy()[:-1] drop = np.argsort(sorted_weights)[:self.pdarts_num_to_drop[self.pdarts_epoch_index]] for idx in drop: switches[idxs[idx]] = False return all_switches
[ "def", "drop_paths", "(", "self", ")", ":", "all_switches", "=", "copy", ".", "deepcopy", "(", "self", ".", "switches", ")", "for", "key", "in", "all_switches", ":", "switches", "=", "all_switches", "[", "key", "]", "idxs", "=", "[", "]", "for", "j", "in", "range", "(", "len", "(", "switches", ")", ")", ":", "if", "switches", "[", "j", "]", ":", "idxs", ".", "append", "(", "j", ")", "sorted_weights", "=", "self", ".", "choices", "[", "key", "]", ".", "data", ".", "cpu", "(", ")", ".", "numpy", "(", ")", "[", ":", "-", "1", "]", "drop", "=", "np", ".", "argsort", "(", "sorted_weights", ")", "[", ":", "self", ".", "pdarts_num_to_drop", "[", "self", ".", "pdarts_epoch_index", "]", "]", "for", "idx", "in", "drop", ":", "switches", "[", "idxs", "[", "idx", "]", "]", "=", "False", "return", "all_switches" ]
[ 75, 4 ]
[ 92, 27 ]
python
en
['en', 'error', 'th']
False
test_show_user_form
(hass: HomeAssistantType)
Test that the user set up form is served.
Test that the user set up form is served.
async def test_show_user_form(hass: HomeAssistantType) -> None: """Test that the user set up form is served.""" result = await hass.config_entries.flow.async_init( DOMAIN, context={CONF_SOURCE: SOURCE_USER}, ) assert result["step_id"] == "user" assert result["type"] == RESULT_TYPE_FORM
[ "async", "def", "test_show_user_form", "(", "hass", ":", "HomeAssistantType", ")", "->", "None", ":", "result", "=", "await", "hass", ".", "config_entries", ".", "flow", ".", "async_init", "(", "DOMAIN", ",", "context", "=", "{", "CONF_SOURCE", ":", "SOURCE_USER", "}", ",", ")", "assert", "result", "[", "\"step_id\"", "]", "==", "\"user\"", "assert", "result", "[", "\"type\"", "]", "==", "RESULT_TYPE_FORM" ]
[ 27, 0 ]
[ 35, 45 ]
python
en
['en', 'en', 'en']
True
test_show_ssdp_form
( hass: HomeAssistantType, aioclient_mock: AiohttpClientMocker )
Test that the ssdp confirmation form is served.
Test that the ssdp confirmation form is served.
async def test_show_ssdp_form( hass: HomeAssistantType, aioclient_mock: AiohttpClientMocker ) -> None: """Test that the ssdp confirmation form is served.""" mock_connection(aioclient_mock) discovery_info = MOCK_SSDP_DISCOVERY_INFO.copy() result = await hass.config_entries.flow.async_init( DOMAIN, context={CONF_SOURCE: SOURCE_SSDP}, data=discovery_info ) assert result["type"] == RESULT_TYPE_FORM assert result["step_id"] == "ssdp_confirm" assert result["description_placeholders"] == {CONF_NAME: HOST}
[ "async", "def", "test_show_ssdp_form", "(", "hass", ":", "HomeAssistantType", ",", "aioclient_mock", ":", "AiohttpClientMocker", ")", "->", "None", ":", "mock_connection", "(", "aioclient_mock", ")", "discovery_info", "=", "MOCK_SSDP_DISCOVERY_INFO", ".", "copy", "(", ")", "result", "=", "await", "hass", ".", "config_entries", ".", "flow", ".", "async_init", "(", "DOMAIN", ",", "context", "=", "{", "CONF_SOURCE", ":", "SOURCE_SSDP", "}", ",", "data", "=", "discovery_info", ")", "assert", "result", "[", "\"type\"", "]", "==", "RESULT_TYPE_FORM", "assert", "result", "[", "\"step_id\"", "]", "==", "\"ssdp_confirm\"", "assert", "result", "[", "\"description_placeholders\"", "]", "==", "{", "CONF_NAME", ":", "HOST", "}" ]
[ 38, 0 ]
[ 51, 66 ]
python
en
['en', 'en', 'en']
True
test_cannot_connect
( hass: HomeAssistantType, aioclient_mock: AiohttpClientMocker )
Test we show user form on connection error.
Test we show user form on connection error.
async def test_cannot_connect( hass: HomeAssistantType, aioclient_mock: AiohttpClientMocker ) -> None: """Test we show user form on connection error.""" aioclient_mock.get("http://127.0.0.1:8080/info/getVersion", exc=HTTPClientError) user_input = MOCK_USER_INPUT.copy() result = await hass.config_entries.flow.async_init( DOMAIN, context={CONF_SOURCE: SOURCE_USER}, data=user_input, ) assert result["type"] == RESULT_TYPE_FORM assert result["step_id"] == "user" assert result["errors"] == {"base": "cannot_connect"}
[ "async", "def", "test_cannot_connect", "(", "hass", ":", "HomeAssistantType", ",", "aioclient_mock", ":", "AiohttpClientMocker", ")", "->", "None", ":", "aioclient_mock", ".", "get", "(", "\"http://127.0.0.1:8080/info/getVersion\"", ",", "exc", "=", "HTTPClientError", ")", "user_input", "=", "MOCK_USER_INPUT", ".", "copy", "(", ")", "result", "=", "await", "hass", ".", "config_entries", ".", "flow", ".", "async_init", "(", "DOMAIN", ",", "context", "=", "{", "CONF_SOURCE", ":", "SOURCE_USER", "}", ",", "data", "=", "user_input", ",", ")", "assert", "result", "[", "\"type\"", "]", "==", "RESULT_TYPE_FORM", "assert", "result", "[", "\"step_id\"", "]", "==", "\"user\"", "assert", "result", "[", "\"errors\"", "]", "==", "{", "\"base\"", ":", "\"cannot_connect\"", "}" ]
[ 54, 0 ]
[ 69, 57 ]
python
en
['en', 'en', 'en']
True
test_ssdp_cannot_connect
( hass: HomeAssistantType, aioclient_mock: AiohttpClientMocker )
Test we abort SSDP flow on connection error.
Test we abort SSDP flow on connection error.
async def test_ssdp_cannot_connect( hass: HomeAssistantType, aioclient_mock: AiohttpClientMocker ) -> None: """Test we abort SSDP flow on connection error.""" aioclient_mock.get("http://127.0.0.1:8080/info/getVersion", exc=HTTPClientError) discovery_info = MOCK_SSDP_DISCOVERY_INFO.copy() result = await hass.config_entries.flow.async_init( DOMAIN, context={CONF_SOURCE: SOURCE_SSDP}, data=discovery_info, ) assert result["type"] == RESULT_TYPE_ABORT assert result["reason"] == "cannot_connect"
[ "async", "def", "test_ssdp_cannot_connect", "(", "hass", ":", "HomeAssistantType", ",", "aioclient_mock", ":", "AiohttpClientMocker", ")", "->", "None", ":", "aioclient_mock", ".", "get", "(", "\"http://127.0.0.1:8080/info/getVersion\"", ",", "exc", "=", "HTTPClientError", ")", "discovery_info", "=", "MOCK_SSDP_DISCOVERY_INFO", ".", "copy", "(", ")", "result", "=", "await", "hass", ".", "config_entries", ".", "flow", ".", "async_init", "(", "DOMAIN", ",", "context", "=", "{", "CONF_SOURCE", ":", "SOURCE_SSDP", "}", ",", "data", "=", "discovery_info", ",", ")", "assert", "result", "[", "\"type\"", "]", "==", "RESULT_TYPE_ABORT", "assert", "result", "[", "\"reason\"", "]", "==", "\"cannot_connect\"" ]
[ 72, 0 ]
[ 86, 47 ]
python
en
['en', 'de', 'en']
True
test_ssdp_confirm_cannot_connect
( hass: HomeAssistantType, aioclient_mock: AiohttpClientMocker )
Test we abort SSDP flow on connection error.
Test we abort SSDP flow on connection error.
async def test_ssdp_confirm_cannot_connect( hass: HomeAssistantType, aioclient_mock: AiohttpClientMocker ) -> None: """Test we abort SSDP flow on connection error.""" aioclient_mock.get("http://127.0.0.1:8080/info/getVersion", exc=HTTPClientError) discovery_info = MOCK_SSDP_DISCOVERY_INFO.copy() result = await hass.config_entries.flow.async_init( DOMAIN, context={CONF_SOURCE: SOURCE_SSDP, CONF_HOST: HOST, CONF_NAME: HOST}, data=discovery_info, ) assert result["type"] == RESULT_TYPE_ABORT assert result["reason"] == "cannot_connect"
[ "async", "def", "test_ssdp_confirm_cannot_connect", "(", "hass", ":", "HomeAssistantType", ",", "aioclient_mock", ":", "AiohttpClientMocker", ")", "->", "None", ":", "aioclient_mock", ".", "get", "(", "\"http://127.0.0.1:8080/info/getVersion\"", ",", "exc", "=", "HTTPClientError", ")", "discovery_info", "=", "MOCK_SSDP_DISCOVERY_INFO", ".", "copy", "(", ")", "result", "=", "await", "hass", ".", "config_entries", ".", "flow", ".", "async_init", "(", "DOMAIN", ",", "context", "=", "{", "CONF_SOURCE", ":", "SOURCE_SSDP", ",", "CONF_HOST", ":", "HOST", ",", "CONF_NAME", ":", "HOST", "}", ",", "data", "=", "discovery_info", ",", ")", "assert", "result", "[", "\"type\"", "]", "==", "RESULT_TYPE_ABORT", "assert", "result", "[", "\"reason\"", "]", "==", "\"cannot_connect\"" ]
[ 89, 0 ]
[ 103, 47 ]
python
en
['en', 'de', 'en']
True
test_user_device_exists_abort
( hass: HomeAssistantType, aioclient_mock: AiohttpClientMocker )
Test we abort user flow if DirecTV receiver already configured.
Test we abort user flow if DirecTV receiver already configured.
async def test_user_device_exists_abort( hass: HomeAssistantType, aioclient_mock: AiohttpClientMocker ) -> None: """Test we abort user flow if DirecTV receiver already configured.""" await setup_integration(hass, aioclient_mock, skip_entry_setup=True) user_input = MOCK_USER_INPUT.copy() result = await hass.config_entries.flow.async_init( DOMAIN, context={CONF_SOURCE: SOURCE_USER}, data=user_input, ) assert result["type"] == RESULT_TYPE_ABORT assert result["reason"] == "already_configured"
[ "async", "def", "test_user_device_exists_abort", "(", "hass", ":", "HomeAssistantType", ",", "aioclient_mock", ":", "AiohttpClientMocker", ")", "->", "None", ":", "await", "setup_integration", "(", "hass", ",", "aioclient_mock", ",", "skip_entry_setup", "=", "True", ")", "user_input", "=", "MOCK_USER_INPUT", ".", "copy", "(", ")", "result", "=", "await", "hass", ".", "config_entries", ".", "flow", ".", "async_init", "(", "DOMAIN", ",", "context", "=", "{", "CONF_SOURCE", ":", "SOURCE_USER", "}", ",", "data", "=", "user_input", ",", ")", "assert", "result", "[", "\"type\"", "]", "==", "RESULT_TYPE_ABORT", "assert", "result", "[", "\"reason\"", "]", "==", "\"already_configured\"" ]
[ 106, 0 ]
[ 120, 51 ]
python
en
['en', 'de', 'en']
True
test_ssdp_device_exists_abort
( hass: HomeAssistantType, aioclient_mock: AiohttpClientMocker )
Test we abort SSDP flow if DirecTV receiver already configured.
Test we abort SSDP flow if DirecTV receiver already configured.
async def test_ssdp_device_exists_abort( hass: HomeAssistantType, aioclient_mock: AiohttpClientMocker ) -> None: """Test we abort SSDP flow if DirecTV receiver already configured.""" await setup_integration(hass, aioclient_mock, skip_entry_setup=True) discovery_info = MOCK_SSDP_DISCOVERY_INFO.copy() result = await hass.config_entries.flow.async_init( DOMAIN, context={CONF_SOURCE: SOURCE_SSDP}, data=discovery_info, ) assert result["type"] == RESULT_TYPE_ABORT assert result["reason"] == "already_configured"
[ "async", "def", "test_ssdp_device_exists_abort", "(", "hass", ":", "HomeAssistantType", ",", "aioclient_mock", ":", "AiohttpClientMocker", ")", "->", "None", ":", "await", "setup_integration", "(", "hass", ",", "aioclient_mock", ",", "skip_entry_setup", "=", "True", ")", "discovery_info", "=", "MOCK_SSDP_DISCOVERY_INFO", ".", "copy", "(", ")", "result", "=", "await", "hass", ".", "config_entries", ".", "flow", ".", "async_init", "(", "DOMAIN", ",", "context", "=", "{", "CONF_SOURCE", ":", "SOURCE_SSDP", "}", ",", "data", "=", "discovery_info", ",", ")", "assert", "result", "[", "\"type\"", "]", "==", "RESULT_TYPE_ABORT", "assert", "result", "[", "\"reason\"", "]", "==", "\"already_configured\"" ]
[ 123, 0 ]
[ 137, 51 ]
python
en
['en', 'de', 'en']
True