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 |
---|---|---|---|---|---|---|---|---|---|---|---|
preprocess_random_forest | (dataset, log) |
For random forest:
- Do nothing for numerical features except null imputation.
- For categorical features, use ordinal encoding to map them into integers.
|
For random forest:
- Do nothing for numerical features except null imputation.
- For categorical features, use ordinal encoding to map them into integers.
| def preprocess_random_forest(dataset, log):
'''
For random forest:
- Do nothing for numerical features except null imputation.
- For categorical features, use ordinal encoding to map them into integers.
'''
cat_columns, num_columns = [], []
shift_amount = 0
for i, f in enumerate(dataset.features):
if f.is_target:
shift_amount += 1
continue
elif f.is_categorical():
cat_columns.append(i - shift_amount)
else:
num_columns.append(i - shift_amount)
cat_pipeline = Pipeline([('imputer', SimpleImputer(strategy='most_frequent')),
('ordinal_encoder', OrdinalEncoder()),
])
num_pipeline = Pipeline([('imputer', SimpleImputer(strategy='mean')),
])
data_pipeline = ColumnTransformer([
('categorical', cat_pipeline, cat_columns),
('numerical', num_pipeline, num_columns),
])
data_pipeline.fit(np.concatenate([dataset.train.X, dataset.test.X], axis=0))
X_train = data_pipeline.transform(dataset.train.X)
X_test = data_pipeline.transform(dataset.test.X)
return X_train, X_test | [
"def",
"preprocess_random_forest",
"(",
"dataset",
",",
"log",
")",
":",
"cat_columns",
",",
"num_columns",
"=",
"[",
"]",
",",
"[",
"]",
"shift_amount",
"=",
"0",
"for",
"i",
",",
"f",
"in",
"enumerate",
"(",
"dataset",
".",
"features",
")",
":",
"if",
"f",
".",
"is_target",
":",
"shift_amount",
"+=",
"1",
"continue",
"elif",
"f",
".",
"is_categorical",
"(",
")",
":",
"cat_columns",
".",
"append",
"(",
"i",
"-",
"shift_amount",
")",
"else",
":",
"num_columns",
".",
"append",
"(",
"i",
"-",
"shift_amount",
")",
"cat_pipeline",
"=",
"Pipeline",
"(",
"[",
"(",
"'imputer'",
",",
"SimpleImputer",
"(",
"strategy",
"=",
"'most_frequent'",
")",
")",
",",
"(",
"'ordinal_encoder'",
",",
"OrdinalEncoder",
"(",
")",
")",
",",
"]",
")",
"num_pipeline",
"=",
"Pipeline",
"(",
"[",
"(",
"'imputer'",
",",
"SimpleImputer",
"(",
"strategy",
"=",
"'mean'",
")",
")",
",",
"]",
")",
"data_pipeline",
"=",
"ColumnTransformer",
"(",
"[",
"(",
"'categorical'",
",",
"cat_pipeline",
",",
"cat_columns",
")",
",",
"(",
"'numerical'",
",",
"num_pipeline",
",",
"num_columns",
")",
",",
"]",
")",
"data_pipeline",
".",
"fit",
"(",
"np",
".",
"concatenate",
"(",
"[",
"dataset",
".",
"train",
".",
"X",
",",
"dataset",
".",
"test",
".",
"X",
"]",
",",
"axis",
"=",
"0",
")",
")",
"X_train",
"=",
"data_pipeline",
".",
"transform",
"(",
"dataset",
".",
"train",
".",
"X",
")",
"X_test",
"=",
"data_pipeline",
".",
"transform",
"(",
"dataset",
".",
"test",
".",
"X",
")",
"return",
"X_train",
",",
"X_test"
] | [
47,
0
] | [
81,
26
] | python | en | ['en', 'error', 'th'] | False |
run_random_forest | (dataset, config, tuner, log) |
Using the given tuner, tune a random forest within the given time constraint.
This function uses cross validation score as the feedback score to the tuner.
The search space on which tuners search on is defined above empirically as a global variable.
|
Using the given tuner, tune a random forest within the given time constraint.
This function uses cross validation score as the feedback score to the tuner.
The search space on which tuners search on is defined above empirically as a global variable.
| def run_random_forest(dataset, config, tuner, log):
"""
Using the given tuner, tune a random forest within the given time constraint.
This function uses cross validation score as the feedback score to the tuner.
The search space on which tuners search on is defined above empirically as a global variable.
"""
limit_type, trial_limit = config.framework_params['limit_type'], None
if limit_type == 'ntrials':
trial_limit = int(config.framework_params['trial_limit'])
X_train, X_test = preprocess_random_forest(dataset, log)
y_train, y_test = dataset.train.y, dataset.test.y
is_classification = config.type == 'classification'
estimator = RandomForestClassifier if is_classification else RandomForestRegressor
best_score, best_params, best_model = None, None, None
score_higher_better = True
tuner.update_search_space(SEARCH_SPACE)
start_time = time.time()
trial_count = 0
intermediate_scores = []
intermediate_best_scores = [] # should be monotonically increasing
while True:
try:
trial_count += 1
param_idx, cur_params = tuner.generate_parameters()
train_params = cur_params.copy()
if 'TRIAL_BUDGET' in cur_params:
train_params.pop('TRIAL_BUDGET')
if cur_params['max_leaf_nodes'] == 0:
train_params.pop('max_leaf_nodes')
if cur_params['max_depth'] == 0:
train_params.pop('max_depth')
log.info("Trial {}: \n{}\n".format(param_idx, cur_params))
cur_model = estimator(random_state=config.seed, **train_params)
# Here score is the output of score() from the estimator
cur_score = cross_val_score(cur_model, X_train, y_train)
cur_score = sum(cur_score) / float(len(cur_score))
if np.isnan(cur_score):
cur_score = 0
log.info("Score: {}\n".format(cur_score))
if best_score is None or (score_higher_better and cur_score > best_score) or (not score_higher_better and cur_score < best_score):
best_score, best_params, best_model = cur_score, cur_params, cur_model
intermediate_scores.append(cur_score)
intermediate_best_scores.append(best_score)
tuner.receive_trial_result(param_idx, cur_params, cur_score)
if limit_type == 'time':
current_time = time.time()
elapsed_time = current_time - start_time
if elapsed_time >= config.max_runtime_seconds:
break
elif limit_type == 'ntrials':
if trial_count >= trial_limit:
break
except:
break
# This line is required to fully terminate some advisors
tuner.handle_terminate()
log.info("Tuning done, the best parameters are:\n{}\n".format(best_params))
# retrain on the whole dataset
with Timer() as training:
best_model.fit(X_train, y_train)
predictions = best_model.predict(X_test)
probabilities = best_model.predict_proba(X_test) if is_classification else None
return probabilities, predictions, training, y_test, intermediate_scores, intermediate_best_scores | [
"def",
"run_random_forest",
"(",
"dataset",
",",
"config",
",",
"tuner",
",",
"log",
")",
":",
"limit_type",
",",
"trial_limit",
"=",
"config",
".",
"framework_params",
"[",
"'limit_type'",
"]",
",",
"None",
"if",
"limit_type",
"==",
"'ntrials'",
":",
"trial_limit",
"=",
"int",
"(",
"config",
".",
"framework_params",
"[",
"'trial_limit'",
"]",
")",
"X_train",
",",
"X_test",
"=",
"preprocess_random_forest",
"(",
"dataset",
",",
"log",
")",
"y_train",
",",
"y_test",
"=",
"dataset",
".",
"train",
".",
"y",
",",
"dataset",
".",
"test",
".",
"y",
"is_classification",
"=",
"config",
".",
"type",
"==",
"'classification'",
"estimator",
"=",
"RandomForestClassifier",
"if",
"is_classification",
"else",
"RandomForestRegressor",
"best_score",
",",
"best_params",
",",
"best_model",
"=",
"None",
",",
"None",
",",
"None",
"score_higher_better",
"=",
"True",
"tuner",
".",
"update_search_space",
"(",
"SEARCH_SPACE",
")",
"start_time",
"=",
"time",
".",
"time",
"(",
")",
"trial_count",
"=",
"0",
"intermediate_scores",
"=",
"[",
"]",
"intermediate_best_scores",
"=",
"[",
"]",
"# should be monotonically increasing ",
"while",
"True",
":",
"try",
":",
"trial_count",
"+=",
"1",
"param_idx",
",",
"cur_params",
"=",
"tuner",
".",
"generate_parameters",
"(",
")",
"train_params",
"=",
"cur_params",
".",
"copy",
"(",
")",
"if",
"'TRIAL_BUDGET'",
"in",
"cur_params",
":",
"train_params",
".",
"pop",
"(",
"'TRIAL_BUDGET'",
")",
"if",
"cur_params",
"[",
"'max_leaf_nodes'",
"]",
"==",
"0",
":",
"train_params",
".",
"pop",
"(",
"'max_leaf_nodes'",
")",
"if",
"cur_params",
"[",
"'max_depth'",
"]",
"==",
"0",
":",
"train_params",
".",
"pop",
"(",
"'max_depth'",
")",
"log",
".",
"info",
"(",
"\"Trial {}: \\n{}\\n\"",
".",
"format",
"(",
"param_idx",
",",
"cur_params",
")",
")",
"cur_model",
"=",
"estimator",
"(",
"random_state",
"=",
"config",
".",
"seed",
",",
"*",
"*",
"train_params",
")",
"# Here score is the output of score() from the estimator",
"cur_score",
"=",
"cross_val_score",
"(",
"cur_model",
",",
"X_train",
",",
"y_train",
")",
"cur_score",
"=",
"sum",
"(",
"cur_score",
")",
"/",
"float",
"(",
"len",
"(",
"cur_score",
")",
")",
"if",
"np",
".",
"isnan",
"(",
"cur_score",
")",
":",
"cur_score",
"=",
"0",
"log",
".",
"info",
"(",
"\"Score: {}\\n\"",
".",
"format",
"(",
"cur_score",
")",
")",
"if",
"best_score",
"is",
"None",
"or",
"(",
"score_higher_better",
"and",
"cur_score",
">",
"best_score",
")",
"or",
"(",
"not",
"score_higher_better",
"and",
"cur_score",
"<",
"best_score",
")",
":",
"best_score",
",",
"best_params",
",",
"best_model",
"=",
"cur_score",
",",
"cur_params",
",",
"cur_model",
"intermediate_scores",
".",
"append",
"(",
"cur_score",
")",
"intermediate_best_scores",
".",
"append",
"(",
"best_score",
")",
"tuner",
".",
"receive_trial_result",
"(",
"param_idx",
",",
"cur_params",
",",
"cur_score",
")",
"if",
"limit_type",
"==",
"'time'",
":",
"current_time",
"=",
"time",
".",
"time",
"(",
")",
"elapsed_time",
"=",
"current_time",
"-",
"start_time",
"if",
"elapsed_time",
">=",
"config",
".",
"max_runtime_seconds",
":",
"break",
"elif",
"limit_type",
"==",
"'ntrials'",
":",
"if",
"trial_count",
">=",
"trial_limit",
":",
"break",
"except",
":",
"break",
"# This line is required to fully terminate some advisors",
"tuner",
".",
"handle_terminate",
"(",
")",
"log",
".",
"info",
"(",
"\"Tuning done, the best parameters are:\\n{}\\n\"",
".",
"format",
"(",
"best_params",
")",
")",
"# retrain on the whole dataset ",
"with",
"Timer",
"(",
")",
"as",
"training",
":",
"best_model",
".",
"fit",
"(",
"X_train",
",",
"y_train",
")",
"predictions",
"=",
"best_model",
".",
"predict",
"(",
"X_test",
")",
"probabilities",
"=",
"best_model",
".",
"predict_proba",
"(",
"X_test",
")",
"if",
"is_classification",
"else",
"None",
"return",
"probabilities",
",",
"predictions",
",",
"training",
",",
"y_test",
",",
"intermediate_scores",
",",
"intermediate_best_scores"
] | [
84,
0
] | [
162,
102
] | python | en | ['en', 'error', 'th'] | False |
async_setup_entry | (
hass: HomeAssistantType, entry: ConfigType, async_add_entities
) | Set up the Met Office weather sensor platform. | Set up the Met Office weather sensor platform. | async def async_setup_entry(
hass: HomeAssistantType, entry: ConfigType, async_add_entities
) -> None:
"""Set up the Met Office weather sensor platform."""
hass_data = hass.data[DOMAIN][entry.entry_id]
async_add_entities(
[
MetOfficeWeather(
entry.data,
hass_data,
)
],
False,
) | [
"async",
"def",
"async_setup_entry",
"(",
"hass",
":",
"HomeAssistantType",
",",
"entry",
":",
"ConfigType",
",",
"async_add_entities",
")",
"->",
"None",
":",
"hass_data",
"=",
"hass",
".",
"data",
"[",
"DOMAIN",
"]",
"[",
"entry",
".",
"entry_id",
"]",
"async_add_entities",
"(",
"[",
"MetOfficeWeather",
"(",
"entry",
".",
"data",
",",
"hass_data",
",",
")",
"]",
",",
"False",
",",
")"
] | [
19,
0
] | [
33,
5
] | python | en | ['en', 'da', 'en'] | True |
MetOfficeWeather.__init__ | (self, entry_data, hass_data) | Initialise the platform with a data instance. | Initialise the platform with a data instance. | def __init__(self, entry_data, hass_data):
"""Initialise the platform with a data instance."""
self._data = hass_data[METOFFICE_DATA]
self._coordinator = hass_data[METOFFICE_COORDINATOR]
self._name = f"{DEFAULT_NAME} {hass_data[METOFFICE_NAME]}"
self._unique_id = f"{self._data.latitude}_{self._data.longitude}"
self.metoffice_now = None | [
"def",
"__init__",
"(",
"self",
",",
"entry_data",
",",
"hass_data",
")",
":",
"self",
".",
"_data",
"=",
"hass_data",
"[",
"METOFFICE_DATA",
"]",
"self",
".",
"_coordinator",
"=",
"hass_data",
"[",
"METOFFICE_COORDINATOR",
"]",
"self",
".",
"_name",
"=",
"f\"{DEFAULT_NAME} {hass_data[METOFFICE_NAME]}\"",
"self",
".",
"_unique_id",
"=",
"f\"{self._data.latitude}_{self._data.longitude}\"",
"self",
".",
"metoffice_now",
"=",
"None"
] | [
39,
4
] | [
47,
33
] | python | en | ['en', 'en', 'en'] | True |
MetOfficeWeather.name | (self) | Return the name of the sensor. | Return the name of the sensor. | def name(self):
"""Return the name of the sensor."""
return self._name | [
"def",
"name",
"(",
"self",
")",
":",
"return",
"self",
".",
"_name"
] | [
50,
4
] | [
52,
25
] | python | en | ['en', 'mi', 'en'] | True |
MetOfficeWeather.unique_id | (self) | Return the unique of the sensor. | Return the unique of the sensor. | def unique_id(self):
"""Return the unique of the sensor."""
return self._unique_id | [
"def",
"unique_id",
"(",
"self",
")",
":",
"return",
"self",
".",
"_unique_id"
] | [
55,
4
] | [
57,
30
] | python | en | ['en', 'la', 'en'] | True |
MetOfficeWeather.condition | (self) | Return the current condition. | Return the current condition. | def condition(self):
"""Return the current condition."""
return (
[
k
for k, v in CONDITION_CLASSES.items()
if self.metoffice_now.weather.value in v
][0]
if self.metoffice_now
else None
) | [
"def",
"condition",
"(",
"self",
")",
":",
"return",
"(",
"[",
"k",
"for",
"k",
",",
"v",
"in",
"CONDITION_CLASSES",
".",
"items",
"(",
")",
"if",
"self",
".",
"metoffice_now",
".",
"weather",
".",
"value",
"in",
"v",
"]",
"[",
"0",
"]",
"if",
"self",
".",
"metoffice_now",
"else",
"None",
")"
] | [
60,
4
] | [
70,
9
] | python | en | ['en', 'en', 'en'] | True |
MetOfficeWeather.temperature | (self) | Return the platform temperature. | Return the platform temperature. | def temperature(self):
"""Return the platform temperature."""
return (
self.metoffice_now.temperature.value
if self.metoffice_now and self.metoffice_now.temperature
else None
) | [
"def",
"temperature",
"(",
"self",
")",
":",
"return",
"(",
"self",
".",
"metoffice_now",
".",
"temperature",
".",
"value",
"if",
"self",
".",
"metoffice_now",
"and",
"self",
".",
"metoffice_now",
".",
"temperature",
"else",
"None",
")"
] | [
73,
4
] | [
79,
9
] | python | en | ['en', 'la', 'en'] | True |
MetOfficeWeather.temperature_unit | (self) | Return the unit of measurement. | Return the unit of measurement. | def temperature_unit(self):
"""Return the unit of measurement."""
return TEMP_CELSIUS | [
"def",
"temperature_unit",
"(",
"self",
")",
":",
"return",
"TEMP_CELSIUS"
] | [
82,
4
] | [
84,
27
] | python | en | ['en', 'la', 'en'] | True |
MetOfficeWeather.visibility | (self) | Return the platform visibility. | Return the platform visibility. | def visibility(self):
"""Return the platform visibility."""
_visibility = None
if hasattr(self.metoffice_now, "visibility"):
_visibility = f"{VISIBILITY_CLASSES.get(self.metoffice_now.visibility.value)} - {VISIBILITY_DISTANCE_CLASSES.get(self.metoffice_now.visibility.value)}"
return _visibility | [
"def",
"visibility",
"(",
"self",
")",
":",
"_visibility",
"=",
"None",
"if",
"hasattr",
"(",
"self",
".",
"metoffice_now",
",",
"\"visibility\"",
")",
":",
"_visibility",
"=",
"f\"{VISIBILITY_CLASSES.get(self.metoffice_now.visibility.value)} - {VISIBILITY_DISTANCE_CLASSES.get(self.metoffice_now.visibility.value)}\"",
"return",
"_visibility"
] | [
87,
4
] | [
92,
26
] | python | en | ['en', 'hi-Latn', 'en'] | True |
MetOfficeWeather.visibility_unit | (self) | Return the unit of measurement. | Return the unit of measurement. | def visibility_unit(self):
"""Return the unit of measurement."""
return LENGTH_KILOMETERS | [
"def",
"visibility_unit",
"(",
"self",
")",
":",
"return",
"LENGTH_KILOMETERS"
] | [
95,
4
] | [
97,
32
] | python | en | ['en', 'la', 'en'] | True |
MetOfficeWeather.pressure | (self) | Return the mean sea-level pressure. | Return the mean sea-level pressure. | def pressure(self):
"""Return the mean sea-level pressure."""
return (
self.metoffice_now.pressure.value
if self.metoffice_now and self.metoffice_now.pressure
else None
) | [
"def",
"pressure",
"(",
"self",
")",
":",
"return",
"(",
"self",
".",
"metoffice_now",
".",
"pressure",
".",
"value",
"if",
"self",
".",
"metoffice_now",
"and",
"self",
".",
"metoffice_now",
".",
"pressure",
"else",
"None",
")"
] | [
100,
4
] | [
106,
9
] | python | en | ['en', 'it', 'en'] | True |
MetOfficeWeather.humidity | (self) | Return the relative humidity. | Return the relative humidity. | def humidity(self):
"""Return the relative humidity."""
return (
self.metoffice_now.humidity.value
if self.metoffice_now and self.metoffice_now.humidity
else None
) | [
"def",
"humidity",
"(",
"self",
")",
":",
"return",
"(",
"self",
".",
"metoffice_now",
".",
"humidity",
".",
"value",
"if",
"self",
".",
"metoffice_now",
"and",
"self",
".",
"metoffice_now",
".",
"humidity",
"else",
"None",
")"
] | [
109,
4
] | [
115,
9
] | python | en | ['en', 'en', 'en'] | True |
MetOfficeWeather.wind_speed | (self) | Return the wind speed. | Return the wind speed. | def wind_speed(self):
"""Return the wind speed."""
return (
self.metoffice_now.wind_speed.value
if self.metoffice_now and self.metoffice_now.wind_speed
else None
) | [
"def",
"wind_speed",
"(",
"self",
")",
":",
"return",
"(",
"self",
".",
"metoffice_now",
".",
"wind_speed",
".",
"value",
"if",
"self",
".",
"metoffice_now",
"and",
"self",
".",
"metoffice_now",
".",
"wind_speed",
"else",
"None",
")"
] | [
118,
4
] | [
124,
9
] | python | en | ['en', 'zh', 'en'] | True |
MetOfficeWeather.wind_bearing | (self) | Return the wind bearing. | Return the wind bearing. | def wind_bearing(self):
"""Return the wind bearing."""
return (
self.metoffice_now.wind_direction.value
if self.metoffice_now and self.metoffice_now.wind_direction
else None
) | [
"def",
"wind_bearing",
"(",
"self",
")",
":",
"return",
"(",
"self",
".",
"metoffice_now",
".",
"wind_direction",
".",
"value",
"if",
"self",
".",
"metoffice_now",
"and",
"self",
".",
"metoffice_now",
".",
"wind_direction",
"else",
"None",
")"
] | [
127,
4
] | [
133,
9
] | python | en | ['en', 'ig', 'en'] | True |
MetOfficeWeather.attribution | (self) | Return the attribution. | Return the attribution. | def attribution(self):
"""Return the attribution."""
return ATTRIBUTION | [
"def",
"attribution",
"(",
"self",
")",
":",
"return",
"ATTRIBUTION"
] | [
136,
4
] | [
138,
26
] | python | en | ['en', 'ja', 'en'] | True |
MetOfficeWeather.async_added_to_hass | (self) | Set up a listener and load data. | Set up a listener and load data. | async def async_added_to_hass(self) -> None:
"""Set up a listener and load data."""
self.async_on_remove(
self._coordinator.async_add_listener(self._update_callback)
)
self._update_callback() | [
"async",
"def",
"async_added_to_hass",
"(",
"self",
")",
"->",
"None",
":",
"self",
".",
"async_on_remove",
"(",
"self",
".",
"_coordinator",
".",
"async_add_listener",
"(",
"self",
".",
"_update_callback",
")",
")",
"self",
".",
"_update_callback",
"(",
")"
] | [
140,
4
] | [
145,
31
] | python | en | ['en', 'en', 'en'] | True |
MetOfficeWeather._update_callback | (self) | Load data from integration. | Load data from integration. | def _update_callback(self) -> None:
"""Load data from integration."""
self.metoffice_now = self._data.now
self.async_write_ha_state() | [
"def",
"_update_callback",
"(",
"self",
")",
"->",
"None",
":",
"self",
".",
"metoffice_now",
"=",
"self",
".",
"_data",
".",
"now",
"self",
".",
"async_write_ha_state",
"(",
")"
] | [
148,
4
] | [
151,
35
] | python | en | ['en', 'en', 'en'] | True |
MetOfficeWeather.should_poll | (self) | Entities do not individually poll. | Entities do not individually poll. | def should_poll(self) -> bool:
"""Entities do not individually poll."""
return False | [
"def",
"should_poll",
"(",
"self",
")",
"->",
"bool",
":",
"return",
"False"
] | [
154,
4
] | [
156,
20
] | python | en | ['en', 'en', 'en'] | True |
MetOfficeWeather.available | (self) | Return if state is available. | Return if state is available. | def available(self):
"""Return if state is available."""
return self.metoffice_now is not None | [
"def",
"available",
"(",
"self",
")",
":",
"return",
"self",
".",
"metoffice_now",
"is",
"not",
"None"
] | [
159,
4
] | [
161,
45
] | python | en | ['en', 'en', 'en'] | True |
request_handler_factory | (view: HomeAssistantView, handler: Callable) | Wrap the handler classes. | Wrap the handler classes. | def request_handler_factory(view: HomeAssistantView, handler: Callable) -> Callable:
"""Wrap the handler classes."""
assert asyncio.iscoroutinefunction(handler) or is_callback(
handler
), "Handler should be a coroutine or a callback."
async def handle(request: web.Request) -> web.StreamResponse:
"""Handle incoming request."""
if request.app[KEY_HASS].is_stopping:
return web.Response(status=HTTP_SERVICE_UNAVAILABLE)
authenticated = request.get(KEY_AUTHENTICATED, False)
if view.requires_auth and not authenticated:
raise HTTPUnauthorized()
_LOGGER.debug(
"Serving %s to %s (auth: %s)",
request.path,
request.remote,
authenticated,
)
try:
result = handler(request, **request.match_info)
if asyncio.iscoroutine(result):
result = await result
except vol.Invalid as err:
raise HTTPBadRequest() from err
except exceptions.ServiceNotFound as err:
raise HTTPInternalServerError() from err
except exceptions.Unauthorized as err:
raise HTTPUnauthorized() from err
if isinstance(result, web.StreamResponse):
# The method handler returned a ready-made Response, how nice of it
return result
status_code = HTTP_OK
if isinstance(result, tuple):
result, status_code = result
if isinstance(result, bytes):
bresult = result
elif isinstance(result, str):
bresult = result.encode("utf-8")
elif result is None:
bresult = b""
else:
assert (
False
), f"Result should be None, string, bytes or Response. Got: {result}"
return web.Response(body=bresult, status=status_code)
return handle | [
"def",
"request_handler_factory",
"(",
"view",
":",
"HomeAssistantView",
",",
"handler",
":",
"Callable",
")",
"->",
"Callable",
":",
"assert",
"asyncio",
".",
"iscoroutinefunction",
"(",
"handler",
")",
"or",
"is_callback",
"(",
"handler",
")",
",",
"\"Handler should be a coroutine or a callback.\"",
"async",
"def",
"handle",
"(",
"request",
":",
"web",
".",
"Request",
")",
"->",
"web",
".",
"StreamResponse",
":",
"\"\"\"Handle incoming request.\"\"\"",
"if",
"request",
".",
"app",
"[",
"KEY_HASS",
"]",
".",
"is_stopping",
":",
"return",
"web",
".",
"Response",
"(",
"status",
"=",
"HTTP_SERVICE_UNAVAILABLE",
")",
"authenticated",
"=",
"request",
".",
"get",
"(",
"KEY_AUTHENTICATED",
",",
"False",
")",
"if",
"view",
".",
"requires_auth",
"and",
"not",
"authenticated",
":",
"raise",
"HTTPUnauthorized",
"(",
")",
"_LOGGER",
".",
"debug",
"(",
"\"Serving %s to %s (auth: %s)\"",
",",
"request",
".",
"path",
",",
"request",
".",
"remote",
",",
"authenticated",
",",
")",
"try",
":",
"result",
"=",
"handler",
"(",
"request",
",",
"*",
"*",
"request",
".",
"match_info",
")",
"if",
"asyncio",
".",
"iscoroutine",
"(",
"result",
")",
":",
"result",
"=",
"await",
"result",
"except",
"vol",
".",
"Invalid",
"as",
"err",
":",
"raise",
"HTTPBadRequest",
"(",
")",
"from",
"err",
"except",
"exceptions",
".",
"ServiceNotFound",
"as",
"err",
":",
"raise",
"HTTPInternalServerError",
"(",
")",
"from",
"err",
"except",
"exceptions",
".",
"Unauthorized",
"as",
"err",
":",
"raise",
"HTTPUnauthorized",
"(",
")",
"from",
"err",
"if",
"isinstance",
"(",
"result",
",",
"web",
".",
"StreamResponse",
")",
":",
"# The method handler returned a ready-made Response, how nice of it",
"return",
"result",
"status_code",
"=",
"HTTP_OK",
"if",
"isinstance",
"(",
"result",
",",
"tuple",
")",
":",
"result",
",",
"status_code",
"=",
"result",
"if",
"isinstance",
"(",
"result",
",",
"bytes",
")",
":",
"bresult",
"=",
"result",
"elif",
"isinstance",
"(",
"result",
",",
"str",
")",
":",
"bresult",
"=",
"result",
".",
"encode",
"(",
"\"utf-8\"",
")",
"elif",
"result",
"is",
"None",
":",
"bresult",
"=",
"b\"\"",
"else",
":",
"assert",
"(",
"False",
")",
",",
"f\"Result should be None, string, bytes or Response. Got: {result}\"",
"return",
"web",
".",
"Response",
"(",
"body",
"=",
"bresult",
",",
"status",
"=",
"status_code",
")",
"return",
"handle"
] | [
101,
0
] | [
158,
17
] | python | en | ['en', 'en', 'en'] | True |
HomeAssistantView.context | (request: web.Request) | Generate a context from a request. | Generate a context from a request. | def context(request: web.Request) -> Context:
"""Generate a context from a request."""
user = request.get("hass_user")
if user is None:
return Context()
return Context(user_id=user.id) | [
"def",
"context",
"(",
"request",
":",
"web",
".",
"Request",
")",
"->",
"Context",
":",
"user",
"=",
"request",
".",
"get",
"(",
"\"hass_user\"",
")",
"if",
"user",
"is",
"None",
":",
"return",
"Context",
"(",
")",
"return",
"Context",
"(",
"user_id",
"=",
"user",
".",
"id",
")"
] | [
35,
4
] | [
41,
39
] | python | en | ['en', 'en', 'en'] | True |
HomeAssistantView.json | (
result: Any,
status_code: int = HTTP_OK,
headers: Optional[LooseHeaders] = None,
) | Return a JSON response. | Return a JSON response. | def json(
result: Any,
status_code: int = HTTP_OK,
headers: Optional[LooseHeaders] = None,
) -> web.Response:
"""Return a JSON response."""
try:
msg = json.dumps(result, cls=JSONEncoder, allow_nan=False).encode("UTF-8")
except (ValueError, TypeError) as err:
_LOGGER.error("Unable to serialize to JSON: %s\n%s", err, result)
raise HTTPInternalServerError from err
response = web.Response(
body=msg,
content_type=CONTENT_TYPE_JSON,
status=status_code,
headers=headers,
)
response.enable_compression()
return response | [
"def",
"json",
"(",
"result",
":",
"Any",
",",
"status_code",
":",
"int",
"=",
"HTTP_OK",
",",
"headers",
":",
"Optional",
"[",
"LooseHeaders",
"]",
"=",
"None",
",",
")",
"->",
"web",
".",
"Response",
":",
"try",
":",
"msg",
"=",
"json",
".",
"dumps",
"(",
"result",
",",
"cls",
"=",
"JSONEncoder",
",",
"allow_nan",
"=",
"False",
")",
".",
"encode",
"(",
"\"UTF-8\"",
")",
"except",
"(",
"ValueError",
",",
"TypeError",
")",
"as",
"err",
":",
"_LOGGER",
".",
"error",
"(",
"\"Unable to serialize to JSON: %s\\n%s\"",
",",
"err",
",",
"result",
")",
"raise",
"HTTPInternalServerError",
"from",
"err",
"response",
"=",
"web",
".",
"Response",
"(",
"body",
"=",
"msg",
",",
"content_type",
"=",
"CONTENT_TYPE_JSON",
",",
"status",
"=",
"status_code",
",",
"headers",
"=",
"headers",
",",
")",
"response",
".",
"enable_compression",
"(",
")",
"return",
"response"
] | [
44,
4
] | [
62,
23
] | python | en | ['en', 'ht', 'en'] | True |
HomeAssistantView.json_message | (
self,
message: str,
status_code: int = HTTP_OK,
message_code: Optional[str] = None,
headers: Optional[LooseHeaders] = None,
) | Return a JSON message response. | Return a JSON message response. | def json_message(
self,
message: str,
status_code: int = HTTP_OK,
message_code: Optional[str] = None,
headers: Optional[LooseHeaders] = None,
) -> web.Response:
"""Return a JSON message response."""
data = {"message": message}
if message_code is not None:
data["code"] = message_code
return self.json(data, status_code, headers=headers) | [
"def",
"json_message",
"(",
"self",
",",
"message",
":",
"str",
",",
"status_code",
":",
"int",
"=",
"HTTP_OK",
",",
"message_code",
":",
"Optional",
"[",
"str",
"]",
"=",
"None",
",",
"headers",
":",
"Optional",
"[",
"LooseHeaders",
"]",
"=",
"None",
",",
")",
"->",
"web",
".",
"Response",
":",
"data",
"=",
"{",
"\"message\"",
":",
"message",
"}",
"if",
"message_code",
"is",
"not",
"None",
":",
"data",
"[",
"\"code\"",
"]",
"=",
"message_code",
"return",
"self",
".",
"json",
"(",
"data",
",",
"status_code",
",",
"headers",
"=",
"headers",
")"
] | [
64,
4
] | [
75,
60
] | python | en | ['en', 'lb', 'en'] | True |
HomeAssistantView.register | (self, app: web.Application, router: web.UrlDispatcher) | Register the view with a router. | Register the view with a router. | def register(self, app: web.Application, router: web.UrlDispatcher) -> None:
"""Register the view with a router."""
assert self.url is not None, "No url set for view"
urls = [self.url] + self.extra_urls
routes = []
for method in ("get", "post", "delete", "put", "patch", "head", "options"):
handler = getattr(self, method, None)
if not handler:
continue
handler = request_handler_factory(self, handler)
for url in urls:
routes.append(router.add_route(method, url, handler))
if not self.cors_allowed:
return
for route in routes:
app["allow_cors"](route) | [
"def",
"register",
"(",
"self",
",",
"app",
":",
"web",
".",
"Application",
",",
"router",
":",
"web",
".",
"UrlDispatcher",
")",
"->",
"None",
":",
"assert",
"self",
".",
"url",
"is",
"not",
"None",
",",
"\"No url set for view\"",
"urls",
"=",
"[",
"self",
".",
"url",
"]",
"+",
"self",
".",
"extra_urls",
"routes",
"=",
"[",
"]",
"for",
"method",
"in",
"(",
"\"get\"",
",",
"\"post\"",
",",
"\"delete\"",
",",
"\"put\"",
",",
"\"patch\"",
",",
"\"head\"",
",",
"\"options\"",
")",
":",
"handler",
"=",
"getattr",
"(",
"self",
",",
"method",
",",
"None",
")",
"if",
"not",
"handler",
":",
"continue",
"handler",
"=",
"request_handler_factory",
"(",
"self",
",",
"handler",
")",
"for",
"url",
"in",
"urls",
":",
"routes",
".",
"append",
"(",
"router",
".",
"add_route",
"(",
"method",
",",
"url",
",",
"handler",
")",
")",
"if",
"not",
"self",
".",
"cors_allowed",
":",
"return",
"for",
"route",
"in",
"routes",
":",
"app",
"[",
"\"allow_cors\"",
"]",
"(",
"route",
")"
] | [
77,
4
] | [
98,
36
] | python | en | ['en', 'en', 'en'] | True |
get_scanner | (hass, config) | Validate the configuration and return a Aruba scanner. | Validate the configuration and return a Aruba scanner. | def get_scanner(hass, config):
"""Validate the configuration and return a Aruba scanner."""
scanner = ArubaDeviceScanner(config[DOMAIN])
return scanner if scanner.success_init else None | [
"def",
"get_scanner",
"(",
"hass",
",",
"config",
")",
":",
"scanner",
"=",
"ArubaDeviceScanner",
"(",
"config",
"[",
"DOMAIN",
"]",
")",
"return",
"scanner",
"if",
"scanner",
".",
"success_init",
"else",
"None"
] | [
32,
0
] | [
36,
52
] | python | en | ['en', 'en', 'en'] | True |
ArubaDeviceScanner.__init__ | (self, config) | Initialize the scanner. | Initialize the scanner. | def __init__(self, config):
"""Initialize the scanner."""
self.host = config[CONF_HOST]
self.username = config[CONF_USERNAME]
self.password = config[CONF_PASSWORD]
self.last_results = {}
# Test the router is accessible.
data = self.get_aruba_data()
self.success_init = data is not None | [
"def",
"__init__",
"(",
"self",
",",
"config",
")",
":",
"self",
".",
"host",
"=",
"config",
"[",
"CONF_HOST",
"]",
"self",
".",
"username",
"=",
"config",
"[",
"CONF_USERNAME",
"]",
"self",
".",
"password",
"=",
"config",
"[",
"CONF_PASSWORD",
"]",
"self",
".",
"last_results",
"=",
"{",
"}",
"# Test the router is accessible.",
"data",
"=",
"self",
".",
"get_aruba_data",
"(",
")",
"self",
".",
"success_init",
"=",
"data",
"is",
"not",
"None"
] | [
42,
4
] | [
52,
44
] | python | en | ['en', 'en', 'en'] | True |
ArubaDeviceScanner.scan_devices | (self) | Scan for new devices and return a list with found device IDs. | Scan for new devices and return a list with found device IDs. | def scan_devices(self):
"""Scan for new devices and return a list with found device IDs."""
self._update_info()
return [client["mac"] for client in self.last_results] | [
"def",
"scan_devices",
"(",
"self",
")",
":",
"self",
".",
"_update_info",
"(",
")",
"return",
"[",
"client",
"[",
"\"mac\"",
"]",
"for",
"client",
"in",
"self",
".",
"last_results",
"]"
] | [
54,
4
] | [
57,
62
] | python | en | ['en', 'en', 'en'] | True |
ArubaDeviceScanner.get_device_name | (self, device) | Return the name of the given device or None if we don't know. | Return the name of the given device or None if we don't know. | def get_device_name(self, device):
"""Return the name of the given device or None if we don't know."""
if not self.last_results:
return None
for client in self.last_results:
if client["mac"] == device:
return client["name"]
return None | [
"def",
"get_device_name",
"(",
"self",
",",
"device",
")",
":",
"if",
"not",
"self",
".",
"last_results",
":",
"return",
"None",
"for",
"client",
"in",
"self",
".",
"last_results",
":",
"if",
"client",
"[",
"\"mac\"",
"]",
"==",
"device",
":",
"return",
"client",
"[",
"\"name\"",
"]",
"return",
"None"
] | [
59,
4
] | [
66,
19
] | python | en | ['en', 'en', 'en'] | True |
ArubaDeviceScanner._update_info | (self) | Ensure the information from the Aruba Access Point is up to date.
Return boolean if scanning successful.
| Ensure the information from the Aruba Access Point is up to date. | def _update_info(self):
"""Ensure the information from the Aruba Access Point is up to date.
Return boolean if scanning successful.
"""
if not self.success_init:
return False
data = self.get_aruba_data()
if not data:
return False
self.last_results = data.values()
return True | [
"def",
"_update_info",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"success_init",
":",
"return",
"False",
"data",
"=",
"self",
".",
"get_aruba_data",
"(",
")",
"if",
"not",
"data",
":",
"return",
"False",
"self",
".",
"last_results",
"=",
"data",
".",
"values",
"(",
")",
"return",
"True"
] | [
68,
4
] | [
81,
19
] | python | en | ['en', 'en', 'en'] | True |
ArubaDeviceScanner.get_aruba_data | (self) | Retrieve data from Aruba Access Point and return parsed result. | Retrieve data from Aruba Access Point and return parsed result. | def get_aruba_data(self):
"""Retrieve data from Aruba Access Point and return parsed result."""
connect = f"ssh {self.username}@{self.host}"
ssh = pexpect.spawn(connect)
query = ssh.expect(
[
"password:",
pexpect.TIMEOUT,
pexpect.EOF,
"continue connecting (yes/no)?",
"Host key verification failed.",
"Connection refused",
"Connection timed out",
],
timeout=120,
)
if query == 1:
_LOGGER.error("Timeout")
return
if query == 2:
_LOGGER.error("Unexpected response from router")
return
if query == 3:
ssh.sendline("yes")
ssh.expect("password:")
elif query == 4:
_LOGGER.error("Host key changed")
return
elif query == 5:
_LOGGER.error("Connection refused by server")
return
elif query == 6:
_LOGGER.error("Connection timed out")
return
ssh.sendline(self.password)
ssh.expect("#")
ssh.sendline("show clients")
ssh.expect("#")
devices_result = ssh.before.split(b"\r\n")
ssh.sendline("exit")
devices = {}
for device in devices_result:
match = _DEVICES_REGEX.search(device.decode("utf-8"))
if match:
devices[match.group("ip")] = {
"ip": match.group("ip"),
"mac": match.group("mac").upper(),
"name": match.group("name"),
}
return devices | [
"def",
"get_aruba_data",
"(",
"self",
")",
":",
"connect",
"=",
"f\"ssh {self.username}@{self.host}\"",
"ssh",
"=",
"pexpect",
".",
"spawn",
"(",
"connect",
")",
"query",
"=",
"ssh",
".",
"expect",
"(",
"[",
"\"password:\"",
",",
"pexpect",
".",
"TIMEOUT",
",",
"pexpect",
".",
"EOF",
",",
"\"continue connecting (yes/no)?\"",
",",
"\"Host key verification failed.\"",
",",
"\"Connection refused\"",
",",
"\"Connection timed out\"",
",",
"]",
",",
"timeout",
"=",
"120",
",",
")",
"if",
"query",
"==",
"1",
":",
"_LOGGER",
".",
"error",
"(",
"\"Timeout\"",
")",
"return",
"if",
"query",
"==",
"2",
":",
"_LOGGER",
".",
"error",
"(",
"\"Unexpected response from router\"",
")",
"return",
"if",
"query",
"==",
"3",
":",
"ssh",
".",
"sendline",
"(",
"\"yes\"",
")",
"ssh",
".",
"expect",
"(",
"\"password:\"",
")",
"elif",
"query",
"==",
"4",
":",
"_LOGGER",
".",
"error",
"(",
"\"Host key changed\"",
")",
"return",
"elif",
"query",
"==",
"5",
":",
"_LOGGER",
".",
"error",
"(",
"\"Connection refused by server\"",
")",
"return",
"elif",
"query",
"==",
"6",
":",
"_LOGGER",
".",
"error",
"(",
"\"Connection timed out\"",
")",
"return",
"ssh",
".",
"sendline",
"(",
"self",
".",
"password",
")",
"ssh",
".",
"expect",
"(",
"\"#\"",
")",
"ssh",
".",
"sendline",
"(",
"\"show clients\"",
")",
"ssh",
".",
"expect",
"(",
"\"#\"",
")",
"devices_result",
"=",
"ssh",
".",
"before",
".",
"split",
"(",
"b\"\\r\\n\"",
")",
"ssh",
".",
"sendline",
"(",
"\"exit\"",
")",
"devices",
"=",
"{",
"}",
"for",
"device",
"in",
"devices_result",
":",
"match",
"=",
"_DEVICES_REGEX",
".",
"search",
"(",
"device",
".",
"decode",
"(",
"\"utf-8\"",
")",
")",
"if",
"match",
":",
"devices",
"[",
"match",
".",
"group",
"(",
"\"ip\"",
")",
"]",
"=",
"{",
"\"ip\"",
":",
"match",
".",
"group",
"(",
"\"ip\"",
")",
",",
"\"mac\"",
":",
"match",
".",
"group",
"(",
"\"mac\"",
")",
".",
"upper",
"(",
")",
",",
"\"name\"",
":",
"match",
".",
"group",
"(",
"\"name\"",
")",
",",
"}",
"return",
"devices"
] | [
83,
4
] | [
134,
22
] | python | en | ['en', 'en', 'en'] | True |
test_ws_setup_depose_mfa | (hass, hass_ws_client) | Test set up mfa module for current user. | Test set up mfa module for current user. | async def test_ws_setup_depose_mfa(hass, hass_ws_client):
"""Test set up mfa module for current user."""
hass.auth = await auth_manager_from_config(
hass,
provider_configs=[
{
"type": "insecure_example",
"users": [
{
"username": "test-user",
"password": "test-pass",
"name": "Test Name",
}
],
}
],
module_configs=[
{
"type": "insecure_example",
"id": "example_module",
"data": [{"user_id": "mock-user", "pin": "123456"}],
}
],
)
ensure_auth_manager_loaded(hass.auth)
await async_setup_component(hass, "auth", {"http": {}})
user = MockUser(id="mock-user").add_to_hass(hass)
cred = await hass.auth.auth_providers[0].async_get_or_create_credentials(
{"username": "test-user"}
)
await hass.auth.async_link_user(user, cred)
refresh_token = await hass.auth.async_create_refresh_token(user, CLIENT_ID)
access_token = hass.auth.async_create_access_token(refresh_token)
client = await hass_ws_client(hass, access_token)
await client.send_json({"id": 10, "type": mfa_setup_flow.WS_TYPE_SETUP_MFA})
result = await client.receive_json()
assert result["id"] == 10
assert result["success"] is False
assert result["error"]["code"] == "no_module"
await client.send_json(
{
"id": 11,
"type": mfa_setup_flow.WS_TYPE_SETUP_MFA,
"mfa_module_id": "example_module",
}
)
result = await client.receive_json()
assert result["id"] == 11
assert result["success"]
flow = result["result"]
assert flow["type"] == data_entry_flow.RESULT_TYPE_FORM
assert flow["handler"] == "example_module"
assert flow["step_id"] == "init"
assert flow["data_schema"][0] == {"type": "string", "name": "pin"}
await client.send_json(
{
"id": 12,
"type": mfa_setup_flow.WS_TYPE_SETUP_MFA,
"flow_id": flow["flow_id"],
"user_input": {"pin": "654321"},
}
)
result = await client.receive_json()
assert result["id"] == 12
assert result["success"]
flow = result["result"]
assert flow["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY
assert flow["handler"] == "example_module"
assert flow["data"]["result"] is None
await client.send_json(
{
"id": 13,
"type": mfa_setup_flow.WS_TYPE_DEPOSE_MFA,
"mfa_module_id": "invalid_id",
}
)
result = await client.receive_json()
assert result["id"] == 13
assert result["success"] is False
assert result["error"]["code"] == "disable_failed"
await client.send_json(
{
"id": 14,
"type": mfa_setup_flow.WS_TYPE_DEPOSE_MFA,
"mfa_module_id": "example_module",
}
)
result = await client.receive_json()
assert result["id"] == 14
assert result["success"]
assert result["result"] == "done" | [
"async",
"def",
"test_ws_setup_depose_mfa",
"(",
"hass",
",",
"hass_ws_client",
")",
":",
"hass",
".",
"auth",
"=",
"await",
"auth_manager_from_config",
"(",
"hass",
",",
"provider_configs",
"=",
"[",
"{",
"\"type\"",
":",
"\"insecure_example\"",
",",
"\"users\"",
":",
"[",
"{",
"\"username\"",
":",
"\"test-user\"",
",",
"\"password\"",
":",
"\"test-pass\"",
",",
"\"name\"",
":",
"\"Test Name\"",
",",
"}",
"]",
",",
"}",
"]",
",",
"module_configs",
"=",
"[",
"{",
"\"type\"",
":",
"\"insecure_example\"",
",",
"\"id\"",
":",
"\"example_module\"",
",",
"\"data\"",
":",
"[",
"{",
"\"user_id\"",
":",
"\"mock-user\"",
",",
"\"pin\"",
":",
"\"123456\"",
"}",
"]",
",",
"}",
"]",
",",
")",
"ensure_auth_manager_loaded",
"(",
"hass",
".",
"auth",
")",
"await",
"async_setup_component",
"(",
"hass",
",",
"\"auth\"",
",",
"{",
"\"http\"",
":",
"{",
"}",
"}",
")",
"user",
"=",
"MockUser",
"(",
"id",
"=",
"\"mock-user\"",
")",
".",
"add_to_hass",
"(",
"hass",
")",
"cred",
"=",
"await",
"hass",
".",
"auth",
".",
"auth_providers",
"[",
"0",
"]",
".",
"async_get_or_create_credentials",
"(",
"{",
"\"username\"",
":",
"\"test-user\"",
"}",
")",
"await",
"hass",
".",
"auth",
".",
"async_link_user",
"(",
"user",
",",
"cred",
")",
"refresh_token",
"=",
"await",
"hass",
".",
"auth",
".",
"async_create_refresh_token",
"(",
"user",
",",
"CLIENT_ID",
")",
"access_token",
"=",
"hass",
".",
"auth",
".",
"async_create_access_token",
"(",
"refresh_token",
")",
"client",
"=",
"await",
"hass_ws_client",
"(",
"hass",
",",
"access_token",
")",
"await",
"client",
".",
"send_json",
"(",
"{",
"\"id\"",
":",
"10",
",",
"\"type\"",
":",
"mfa_setup_flow",
".",
"WS_TYPE_SETUP_MFA",
"}",
")",
"result",
"=",
"await",
"client",
".",
"receive_json",
"(",
")",
"assert",
"result",
"[",
"\"id\"",
"]",
"==",
"10",
"assert",
"result",
"[",
"\"success\"",
"]",
"is",
"False",
"assert",
"result",
"[",
"\"error\"",
"]",
"[",
"\"code\"",
"]",
"==",
"\"no_module\"",
"await",
"client",
".",
"send_json",
"(",
"{",
"\"id\"",
":",
"11",
",",
"\"type\"",
":",
"mfa_setup_flow",
".",
"WS_TYPE_SETUP_MFA",
",",
"\"mfa_module_id\"",
":",
"\"example_module\"",
",",
"}",
")",
"result",
"=",
"await",
"client",
".",
"receive_json",
"(",
")",
"assert",
"result",
"[",
"\"id\"",
"]",
"==",
"11",
"assert",
"result",
"[",
"\"success\"",
"]",
"flow",
"=",
"result",
"[",
"\"result\"",
"]",
"assert",
"flow",
"[",
"\"type\"",
"]",
"==",
"data_entry_flow",
".",
"RESULT_TYPE_FORM",
"assert",
"flow",
"[",
"\"handler\"",
"]",
"==",
"\"example_module\"",
"assert",
"flow",
"[",
"\"step_id\"",
"]",
"==",
"\"init\"",
"assert",
"flow",
"[",
"\"data_schema\"",
"]",
"[",
"0",
"]",
"==",
"{",
"\"type\"",
":",
"\"string\"",
",",
"\"name\"",
":",
"\"pin\"",
"}",
"await",
"client",
".",
"send_json",
"(",
"{",
"\"id\"",
":",
"12",
",",
"\"type\"",
":",
"mfa_setup_flow",
".",
"WS_TYPE_SETUP_MFA",
",",
"\"flow_id\"",
":",
"flow",
"[",
"\"flow_id\"",
"]",
",",
"\"user_input\"",
":",
"{",
"\"pin\"",
":",
"\"654321\"",
"}",
",",
"}",
")",
"result",
"=",
"await",
"client",
".",
"receive_json",
"(",
")",
"assert",
"result",
"[",
"\"id\"",
"]",
"==",
"12",
"assert",
"result",
"[",
"\"success\"",
"]",
"flow",
"=",
"result",
"[",
"\"result\"",
"]",
"assert",
"flow",
"[",
"\"type\"",
"]",
"==",
"data_entry_flow",
".",
"RESULT_TYPE_CREATE_ENTRY",
"assert",
"flow",
"[",
"\"handler\"",
"]",
"==",
"\"example_module\"",
"assert",
"flow",
"[",
"\"data\"",
"]",
"[",
"\"result\"",
"]",
"is",
"None",
"await",
"client",
".",
"send_json",
"(",
"{",
"\"id\"",
":",
"13",
",",
"\"type\"",
":",
"mfa_setup_flow",
".",
"WS_TYPE_DEPOSE_MFA",
",",
"\"mfa_module_id\"",
":",
"\"invalid_id\"",
",",
"}",
")",
"result",
"=",
"await",
"client",
".",
"receive_json",
"(",
")",
"assert",
"result",
"[",
"\"id\"",
"]",
"==",
"13",
"assert",
"result",
"[",
"\"success\"",
"]",
"is",
"False",
"assert",
"result",
"[",
"\"error\"",
"]",
"[",
"\"code\"",
"]",
"==",
"\"disable_failed\"",
"await",
"client",
".",
"send_json",
"(",
"{",
"\"id\"",
":",
"14",
",",
"\"type\"",
":",
"mfa_setup_flow",
".",
"WS_TYPE_DEPOSE_MFA",
",",
"\"mfa_module_id\"",
":",
"\"example_module\"",
",",
"}",
")",
"result",
"=",
"await",
"client",
".",
"receive_json",
"(",
")",
"assert",
"result",
"[",
"\"id\"",
"]",
"==",
"14",
"assert",
"result",
"[",
"\"success\"",
"]",
"assert",
"result",
"[",
"\"result\"",
"]",
"==",
"\"done\""
] | [
9,
0
] | [
113,
37
] | python | en | ['en', 'en', 'en'] | True |
ActorProxy.roll_out | (self, index: int, training: bool = True, model_by_agent: dict = None, exploration_params=None) | Collect roll-out data from remote actors.
Args:
index (int): Index of roll-out requests.
training (bool): If true, the roll-out request is for training purposes.
model_by_agent (dict): Models to be broadcast to remote actors for inference. Defaults to None.
exploration_params: Exploration parameters to be used by the remote roll-out actors. Defaults to None.
| Collect roll-out data from remote actors. | def roll_out(self, index: int, training: bool = True, model_by_agent: dict = None, exploration_params=None):
"""Collect roll-out data from remote actors.
Args:
index (int): Index of roll-out requests.
training (bool): If true, the roll-out request is for training purposes.
model_by_agent (dict): Models to be broadcast to remote actors for inference. Defaults to None.
exploration_params: Exploration parameters to be used by the remote roll-out actors. Defaults to None.
"""
payload = {
PayloadKey.ROLLOUT_INDEX: index,
PayloadKey.TRAINING: training,
PayloadKey.MODEL: model_by_agent,
PayloadKey.EXPLORATION_PARAMS: exploration_params
}
self._proxy.iscatter(MessageTag.ROLLOUT, SessionType.TASK, [(actor, payload) for actor in self._actors])
self.logger.info(f"Sent roll-out requests to {self._actors} for ep-{index}")
# Receive roll-out results from remote actors
for msg in self._proxy.receive():
if msg.payload[PayloadKey.ROLLOUT_INDEX] != index:
self.logger.info(
f"Ignore a message of type {msg.tag} with ep {msg.payload[PayloadKey.ROLLOUT_INDEX]} "
f"(expected {index} or greater)"
)
continue
if msg.tag == MessageTag.FINISHED:
# If enough update messages have been received, call update() and break out of the loop to start
# the next episode.
result = self._registry_table.push(msg)
if result:
env_metrics, details = result[0]
break
return env_metrics, details | [
"def",
"roll_out",
"(",
"self",
",",
"index",
":",
"int",
",",
"training",
":",
"bool",
"=",
"True",
",",
"model_by_agent",
":",
"dict",
"=",
"None",
",",
"exploration_params",
"=",
"None",
")",
":",
"payload",
"=",
"{",
"PayloadKey",
".",
"ROLLOUT_INDEX",
":",
"index",
",",
"PayloadKey",
".",
"TRAINING",
":",
"training",
",",
"PayloadKey",
".",
"MODEL",
":",
"model_by_agent",
",",
"PayloadKey",
".",
"EXPLORATION_PARAMS",
":",
"exploration_params",
"}",
"self",
".",
"_proxy",
".",
"iscatter",
"(",
"MessageTag",
".",
"ROLLOUT",
",",
"SessionType",
".",
"TASK",
",",
"[",
"(",
"actor",
",",
"payload",
")",
"for",
"actor",
"in",
"self",
".",
"_actors",
"]",
")",
"self",
".",
"logger",
".",
"info",
"(",
"f\"Sent roll-out requests to {self._actors} for ep-{index}\"",
")",
"# Receive roll-out results from remote actors",
"for",
"msg",
"in",
"self",
".",
"_proxy",
".",
"receive",
"(",
")",
":",
"if",
"msg",
".",
"payload",
"[",
"PayloadKey",
".",
"ROLLOUT_INDEX",
"]",
"!=",
"index",
":",
"self",
".",
"logger",
".",
"info",
"(",
"f\"Ignore a message of type {msg.tag} with ep {msg.payload[PayloadKey.ROLLOUT_INDEX]} \"",
"f\"(expected {index} or greater)\"",
")",
"continue",
"if",
"msg",
".",
"tag",
"==",
"MessageTag",
".",
"FINISHED",
":",
"# If enough update messages have been received, call update() and break out of the loop to start",
"# the next episode.",
"result",
"=",
"self",
".",
"_registry_table",
".",
"push",
"(",
"msg",
")",
"if",
"result",
":",
"env_metrics",
",",
"details",
"=",
"result",
"[",
"0",
"]",
"break",
"return",
"env_metrics",
",",
"details"
] | [
46,
4
] | [
80,
35
] | python | en | ['en', 'en', 'en'] | True |
ActorProxy.terminate | (self) | Tell the remote actors to exit. | Tell the remote actors to exit. | def terminate(self):
"""Tell the remote actors to exit."""
self._proxy.ibroadcast(
component_type="actor", tag=MessageTag.EXIT, session_type=SessionType.NOTIFICATION
)
self.logger.info("Exiting...")
self._proxy.close() | [
"def",
"terminate",
"(",
"self",
")",
":",
"self",
".",
"_proxy",
".",
"ibroadcast",
"(",
"component_type",
"=",
"\"actor\"",
",",
"tag",
"=",
"MessageTag",
".",
"EXIT",
",",
"session_type",
"=",
"SessionType",
".",
"NOTIFICATION",
")",
"self",
".",
"logger",
".",
"info",
"(",
"\"Exiting...\"",
")",
"self",
".",
"_proxy",
".",
"close",
"(",
")"
] | [
87,
4
] | [
93,
27
] | python | en | ['en', 'en', 'en'] | True |
pytest_runtest_makereport | (item, call) | Add test report to node. | Add test report to node. | def pytest_runtest_makereport(item, call):
"""Add test report to node."""
# execute all other hooks to obtain the report object
outcome = yield
rep = outcome.get_result()
# set a report attribute for each phase of a call, which can
# be "setup", "call", "teardown"
setattr(item, f"rep_{rep.when}", rep) | [
"def",
"pytest_runtest_makereport",
"(",
"item",
",",
"call",
")",
":",
"# execute all other hooks to obtain the report object",
"outcome",
"=",
"yield",
"rep",
"=",
"outcome",
".",
"get_result",
"(",
")",
"# set a report attribute for each phase of a call, which can",
"# be \"setup\", \"call\", \"teardown\"",
"setattr",
"(",
"item",
",",
"f\"rep_{rep.when}\"",
",",
"rep",
")"
] | [
9,
0
] | [
17,
41
] | python | en | ['en', 'en', 'en'] | True |
ToonDataUpdateCoordinator.__init__ | (
self, hass: HomeAssistant, *, entry: ConfigEntry, session: OAuth2Session
) | Initialize global Toon data updater. | Initialize global Toon data updater. | def __init__(
self, hass: HomeAssistant, *, entry: ConfigEntry, session: OAuth2Session
):
"""Initialize global Toon data updater."""
self.session = session
self.entry = entry
async def async_token_refresh() -> str:
await session.async_ensure_token_valid()
return session.token["access_token"]
self.toon = Toon(
token=session.token["access_token"],
session=async_get_clientsession(hass),
token_refresh_method=async_token_refresh,
)
super().__init__(
hass, _LOGGER, name=DOMAIN, update_interval=DEFAULT_SCAN_INTERVAL
) | [
"def",
"__init__",
"(",
"self",
",",
"hass",
":",
"HomeAssistant",
",",
"*",
",",
"entry",
":",
"ConfigEntry",
",",
"session",
":",
"OAuth2Session",
")",
":",
"self",
".",
"session",
"=",
"session",
"self",
".",
"entry",
"=",
"entry",
"async",
"def",
"async_token_refresh",
"(",
")",
"->",
"str",
":",
"await",
"session",
".",
"async_ensure_token_valid",
"(",
")",
"return",
"session",
".",
"token",
"[",
"\"access_token\"",
"]",
"self",
".",
"toon",
"=",
"Toon",
"(",
"token",
"=",
"session",
".",
"token",
"[",
"\"access_token\"",
"]",
",",
"session",
"=",
"async_get_clientsession",
"(",
"hass",
")",
",",
"token_refresh_method",
"=",
"async_token_refresh",
",",
")",
"super",
"(",
")",
".",
"__init__",
"(",
"hass",
",",
"_LOGGER",
",",
"name",
"=",
"DOMAIN",
",",
"update_interval",
"=",
"DEFAULT_SCAN_INTERVAL",
")"
] | [
26,
4
] | [
45,
9
] | python | en | ['nl', 'en', 'it'] | False |
ToonDataUpdateCoordinator.update_listeners | (self) | Call update on all listeners. | Call update on all listeners. | def update_listeners(self) -> None:
"""Call update on all listeners."""
for update_callback in self._listeners:
update_callback() | [
"def",
"update_listeners",
"(",
"self",
")",
"->",
"None",
":",
"for",
"update_callback",
"in",
"self",
".",
"_listeners",
":",
"update_callback",
"(",
")"
] | [
47,
4
] | [
50,
29
] | python | en | ['en', 'en', 'en'] | True |
ToonDataUpdateCoordinator.register_webhook | (self, event: Optional[Event] = None) | Register a webhook with Toon to get live updates. | Register a webhook with Toon to get live updates. | async def register_webhook(self, event: Optional[Event] = None) -> None:
"""Register a webhook with Toon to get live updates."""
if CONF_WEBHOOK_ID not in self.entry.data:
data = {**self.entry.data, CONF_WEBHOOK_ID: secrets.token_hex()}
self.hass.config_entries.async_update_entry(self.entry, data=data)
if self.hass.components.cloud.async_active_subscription():
if CONF_CLOUDHOOK_URL not in self.entry.data:
webhook_url = await self.hass.components.cloud.async_create_cloudhook(
self.entry.data[CONF_WEBHOOK_ID]
)
data = {**self.entry.data, CONF_CLOUDHOOK_URL: webhook_url}
self.hass.config_entries.async_update_entry(self.entry, data=data)
else:
webhook_url = self.entry.data[CONF_CLOUDHOOK_URL]
else:
webhook_url = self.hass.components.webhook.async_generate_url(
self.entry.data[CONF_WEBHOOK_ID]
)
# Ensure the webhook is not registered already
webhook_unregister(self.hass, self.entry.data[CONF_WEBHOOK_ID])
webhook_register(
self.hass,
DOMAIN,
"Toon",
self.entry.data[CONF_WEBHOOK_ID],
self.handle_webhook,
)
try:
await self.toon.subscribe_webhook(
application_id=self.entry.entry_id, url=webhook_url
)
_LOGGER.info("Registered Toon webhook: %s", webhook_url)
except ToonError as err:
_LOGGER.error("Error during webhook registration - %s", err)
self.hass.bus.async_listen_once(
EVENT_HOMEASSISTANT_STOP, self.unregister_webhook
) | [
"async",
"def",
"register_webhook",
"(",
"self",
",",
"event",
":",
"Optional",
"[",
"Event",
"]",
"=",
"None",
")",
"->",
"None",
":",
"if",
"CONF_WEBHOOK_ID",
"not",
"in",
"self",
".",
"entry",
".",
"data",
":",
"data",
"=",
"{",
"*",
"*",
"self",
".",
"entry",
".",
"data",
",",
"CONF_WEBHOOK_ID",
":",
"secrets",
".",
"token_hex",
"(",
")",
"}",
"self",
".",
"hass",
".",
"config_entries",
".",
"async_update_entry",
"(",
"self",
".",
"entry",
",",
"data",
"=",
"data",
")",
"if",
"self",
".",
"hass",
".",
"components",
".",
"cloud",
".",
"async_active_subscription",
"(",
")",
":",
"if",
"CONF_CLOUDHOOK_URL",
"not",
"in",
"self",
".",
"entry",
".",
"data",
":",
"webhook_url",
"=",
"await",
"self",
".",
"hass",
".",
"components",
".",
"cloud",
".",
"async_create_cloudhook",
"(",
"self",
".",
"entry",
".",
"data",
"[",
"CONF_WEBHOOK_ID",
"]",
")",
"data",
"=",
"{",
"*",
"*",
"self",
".",
"entry",
".",
"data",
",",
"CONF_CLOUDHOOK_URL",
":",
"webhook_url",
"}",
"self",
".",
"hass",
".",
"config_entries",
".",
"async_update_entry",
"(",
"self",
".",
"entry",
",",
"data",
"=",
"data",
")",
"else",
":",
"webhook_url",
"=",
"self",
".",
"entry",
".",
"data",
"[",
"CONF_CLOUDHOOK_URL",
"]",
"else",
":",
"webhook_url",
"=",
"self",
".",
"hass",
".",
"components",
".",
"webhook",
".",
"async_generate_url",
"(",
"self",
".",
"entry",
".",
"data",
"[",
"CONF_WEBHOOK_ID",
"]",
")",
"# Ensure the webhook is not registered already",
"webhook_unregister",
"(",
"self",
".",
"hass",
",",
"self",
".",
"entry",
".",
"data",
"[",
"CONF_WEBHOOK_ID",
"]",
")",
"webhook_register",
"(",
"self",
".",
"hass",
",",
"DOMAIN",
",",
"\"Toon\"",
",",
"self",
".",
"entry",
".",
"data",
"[",
"CONF_WEBHOOK_ID",
"]",
",",
"self",
".",
"handle_webhook",
",",
")",
"try",
":",
"await",
"self",
".",
"toon",
".",
"subscribe_webhook",
"(",
"application_id",
"=",
"self",
".",
"entry",
".",
"entry_id",
",",
"url",
"=",
"webhook_url",
")",
"_LOGGER",
".",
"info",
"(",
"\"Registered Toon webhook: %s\"",
",",
"webhook_url",
")",
"except",
"ToonError",
"as",
"err",
":",
"_LOGGER",
".",
"error",
"(",
"\"Error during webhook registration - %s\"",
",",
"err",
")",
"self",
".",
"hass",
".",
"bus",
".",
"async_listen_once",
"(",
"EVENT_HOMEASSISTANT_STOP",
",",
"self",
".",
"unregister_webhook",
")"
] | [
52,
4
] | [
94,
9
] | python | en | ['en', 'en', 'en'] | True |
ToonDataUpdateCoordinator.handle_webhook | (
self, hass: HomeAssistant, webhook_id: str, request
) | Handle webhook callback. | Handle webhook callback. | async def handle_webhook(
self, hass: HomeAssistant, webhook_id: str, request
) -> None:
"""Handle webhook callback."""
try:
data = await request.json()
except ValueError:
return
_LOGGER.debug("Got webhook data: %s", data)
# Webhook expired notification, re-register
if data.get("code") == 510:
await self.register_webhook()
return
if (
"updateDataSet" not in data
or "commonName" not in data
or self.data.agreement.display_common_name != data["commonName"]
):
_LOGGER.warning("Received invalid data from Toon webhook - %s", data)
return
try:
await self.toon.update(data["updateDataSet"])
self.update_listeners()
except ToonError as err:
_LOGGER.error("Could not process data received from Toon webhook - %s", err) | [
"async",
"def",
"handle_webhook",
"(",
"self",
",",
"hass",
":",
"HomeAssistant",
",",
"webhook_id",
":",
"str",
",",
"request",
")",
"->",
"None",
":",
"try",
":",
"data",
"=",
"await",
"request",
".",
"json",
"(",
")",
"except",
"ValueError",
":",
"return",
"_LOGGER",
".",
"debug",
"(",
"\"Got webhook data: %s\"",
",",
"data",
")",
"# Webhook expired notification, re-register",
"if",
"data",
".",
"get",
"(",
"\"code\"",
")",
"==",
"510",
":",
"await",
"self",
".",
"register_webhook",
"(",
")",
"return",
"if",
"(",
"\"updateDataSet\"",
"not",
"in",
"data",
"or",
"\"commonName\"",
"not",
"in",
"data",
"or",
"self",
".",
"data",
".",
"agreement",
".",
"display_common_name",
"!=",
"data",
"[",
"\"commonName\"",
"]",
")",
":",
"_LOGGER",
".",
"warning",
"(",
"\"Received invalid data from Toon webhook - %s\"",
",",
"data",
")",
"return",
"try",
":",
"await",
"self",
".",
"toon",
".",
"update",
"(",
"data",
"[",
"\"updateDataSet\"",
"]",
")",
"self",
".",
"update_listeners",
"(",
")",
"except",
"ToonError",
"as",
"err",
":",
"_LOGGER",
".",
"error",
"(",
"\"Could not process data received from Toon webhook - %s\"",
",",
"err",
")"
] | [
96,
4
] | [
124,
88
] | python | en | ['en', 'xh', 'en'] | True |
ToonDataUpdateCoordinator.unregister_webhook | (self, event: Optional[Event] = None) | Remove / Unregister webhook for toon. | Remove / Unregister webhook for toon. | async def unregister_webhook(self, event: Optional[Event] = None) -> None:
"""Remove / Unregister webhook for toon."""
_LOGGER.debug(
"Unregistering Toon webhook (%s)", self.entry.data[CONF_WEBHOOK_ID]
)
try:
await self.toon.unsubscribe_webhook(self.entry.entry_id)
except ToonError as err:
_LOGGER.error("Failed unregistering Toon webhook - %s", err)
webhook_unregister(self.hass, self.entry.data[CONF_WEBHOOK_ID]) | [
"async",
"def",
"unregister_webhook",
"(",
"self",
",",
"event",
":",
"Optional",
"[",
"Event",
"]",
"=",
"None",
")",
"->",
"None",
":",
"_LOGGER",
".",
"debug",
"(",
"\"Unregistering Toon webhook (%s)\"",
",",
"self",
".",
"entry",
".",
"data",
"[",
"CONF_WEBHOOK_ID",
"]",
")",
"try",
":",
"await",
"self",
".",
"toon",
".",
"unsubscribe_webhook",
"(",
"self",
".",
"entry",
".",
"entry_id",
")",
"except",
"ToonError",
"as",
"err",
":",
"_LOGGER",
".",
"error",
"(",
"\"Failed unregistering Toon webhook - %s\"",
",",
"err",
")",
"webhook_unregister",
"(",
"self",
".",
"hass",
",",
"self",
".",
"entry",
".",
"data",
"[",
"CONF_WEBHOOK_ID",
"]",
")"
] | [
126,
4
] | [
136,
71
] | python | en | ['en', 'en', 'nl'] | True |
ToonDataUpdateCoordinator._async_update_data | (self) | Fetch data from Toon. | Fetch data from Toon. | async def _async_update_data(self) -> Status:
"""Fetch data from Toon."""
try:
return await self.toon.update()
except ToonError as error:
raise UpdateFailed(f"Invalid response from API: {error}") from error | [
"async",
"def",
"_async_update_data",
"(",
"self",
")",
"->",
"Status",
":",
"try",
":",
"return",
"await",
"self",
".",
"toon",
".",
"update",
"(",
")",
"except",
"ToonError",
"as",
"error",
":",
"raise",
"UpdateFailed",
"(",
"f\"Invalid response from API: {error}\"",
")",
"from",
"error"
] | [
138,
4
] | [
143,
80
] | python | en | ['en', 'en', 'en'] | True |
_generate_qr_code | (data: str) | Generate a base64 PNG string represent QR Code image of data. | Generate a base64 PNG string represent QR Code image of data. | def _generate_qr_code(data: str) -> str:
"""Generate a base64 PNG string represent QR Code image of data."""
import pyqrcode # pylint: disable=import-outside-toplevel
qr_code = pyqrcode.create(data)
with BytesIO() as buffer:
qr_code.svg(file=buffer, scale=4)
return str(
buffer.getvalue()
.decode("ascii")
.replace("\n", "")
.replace(
'<?xml version="1.0" encoding="UTF-8"?>'
'<svg xmlns="http://www.w3.org/2000/svg"',
"<svg",
)
) | [
"def",
"_generate_qr_code",
"(",
"data",
":",
"str",
")",
"->",
"str",
":",
"import",
"pyqrcode",
"# pylint: disable=import-outside-toplevel",
"qr_code",
"=",
"pyqrcode",
".",
"create",
"(",
"data",
")",
"with",
"BytesIO",
"(",
")",
"as",
"buffer",
":",
"qr_code",
".",
"svg",
"(",
"file",
"=",
"buffer",
",",
"scale",
"=",
"4",
")",
"return",
"str",
"(",
"buffer",
".",
"getvalue",
"(",
")",
".",
"decode",
"(",
"\"ascii\"",
")",
".",
"replace",
"(",
"\"\\n\"",
",",
"\"\"",
")",
".",
"replace",
"(",
"'<?xml version=\"1.0\" encoding=\"UTF-8\"?>'",
"'<svg xmlns=\"http://www.w3.org/2000/svg\"'",
",",
"\"<svg\"",
",",
")",
")"
] | [
32,
0
] | [
49,
9
] | python | en | ['en', 'en', 'en'] | True |
_generate_secret_and_qr_code | (username: str) | Generate a secret, url, and QR code. | Generate a secret, url, and QR code. | def _generate_secret_and_qr_code(username: str) -> Tuple[str, str, str]:
"""Generate a secret, url, and QR code."""
import pyotp # pylint: disable=import-outside-toplevel
ota_secret = pyotp.random_base32()
url = pyotp.totp.TOTP(ota_secret).provisioning_uri(
username, issuer_name="Home Assistant"
)
image = _generate_qr_code(url)
return ota_secret, url, image | [
"def",
"_generate_secret_and_qr_code",
"(",
"username",
":",
"str",
")",
"->",
"Tuple",
"[",
"str",
",",
"str",
",",
"str",
"]",
":",
"import",
"pyotp",
"# pylint: disable=import-outside-toplevel",
"ota_secret",
"=",
"pyotp",
".",
"random_base32",
"(",
")",
"url",
"=",
"pyotp",
".",
"totp",
".",
"TOTP",
"(",
"ota_secret",
")",
".",
"provisioning_uri",
"(",
"username",
",",
"issuer_name",
"=",
"\"Home Assistant\"",
")",
"image",
"=",
"_generate_qr_code",
"(",
"url",
")",
"return",
"ota_secret",
",",
"url",
",",
"image"
] | [
52,
0
] | [
61,
33
] | python | en | ['en', 'co', 'en'] | True |
TotpSetupFlow.__init__ | (
self, auth_module: TotpAuthModule, setup_schema: vol.Schema, user: User
) | Initialize the setup flow. | Initialize the setup flow. | def __init__(
self, auth_module: TotpAuthModule, setup_schema: vol.Schema, user: User
) -> None:
"""Initialize the setup flow."""
super().__init__(auth_module, setup_schema, user.id)
# to fix typing complaint
self._auth_module: TotpAuthModule = auth_module
self._user = user
self._ota_secret: Optional[str] = None
self._url = None # type Optional[str]
self._image = None | [
"def",
"__init__",
"(",
"self",
",",
"auth_module",
":",
"TotpAuthModule",
",",
"setup_schema",
":",
"vol",
".",
"Schema",
",",
"user",
":",
"User",
")",
"->",
"None",
":",
"super",
"(",
")",
".",
"__init__",
"(",
"auth_module",
",",
"setup_schema",
",",
"user",
".",
"id",
")",
"# to fix typing complaint",
"self",
".",
"_auth_module",
":",
"TotpAuthModule",
"=",
"auth_module",
"self",
".",
"_user",
"=",
"user",
"self",
".",
"_ota_secret",
":",
"Optional",
"[",
"str",
"]",
"=",
"None",
"self",
".",
"_url",
"=",
"None",
"# type Optional[str]",
"self",
".",
"_image",
"=",
"None"
] | [
175,
4
] | [
185,
26
] | python | en | ['en', 'en', 'en'] | True |
TotpSetupFlow.async_step_init | (
self, user_input: Optional[Dict[str, str]] = None
) | Handle the first step of setup flow.
Return self.async_show_form(step_id='init') if user_input is None.
Return self.async_create_entry(data={'result': result}) if finish.
| Handle the first step of setup flow. | async def async_step_init(
self, user_input: Optional[Dict[str, str]] = None
) -> Dict[str, Any]:
"""Handle the first step of setup flow.
Return self.async_show_form(step_id='init') if user_input is None.
Return self.async_create_entry(data={'result': result}) if finish.
"""
import pyotp # pylint: disable=import-outside-toplevel
errors: Dict[str, str] = {}
if user_input:
verified = await self.hass.async_add_executor_job( # type: ignore
pyotp.TOTP(self._ota_secret).verify, user_input["code"]
)
if verified:
result = await self._auth_module.async_setup_user(
self._user_id, {"secret": self._ota_secret}
)
return self.async_create_entry(
title=self._auth_module.name, data={"result": result}
)
errors["base"] = "invalid_code"
else:
hass = self._auth_module.hass
(
self._ota_secret,
self._url,
self._image,
) = await hass.async_add_executor_job(
_generate_secret_and_qr_code, # type: ignore
str(self._user.name),
)
return self.async_show_form(
step_id="init",
data_schema=self._setup_schema,
description_placeholders={
"code": self._ota_secret,
"url": self._url,
"qr_code": self._image,
},
errors=errors,
) | [
"async",
"def",
"async_step_init",
"(",
"self",
",",
"user_input",
":",
"Optional",
"[",
"Dict",
"[",
"str",
",",
"str",
"]",
"]",
"=",
"None",
")",
"->",
"Dict",
"[",
"str",
",",
"Any",
"]",
":",
"import",
"pyotp",
"# pylint: disable=import-outside-toplevel",
"errors",
":",
"Dict",
"[",
"str",
",",
"str",
"]",
"=",
"{",
"}",
"if",
"user_input",
":",
"verified",
"=",
"await",
"self",
".",
"hass",
".",
"async_add_executor_job",
"(",
"# type: ignore",
"pyotp",
".",
"TOTP",
"(",
"self",
".",
"_ota_secret",
")",
".",
"verify",
",",
"user_input",
"[",
"\"code\"",
"]",
")",
"if",
"verified",
":",
"result",
"=",
"await",
"self",
".",
"_auth_module",
".",
"async_setup_user",
"(",
"self",
".",
"_user_id",
",",
"{",
"\"secret\"",
":",
"self",
".",
"_ota_secret",
"}",
")",
"return",
"self",
".",
"async_create_entry",
"(",
"title",
"=",
"self",
".",
"_auth_module",
".",
"name",
",",
"data",
"=",
"{",
"\"result\"",
":",
"result",
"}",
")",
"errors",
"[",
"\"base\"",
"]",
"=",
"\"invalid_code\"",
"else",
":",
"hass",
"=",
"self",
".",
"_auth_module",
".",
"hass",
"(",
"self",
".",
"_ota_secret",
",",
"self",
".",
"_url",
",",
"self",
".",
"_image",
",",
")",
"=",
"await",
"hass",
".",
"async_add_executor_job",
"(",
"_generate_secret_and_qr_code",
",",
"# type: ignore",
"str",
"(",
"self",
".",
"_user",
".",
"name",
")",
",",
")",
"return",
"self",
".",
"async_show_form",
"(",
"step_id",
"=",
"\"init\"",
",",
"data_schema",
"=",
"self",
".",
"_setup_schema",
",",
"description_placeholders",
"=",
"{",
"\"code\"",
":",
"self",
".",
"_ota_secret",
",",
"\"url\"",
":",
"self",
".",
"_url",
",",
"\"qr_code\"",
":",
"self",
".",
"_image",
",",
"}",
",",
"errors",
"=",
"errors",
",",
")"
] | [
187,
4
] | [
233,
9
] | python | en | ['en', 'en', 'en'] | True |
setup_platform | (hass, config, add_entities, discovery_info=None) | Set up the Hikvision binary sensor devices. | Set up the Hikvision binary sensor devices. | def setup_platform(hass, config, add_entities, discovery_info=None):
"""Set up the Hikvision binary sensor devices."""
name = config.get(CONF_NAME)
host = config.get(CONF_HOST)
port = config.get(CONF_PORT)
username = config.get(CONF_USERNAME)
password = config.get(CONF_PASSWORD)
customize = config.get(CONF_CUSTOMIZE)
protocol = "https" if config[CONF_SSL] else "http"
url = f"{protocol}://{host}"
data = HikvisionData(hass, url, port, name, username, password)
if data.sensors is None:
_LOGGER.error("Hikvision event stream has no data, unable to set up")
return False
entities = []
for sensor, channel_list in data.sensors.items():
for channel in channel_list:
# Build sensor name, then parse customize config.
if data.type == "NVR":
sensor_name = f"{sensor.replace(' ', '_')}_{channel[1]}"
else:
sensor_name = sensor.replace(" ", "_")
custom = customize.get(sensor_name.lower(), {})
ignore = custom.get(CONF_IGNORED)
delay = custom.get(CONF_DELAY)
_LOGGER.debug(
"Entity: %s - %s, Options - Ignore: %s, Delay: %s",
data.name,
sensor_name,
ignore,
delay,
)
if not ignore:
entities.append(
HikvisionBinarySensor(hass, sensor, channel[1], data, delay)
)
add_entities(entities) | [
"def",
"setup_platform",
"(",
"hass",
",",
"config",
",",
"add_entities",
",",
"discovery_info",
"=",
"None",
")",
":",
"name",
"=",
"config",
".",
"get",
"(",
"CONF_NAME",
")",
"host",
"=",
"config",
".",
"get",
"(",
"CONF_HOST",
")",
"port",
"=",
"config",
".",
"get",
"(",
"CONF_PORT",
")",
"username",
"=",
"config",
".",
"get",
"(",
"CONF_USERNAME",
")",
"password",
"=",
"config",
".",
"get",
"(",
"CONF_PASSWORD",
")",
"customize",
"=",
"config",
".",
"get",
"(",
"CONF_CUSTOMIZE",
")",
"protocol",
"=",
"\"https\"",
"if",
"config",
"[",
"CONF_SSL",
"]",
"else",
"\"http\"",
"url",
"=",
"f\"{protocol}://{host}\"",
"data",
"=",
"HikvisionData",
"(",
"hass",
",",
"url",
",",
"port",
",",
"name",
",",
"username",
",",
"password",
")",
"if",
"data",
".",
"sensors",
"is",
"None",
":",
"_LOGGER",
".",
"error",
"(",
"\"Hikvision event stream has no data, unable to set up\"",
")",
"return",
"False",
"entities",
"=",
"[",
"]",
"for",
"sensor",
",",
"channel_list",
"in",
"data",
".",
"sensors",
".",
"items",
"(",
")",
":",
"for",
"channel",
"in",
"channel_list",
":",
"# Build sensor name, then parse customize config.",
"if",
"data",
".",
"type",
"==",
"\"NVR\"",
":",
"sensor_name",
"=",
"f\"{sensor.replace(' ', '_')}_{channel[1]}\"",
"else",
":",
"sensor_name",
"=",
"sensor",
".",
"replace",
"(",
"\" \"",
",",
"\"_\"",
")",
"custom",
"=",
"customize",
".",
"get",
"(",
"sensor_name",
".",
"lower",
"(",
")",
",",
"{",
"}",
")",
"ignore",
"=",
"custom",
".",
"get",
"(",
"CONF_IGNORED",
")",
"delay",
"=",
"custom",
".",
"get",
"(",
"CONF_DELAY",
")",
"_LOGGER",
".",
"debug",
"(",
"\"Entity: %s - %s, Options - Ignore: %s, Delay: %s\"",
",",
"data",
".",
"name",
",",
"sensor_name",
",",
"ignore",
",",
"delay",
",",
")",
"if",
"not",
"ignore",
":",
"entities",
".",
"append",
"(",
"HikvisionBinarySensor",
"(",
"hass",
",",
"sensor",
",",
"channel",
"[",
"1",
"]",
",",
"data",
",",
"delay",
")",
")",
"add_entities",
"(",
"entities",
")"
] | [
87,
0
] | [
133,
26
] | python | en | ['en', 'en', 'en'] | True |
HikvisionData.__init__ | (self, hass, url, port, name, username, password) | Initialize the data object. | Initialize the data object. | def __init__(self, hass, url, port, name, username, password):
"""Initialize the data object."""
self._url = url
self._port = port
self._name = name
self._username = username
self._password = password
# Establish camera
self.camdata = HikCamera(self._url, self._port, self._username, self._password)
if self._name is None:
self._name = self.camdata.get_name
hass.bus.listen_once(EVENT_HOMEASSISTANT_STOP, self.stop_hik)
hass.bus.listen_once(EVENT_HOMEASSISTANT_START, self.start_hik) | [
"def",
"__init__",
"(",
"self",
",",
"hass",
",",
"url",
",",
"port",
",",
"name",
",",
"username",
",",
"password",
")",
":",
"self",
".",
"_url",
"=",
"url",
"self",
".",
"_port",
"=",
"port",
"self",
".",
"_name",
"=",
"name",
"self",
".",
"_username",
"=",
"username",
"self",
".",
"_password",
"=",
"password",
"# Establish camera",
"self",
".",
"camdata",
"=",
"HikCamera",
"(",
"self",
".",
"_url",
",",
"self",
".",
"_port",
",",
"self",
".",
"_username",
",",
"self",
".",
"_password",
")",
"if",
"self",
".",
"_name",
"is",
"None",
":",
"self",
".",
"_name",
"=",
"self",
".",
"camdata",
".",
"get_name",
"hass",
".",
"bus",
".",
"listen_once",
"(",
"EVENT_HOMEASSISTANT_STOP",
",",
"self",
".",
"stop_hik",
")",
"hass",
".",
"bus",
".",
"listen_once",
"(",
"EVENT_HOMEASSISTANT_START",
",",
"self",
".",
"start_hik",
")"
] | [
139,
4
] | [
155,
71
] | python | en | ['en', 'en', 'en'] | True |
HikvisionData.stop_hik | (self, event) | Shutdown Hikvision subscriptions and subscription thread on exit. | Shutdown Hikvision subscriptions and subscription thread on exit. | def stop_hik(self, event):
"""Shutdown Hikvision subscriptions and subscription thread on exit."""
self.camdata.disconnect() | [
"def",
"stop_hik",
"(",
"self",
",",
"event",
")",
":",
"self",
".",
"camdata",
".",
"disconnect",
"(",
")"
] | [
157,
4
] | [
159,
33
] | python | en | ['en', 'en', 'en'] | True |
HikvisionData.start_hik | (self, event) | Start Hikvision event stream thread. | Start Hikvision event stream thread. | def start_hik(self, event):
"""Start Hikvision event stream thread."""
self.camdata.start_stream() | [
"def",
"start_hik",
"(",
"self",
",",
"event",
")",
":",
"self",
".",
"camdata",
".",
"start_stream",
"(",
")"
] | [
161,
4
] | [
163,
35
] | python | en | ['en', 'la', 'en'] | True |
HikvisionData.sensors | (self) | Return list of available sensors and their states. | Return list of available sensors and their states. | def sensors(self):
"""Return list of available sensors and their states."""
return self.camdata.current_event_states | [
"def",
"sensors",
"(",
"self",
")",
":",
"return",
"self",
".",
"camdata",
".",
"current_event_states"
] | [
166,
4
] | [
168,
48
] | python | en | ['en', 'en', 'en'] | True |
HikvisionData.cam_id | (self) | Return device id. | Return device id. | def cam_id(self):
"""Return device id."""
return self.camdata.get_id | [
"def",
"cam_id",
"(",
"self",
")",
":",
"return",
"self",
".",
"camdata",
".",
"get_id"
] | [
171,
4
] | [
173,
34
] | python | en | ['es', 'mt', 'en'] | False |
HikvisionData.name | (self) | Return device name. | Return device name. | def name(self):
"""Return device name."""
return self._name | [
"def",
"name",
"(",
"self",
")",
":",
"return",
"self",
".",
"_name"
] | [
176,
4
] | [
178,
25
] | python | en | ['es', 'sl', 'en'] | False |
HikvisionData.type | (self) | Return device type. | Return device type. | def type(self):
"""Return device type."""
return self.camdata.get_type | [
"def",
"type",
"(",
"self",
")",
":",
"return",
"self",
".",
"camdata",
".",
"get_type"
] | [
181,
4
] | [
183,
36
] | python | en | ['es', 'sr', 'en'] | False |
HikvisionData.get_attributes | (self, sensor, channel) | Return attribute list for sensor/channel. | Return attribute list for sensor/channel. | def get_attributes(self, sensor, channel):
"""Return attribute list for sensor/channel."""
return self.camdata.fetch_attributes(sensor, channel) | [
"def",
"get_attributes",
"(",
"self",
",",
"sensor",
",",
"channel",
")",
":",
"return",
"self",
".",
"camdata",
".",
"fetch_attributes",
"(",
"sensor",
",",
"channel",
")"
] | [
185,
4
] | [
187,
61
] | python | en | ['en', 'no', 'en'] | True |
HikvisionBinarySensor.__init__ | (self, hass, sensor, channel, cam, delay) | Initialize the binary_sensor. | Initialize the binary_sensor. | def __init__(self, hass, sensor, channel, cam, delay):
"""Initialize the binary_sensor."""
self._hass = hass
self._cam = cam
self._sensor = sensor
self._channel = channel
if self._cam.type == "NVR":
self._name = f"{self._cam.name} {sensor} {channel}"
else:
self._name = f"{self._cam.name} {sensor}"
self._id = f"{self._cam.cam_id}.{sensor}.{channel}"
if delay is None:
self._delay = 0
else:
self._delay = delay
self._timer = None
# Register callback function with pyHik
self._cam.camdata.add_update_callback(self._update_callback, self._id) | [
"def",
"__init__",
"(",
"self",
",",
"hass",
",",
"sensor",
",",
"channel",
",",
"cam",
",",
"delay",
")",
":",
"self",
".",
"_hass",
"=",
"hass",
"self",
".",
"_cam",
"=",
"cam",
"self",
".",
"_sensor",
"=",
"sensor",
"self",
".",
"_channel",
"=",
"channel",
"if",
"self",
".",
"_cam",
".",
"type",
"==",
"\"NVR\"",
":",
"self",
".",
"_name",
"=",
"f\"{self._cam.name} {sensor} {channel}\"",
"else",
":",
"self",
".",
"_name",
"=",
"f\"{self._cam.name} {sensor}\"",
"self",
".",
"_id",
"=",
"f\"{self._cam.cam_id}.{sensor}.{channel}\"",
"if",
"delay",
"is",
"None",
":",
"self",
".",
"_delay",
"=",
"0",
"else",
":",
"self",
".",
"_delay",
"=",
"delay",
"self",
".",
"_timer",
"=",
"None",
"# Register callback function with pyHik",
"self",
".",
"_cam",
".",
"camdata",
".",
"add_update_callback",
"(",
"self",
".",
"_update_callback",
",",
"self",
".",
"_id",
")"
] | [
193,
4
] | [
215,
78
] | python | en | ['en', 'haw', 'en'] | True |
HikvisionBinarySensor._sensor_state | (self) | Extract sensor state. | Extract sensor state. | def _sensor_state(self):
"""Extract sensor state."""
return self._cam.get_attributes(self._sensor, self._channel)[0] | [
"def",
"_sensor_state",
"(",
"self",
")",
":",
"return",
"self",
".",
"_cam",
".",
"get_attributes",
"(",
"self",
".",
"_sensor",
",",
"self",
".",
"_channel",
")",
"[",
"0",
"]"
] | [
217,
4
] | [
219,
71
] | python | en | ['en', 'en', 'en'] | True |
HikvisionBinarySensor._sensor_last_update | (self) | Extract sensor last update time. | Extract sensor last update time. | def _sensor_last_update(self):
"""Extract sensor last update time."""
return self._cam.get_attributes(self._sensor, self._channel)[3] | [
"def",
"_sensor_last_update",
"(",
"self",
")",
":",
"return",
"self",
".",
"_cam",
".",
"get_attributes",
"(",
"self",
".",
"_sensor",
",",
"self",
".",
"_channel",
")",
"[",
"3",
"]"
] | [
221,
4
] | [
223,
71
] | python | en | ['es', 'nl', 'en'] | False |
HikvisionBinarySensor.name | (self) | Return the name of the Hikvision sensor. | Return the name of the Hikvision sensor. | def name(self):
"""Return the name of the Hikvision sensor."""
return self._name | [
"def",
"name",
"(",
"self",
")",
":",
"return",
"self",
".",
"_name"
] | [
226,
4
] | [
228,
25
] | python | en | ['en', 'sq', 'en'] | True |
HikvisionBinarySensor.unique_id | (self) | Return a unique ID. | Return a unique ID. | def unique_id(self):
"""Return a unique ID."""
return self._id | [
"def",
"unique_id",
"(",
"self",
")",
":",
"return",
"self",
".",
"_id"
] | [
231,
4
] | [
233,
23
] | python | ca | ['fr', 'ca', 'en'] | False |
HikvisionBinarySensor.is_on | (self) | Return true if sensor is on. | Return true if sensor is on. | def is_on(self):
"""Return true if sensor is on."""
return self._sensor_state() | [
"def",
"is_on",
"(",
"self",
")",
":",
"return",
"self",
".",
"_sensor_state",
"(",
")"
] | [
236,
4
] | [
238,
35
] | python | en | ['en', 'et', 'en'] | True |
HikvisionBinarySensor.device_class | (self) | Return the class of this sensor, from DEVICE_CLASSES. | Return the class of this sensor, from DEVICE_CLASSES. | def device_class(self):
"""Return the class of this sensor, from DEVICE_CLASSES."""
try:
return DEVICE_CLASS_MAP[self._sensor]
except KeyError:
# Sensor must be unknown to us, add as generic
return None | [
"def",
"device_class",
"(",
"self",
")",
":",
"try",
":",
"return",
"DEVICE_CLASS_MAP",
"[",
"self",
".",
"_sensor",
"]",
"except",
"KeyError",
":",
"# Sensor must be unknown to us, add as generic",
"return",
"None"
] | [
241,
4
] | [
247,
23
] | python | en | ['en', 'en', 'en'] | True |
HikvisionBinarySensor.should_poll | (self) | No polling needed. | No polling needed. | def should_poll(self):
"""No polling needed."""
return False | [
"def",
"should_poll",
"(",
"self",
")",
":",
"return",
"False"
] | [
250,
4
] | [
252,
20
] | python | en | ['en', 'en', 'en'] | True |
HikvisionBinarySensor.device_state_attributes | (self) | Return the state attributes. | Return the state attributes. | def device_state_attributes(self):
"""Return the state attributes."""
attr = {ATTR_LAST_TRIP_TIME: self._sensor_last_update()}
if self._delay != 0:
attr[ATTR_DELAY] = self._delay
return attr | [
"def",
"device_state_attributes",
"(",
"self",
")",
":",
"attr",
"=",
"{",
"ATTR_LAST_TRIP_TIME",
":",
"self",
".",
"_sensor_last_update",
"(",
")",
"}",
"if",
"self",
".",
"_delay",
"!=",
"0",
":",
"attr",
"[",
"ATTR_DELAY",
"]",
"=",
"self",
".",
"_delay",
"return",
"attr"
] | [
255,
4
] | [
262,
19
] | python | en | ['en', 'en', 'en'] | True |
HikvisionBinarySensor._update_callback | (self, msg) | Update the sensor's state, if needed. | Update the sensor's state, if needed. | def _update_callback(self, msg):
"""Update the sensor's state, if needed."""
_LOGGER.debug("Callback signal from: %s", msg)
if self._delay > 0 and not self.is_on:
# Set timer to wait until updating the state
def _delay_update(now):
"""Timer callback for sensor update."""
_LOGGER.debug(
"%s Called delayed (%ssec) update", self._name, self._delay
)
self.schedule_update_ha_state()
self._timer = None
if self._timer is not None:
self._timer()
self._timer = None
self._timer = track_point_in_utc_time(
self._hass, _delay_update, utcnow() + timedelta(seconds=self._delay)
)
elif self._delay > 0 and self.is_on:
# For delayed sensors kill any callbacks on true events and update
if self._timer is not None:
self._timer()
self._timer = None
self.schedule_update_ha_state()
else:
self.schedule_update_ha_state() | [
"def",
"_update_callback",
"(",
"self",
",",
"msg",
")",
":",
"_LOGGER",
".",
"debug",
"(",
"\"Callback signal from: %s\"",
",",
"msg",
")",
"if",
"self",
".",
"_delay",
">",
"0",
"and",
"not",
"self",
".",
"is_on",
":",
"# Set timer to wait until updating the state",
"def",
"_delay_update",
"(",
"now",
")",
":",
"\"\"\"Timer callback for sensor update.\"\"\"",
"_LOGGER",
".",
"debug",
"(",
"\"%s Called delayed (%ssec) update\"",
",",
"self",
".",
"_name",
",",
"self",
".",
"_delay",
")",
"self",
".",
"schedule_update_ha_state",
"(",
")",
"self",
".",
"_timer",
"=",
"None",
"if",
"self",
".",
"_timer",
"is",
"not",
"None",
":",
"self",
".",
"_timer",
"(",
")",
"self",
".",
"_timer",
"=",
"None",
"self",
".",
"_timer",
"=",
"track_point_in_utc_time",
"(",
"self",
".",
"_hass",
",",
"_delay_update",
",",
"utcnow",
"(",
")",
"+",
"timedelta",
"(",
"seconds",
"=",
"self",
".",
"_delay",
")",
")",
"elif",
"self",
".",
"_delay",
">",
"0",
"and",
"self",
".",
"is_on",
":",
"# For delayed sensors kill any callbacks on true events and update",
"if",
"self",
".",
"_timer",
"is",
"not",
"None",
":",
"self",
".",
"_timer",
"(",
")",
"self",
".",
"_timer",
"=",
"None",
"self",
".",
"schedule_update_ha_state",
"(",
")",
"else",
":",
"self",
".",
"schedule_update_ha_state",
"(",
")"
] | [
264,
4
] | [
295,
43
] | python | en | ['en', 'en', 'en'] | True |
patch_hass_state | (hass) | Mock the hass.state to be not_running. | Mock the hass.state to be not_running. | def patch_hass_state(hass):
"""Mock the hass.state to be not_running."""
hass.state = core.CoreState.not_running | [
"def",
"patch_hass_state",
"(",
"hass",
")",
":",
"hass",
".",
"state",
"=",
"core",
".",
"CoreState",
".",
"not_running"
] | [
17,
0
] | [
19,
43
] | python | en | ['en', 'en', 'en'] | True |
test_set_up_oauth_remote_url | (hass, aioclient_mock) | Test we set up Almond to connect to HA if we have external url. | Test we set up Almond to connect to HA if we have external url. | async def test_set_up_oauth_remote_url(hass, aioclient_mock):
"""Test we set up Almond to connect to HA if we have external url."""
entry = MockConfigEntry(
domain="almond",
data={
"type": const.TYPE_OAUTH2,
"auth_implementation": "local",
"host": "http://localhost:9999",
"token": {"expires_at": time() + 1000, "access_token": "abcd"},
},
)
entry.add_to_hass(hass)
with patch(
"homeassistant.helpers.config_entry_oauth2_flow.async_get_config_entry_implementation",
):
assert await async_setup_component(hass, "almond", {})
assert entry.state == config_entries.ENTRY_STATE_LOADED
hass.config.components.add("cloud")
with patch("homeassistant.components.almond.ALMOND_SETUP_DELAY", 0), patch(
"homeassistant.helpers.network.get_url",
return_value="https://example.nabu.casa",
), patch("pyalmond.WebAlmondAPI.async_create_device") as mock_create_device:
hass.bus.async_fire(EVENT_HOMEASSISTANT_START)
await hass.async_block_till_done()
async_fire_time_changed(hass, utcnow())
await hass.async_block_till_done()
assert len(mock_create_device.mock_calls) == 1 | [
"async",
"def",
"test_set_up_oauth_remote_url",
"(",
"hass",
",",
"aioclient_mock",
")",
":",
"entry",
"=",
"MockConfigEntry",
"(",
"domain",
"=",
"\"almond\"",
",",
"data",
"=",
"{",
"\"type\"",
":",
"const",
".",
"TYPE_OAUTH2",
",",
"\"auth_implementation\"",
":",
"\"local\"",
",",
"\"host\"",
":",
"\"http://localhost:9999\"",
",",
"\"token\"",
":",
"{",
"\"expires_at\"",
":",
"time",
"(",
")",
"+",
"1000",
",",
"\"access_token\"",
":",
"\"abcd\"",
"}",
",",
"}",
",",
")",
"entry",
".",
"add_to_hass",
"(",
"hass",
")",
"with",
"patch",
"(",
"\"homeassistant.helpers.config_entry_oauth2_flow.async_get_config_entry_implementation\"",
",",
")",
":",
"assert",
"await",
"async_setup_component",
"(",
"hass",
",",
"\"almond\"",
",",
"{",
"}",
")",
"assert",
"entry",
".",
"state",
"==",
"config_entries",
".",
"ENTRY_STATE_LOADED",
"hass",
".",
"config",
".",
"components",
".",
"add",
"(",
"\"cloud\"",
")",
"with",
"patch",
"(",
"\"homeassistant.components.almond.ALMOND_SETUP_DELAY\"",
",",
"0",
")",
",",
"patch",
"(",
"\"homeassistant.helpers.network.get_url\"",
",",
"return_value",
"=",
"\"https://example.nabu.casa\"",
",",
")",
",",
"patch",
"(",
"\"pyalmond.WebAlmondAPI.async_create_device\"",
")",
"as",
"mock_create_device",
":",
"hass",
".",
"bus",
".",
"async_fire",
"(",
"EVENT_HOMEASSISTANT_START",
")",
"await",
"hass",
".",
"async_block_till_done",
"(",
")",
"async_fire_time_changed",
"(",
"hass",
",",
"utcnow",
"(",
")",
")",
"await",
"hass",
".",
"async_block_till_done",
"(",
")",
"assert",
"len",
"(",
"mock_create_device",
".",
"mock_calls",
")",
"==",
"1"
] | [
22,
0
] | [
52,
50
] | python | en | ['en', 'en', 'en'] | True |
test_set_up_oauth_no_external_url | (hass, aioclient_mock) | Test we do not set up Almond to connect to HA if we have no external url. | Test we do not set up Almond to connect to HA if we have no external url. | async def test_set_up_oauth_no_external_url(hass, aioclient_mock):
"""Test we do not set up Almond to connect to HA if we have no external url."""
entry = MockConfigEntry(
domain="almond",
data={
"type": const.TYPE_OAUTH2,
"auth_implementation": "local",
"host": "http://localhost:9999",
"token": {"expires_at": time() + 1000, "access_token": "abcd"},
},
)
entry.add_to_hass(hass)
with patch(
"homeassistant.helpers.config_entry_oauth2_flow.async_get_config_entry_implementation",
), patch("pyalmond.WebAlmondAPI.async_create_device") as mock_create_device:
assert await async_setup_component(hass, "almond", {})
assert entry.state == config_entries.ENTRY_STATE_LOADED
assert len(mock_create_device.mock_calls) == 0 | [
"async",
"def",
"test_set_up_oauth_no_external_url",
"(",
"hass",
",",
"aioclient_mock",
")",
":",
"entry",
"=",
"MockConfigEntry",
"(",
"domain",
"=",
"\"almond\"",
",",
"data",
"=",
"{",
"\"type\"",
":",
"const",
".",
"TYPE_OAUTH2",
",",
"\"auth_implementation\"",
":",
"\"local\"",
",",
"\"host\"",
":",
"\"http://localhost:9999\"",
",",
"\"token\"",
":",
"{",
"\"expires_at\"",
":",
"time",
"(",
")",
"+",
"1000",
",",
"\"access_token\"",
":",
"\"abcd\"",
"}",
",",
"}",
",",
")",
"entry",
".",
"add_to_hass",
"(",
"hass",
")",
"with",
"patch",
"(",
"\"homeassistant.helpers.config_entry_oauth2_flow.async_get_config_entry_implementation\"",
",",
")",
",",
"patch",
"(",
"\"pyalmond.WebAlmondAPI.async_create_device\"",
")",
"as",
"mock_create_device",
":",
"assert",
"await",
"async_setup_component",
"(",
"hass",
",",
"\"almond\"",
",",
"{",
"}",
")",
"assert",
"entry",
".",
"state",
"==",
"config_entries",
".",
"ENTRY_STATE_LOADED",
"assert",
"len",
"(",
"mock_create_device",
".",
"mock_calls",
")",
"==",
"0"
] | [
55,
0
] | [
74,
50
] | python | en | ['en', 'en', 'en'] | True |
test_set_up_hassio | (hass, aioclient_mock) | Test we do not set up Almond to connect to HA if we use Hass.io. | Test we do not set up Almond to connect to HA if we use Hass.io. | async def test_set_up_hassio(hass, aioclient_mock):
"""Test we do not set up Almond to connect to HA if we use Hass.io."""
entry = MockConfigEntry(
domain="almond",
data={
"is_hassio": True,
"type": const.TYPE_LOCAL,
"host": "http://localhost:9999",
},
)
entry.add_to_hass(hass)
with patch("pyalmond.WebAlmondAPI.async_create_device") as mock_create_device:
assert await async_setup_component(hass, "almond", {})
assert entry.state == config_entries.ENTRY_STATE_LOADED
assert len(mock_create_device.mock_calls) == 0 | [
"async",
"def",
"test_set_up_hassio",
"(",
"hass",
",",
"aioclient_mock",
")",
":",
"entry",
"=",
"MockConfigEntry",
"(",
"domain",
"=",
"\"almond\"",
",",
"data",
"=",
"{",
"\"is_hassio\"",
":",
"True",
",",
"\"type\"",
":",
"const",
".",
"TYPE_LOCAL",
",",
"\"host\"",
":",
"\"http://localhost:9999\"",
",",
"}",
",",
")",
"entry",
".",
"add_to_hass",
"(",
"hass",
")",
"with",
"patch",
"(",
"\"pyalmond.WebAlmondAPI.async_create_device\"",
")",
"as",
"mock_create_device",
":",
"assert",
"await",
"async_setup_component",
"(",
"hass",
",",
"\"almond\"",
",",
"{",
"}",
")",
"assert",
"entry",
".",
"state",
"==",
"config_entries",
".",
"ENTRY_STATE_LOADED",
"assert",
"len",
"(",
"mock_create_device",
".",
"mock_calls",
")",
"==",
"0"
] | [
77,
0
] | [
93,
50
] | python | en | ['en', 'en', 'en'] | True |
test_set_up_local | (hass, aioclient_mock) | Test we do not set up Almond to connect to HA if we use local. | Test we do not set up Almond to connect to HA if we use local. | async def test_set_up_local(hass, aioclient_mock):
"""Test we do not set up Almond to connect to HA if we use local."""
# Set up an internal URL, as Almond won't be set up if there is no URL available
await async_process_ha_core_config(
hass,
{"internal_url": "https://192.168.0.1"},
)
entry = MockConfigEntry(
domain="almond",
data={"type": const.TYPE_LOCAL, "host": "http://localhost:9999"},
)
entry.add_to_hass(hass)
with patch("pyalmond.WebAlmondAPI.async_create_device") as mock_create_device:
assert await async_setup_component(hass, "almond", {})
assert entry.state == config_entries.ENTRY_STATE_LOADED
assert len(mock_create_device.mock_calls) == 1 | [
"async",
"def",
"test_set_up_local",
"(",
"hass",
",",
"aioclient_mock",
")",
":",
"# Set up an internal URL, as Almond won't be set up if there is no URL available",
"await",
"async_process_ha_core_config",
"(",
"hass",
",",
"{",
"\"internal_url\"",
":",
"\"https://192.168.0.1\"",
"}",
",",
")",
"entry",
"=",
"MockConfigEntry",
"(",
"domain",
"=",
"\"almond\"",
",",
"data",
"=",
"{",
"\"type\"",
":",
"const",
".",
"TYPE_LOCAL",
",",
"\"host\"",
":",
"\"http://localhost:9999\"",
"}",
",",
")",
"entry",
".",
"add_to_hass",
"(",
"hass",
")",
"with",
"patch",
"(",
"\"pyalmond.WebAlmondAPI.async_create_device\"",
")",
"as",
"mock_create_device",
":",
"assert",
"await",
"async_setup_component",
"(",
"hass",
",",
"\"almond\"",
",",
"{",
"}",
")",
"assert",
"entry",
".",
"state",
"==",
"config_entries",
".",
"ENTRY_STATE_LOADED",
"assert",
"len",
"(",
"mock_create_device",
".",
"mock_calls",
")",
"==",
"1"
] | [
96,
0
] | [
115,
50
] | python | en | ['en', 'en', 'en'] | True |
async_setup_platform | (hass, config, add_entities, discovery_info=None) | Set up the Binary Sensor platform to w800rf32. | Set up the Binary Sensor platform to w800rf32. | async def async_setup_platform(hass, config, add_entities, discovery_info=None):
"""Set up the Binary Sensor platform to w800rf32."""
binary_sensors = []
# device_id --> "c1 or a3" X10 device. entity (type dictionary)
# --> name, device_class etc
for device_id, entity in config[CONF_DEVICES].items():
_LOGGER.debug(
"Add %s w800rf32.binary_sensor (class %s)",
entity[CONF_NAME],
entity.get(CONF_DEVICE_CLASS),
)
device = W800rf32BinarySensor(
device_id,
entity.get(CONF_NAME),
entity.get(CONF_DEVICE_CLASS),
entity.get(CONF_OFF_DELAY),
)
binary_sensors.append(device)
add_entities(binary_sensors) | [
"async",
"def",
"async_setup_platform",
"(",
"hass",
",",
"config",
",",
"add_entities",
",",
"discovery_info",
"=",
"None",
")",
":",
"binary_sensors",
"=",
"[",
"]",
"# device_id --> \"c1 or a3\" X10 device. entity (type dictionary)",
"# --> name, device_class etc",
"for",
"device_id",
",",
"entity",
"in",
"config",
"[",
"CONF_DEVICES",
"]",
".",
"items",
"(",
")",
":",
"_LOGGER",
".",
"debug",
"(",
"\"Add %s w800rf32.binary_sensor (class %s)\"",
",",
"entity",
"[",
"CONF_NAME",
"]",
",",
"entity",
".",
"get",
"(",
"CONF_DEVICE_CLASS",
")",
",",
")",
"device",
"=",
"W800rf32BinarySensor",
"(",
"device_id",
",",
"entity",
".",
"get",
"(",
"CONF_NAME",
")",
",",
"entity",
".",
"get",
"(",
"CONF_DEVICE_CLASS",
")",
",",
"entity",
".",
"get",
"(",
"CONF_OFF_DELAY",
")",
",",
")",
"binary_sensors",
".",
"append",
"(",
"device",
")",
"add_entities",
"(",
"binary_sensors",
")"
] | [
41,
0
] | [
63,
32
] | python | en | ['en', 'haw', 'en'] | True |
W800rf32BinarySensor.__init__ | (self, device_id, name, device_class=None, off_delay=None) | Initialize the w800rf32 sensor. | Initialize the w800rf32 sensor. | def __init__(self, device_id, name, device_class=None, off_delay=None):
"""Initialize the w800rf32 sensor."""
self._signal = W800RF32_DEVICE.format(device_id)
self._name = name
self._device_class = device_class
self._off_delay = off_delay
self._state = False
self._delay_listener = None | [
"def",
"__init__",
"(",
"self",
",",
"device_id",
",",
"name",
",",
"device_class",
"=",
"None",
",",
"off_delay",
"=",
"None",
")",
":",
"self",
".",
"_signal",
"=",
"W800RF32_DEVICE",
".",
"format",
"(",
"device_id",
")",
"self",
".",
"_name",
"=",
"name",
"self",
".",
"_device_class",
"=",
"device_class",
"self",
".",
"_off_delay",
"=",
"off_delay",
"self",
".",
"_state",
"=",
"False",
"self",
".",
"_delay_listener",
"=",
"None"
] | [
69,
4
] | [
76,
35
] | python | en | ['en', 'pl', 'en'] | True |
W800rf32BinarySensor._off_delay_listener | (self, now) | Switch device off after a delay. | Switch device off after a delay. | def _off_delay_listener(self, now):
"""Switch device off after a delay."""
self._delay_listener = None
self.update_state(False) | [
"def",
"_off_delay_listener",
"(",
"self",
",",
"now",
")",
":",
"self",
".",
"_delay_listener",
"=",
"None",
"self",
".",
"update_state",
"(",
"False",
")"
] | [
79,
4
] | [
82,
32
] | python | en | ['en', 'en', 'en'] | True |
W800rf32BinarySensor.name | (self) | Return the device name. | Return the device name. | def name(self):
"""Return the device name."""
return self._name | [
"def",
"name",
"(",
"self",
")",
":",
"return",
"self",
".",
"_name"
] | [
85,
4
] | [
87,
25
] | python | en | ['en', 'en', 'en'] | True |
W800rf32BinarySensor.should_poll | (self) | No polling needed. | No polling needed. | def should_poll(self):
"""No polling needed."""
return False | [
"def",
"should_poll",
"(",
"self",
")",
":",
"return",
"False"
] | [
90,
4
] | [
92,
20
] | python | en | ['en', 'en', 'en'] | True |
W800rf32BinarySensor.device_class | (self) | Return the sensor class. | Return the sensor class. | def device_class(self):
"""Return the sensor class."""
return self._device_class | [
"def",
"device_class",
"(",
"self",
")",
":",
"return",
"self",
".",
"_device_class"
] | [
95,
4
] | [
97,
33
] | python | en | ['en', 'sq', 'en'] | True |
W800rf32BinarySensor.is_on | (self) | Return true if the sensor state is True. | Return true if the sensor state is True. | def is_on(self):
"""Return true if the sensor state is True."""
return self._state | [
"def",
"is_on",
"(",
"self",
")",
":",
"return",
"self",
".",
"_state"
] | [
100,
4
] | [
102,
26
] | python | en | ['en', 'mt', 'en'] | True |
W800rf32BinarySensor.binary_sensor_update | (self, event) | Call for control updates from the w800rf32 gateway. | Call for control updates from the w800rf32 gateway. | def binary_sensor_update(self, event):
"""Call for control updates from the w800rf32 gateway."""
if not isinstance(event, w800.W800rf32Event):
return
dev_id = event.device
command = event.command
_LOGGER.debug(
"BinarySensor update (Device ID: %s Command %s ...)", dev_id, command
)
# Update the w800rf32 device state
if command in ("On", "Off"):
is_on = command == "On"
self.update_state(is_on)
if self.is_on and self._off_delay is not None and self._delay_listener is None:
self._delay_listener = evt.async_track_point_in_time(
self.hass, self._off_delay_listener, dt_util.utcnow() + self._off_delay
) | [
"def",
"binary_sensor_update",
"(",
"self",
",",
"event",
")",
":",
"if",
"not",
"isinstance",
"(",
"event",
",",
"w800",
".",
"W800rf32Event",
")",
":",
"return",
"dev_id",
"=",
"event",
".",
"device",
"command",
"=",
"event",
".",
"command",
"_LOGGER",
".",
"debug",
"(",
"\"BinarySensor update (Device ID: %s Command %s ...)\"",
",",
"dev_id",
",",
"command",
")",
"# Update the w800rf32 device state",
"if",
"command",
"in",
"(",
"\"On\"",
",",
"\"Off\"",
")",
":",
"is_on",
"=",
"command",
"==",
"\"On\"",
"self",
".",
"update_state",
"(",
"is_on",
")",
"if",
"self",
".",
"is_on",
"and",
"self",
".",
"_off_delay",
"is",
"not",
"None",
"and",
"self",
".",
"_delay_listener",
"is",
"None",
":",
"self",
".",
"_delay_listener",
"=",
"evt",
".",
"async_track_point_in_time",
"(",
"self",
".",
"hass",
",",
"self",
".",
"_off_delay_listener",
",",
"dt_util",
".",
"utcnow",
"(",
")",
"+",
"self",
".",
"_off_delay",
")"
] | [
105,
4
] | [
127,
13
] | python | en | ['en', 'en', 'en'] | True |
W800rf32BinarySensor.update_state | (self, state) | Update the state of the device. | Update the state of the device. | def update_state(self, state):
"""Update the state of the device."""
self._state = state
self.async_write_ha_state() | [
"def",
"update_state",
"(",
"self",
",",
"state",
")",
":",
"self",
".",
"_state",
"=",
"state",
"self",
".",
"async_write_ha_state",
"(",
")"
] | [
129,
4
] | [
132,
35
] | python | en | ['en', 'en', 'en'] | True |
W800rf32BinarySensor.async_added_to_hass | (self) | Register update callback. | Register update callback. | async def async_added_to_hass(self):
"""Register update callback."""
async_dispatcher_connect(self.hass, self._signal, self.binary_sensor_update) | [
"async",
"def",
"async_added_to_hass",
"(",
"self",
")",
":",
"async_dispatcher_connect",
"(",
"self",
".",
"hass",
",",
"self",
".",
"_signal",
",",
"self",
".",
"binary_sensor_update",
")"
] | [
134,
4
] | [
136,
84
] | python | en | ['fr', 'no', 'en'] | False |
GoalZeroFlowHandler.async_step_user | (self, user_input=None) | Handle a flow initiated by the user. | Handle a flow initiated by the user. | async def async_step_user(self, user_input=None):
"""Handle a flow initiated by the user."""
errors = {}
if user_input is not None:
host = user_input[CONF_HOST]
name = user_input[CONF_NAME]
if await self._async_endpoint_existed(host):
return self.async_abort(reason="already_configured")
try:
await self._async_try_connect(host)
except exceptions.ConnectError:
errors["base"] = "cannot_connect"
_LOGGER.error("Error connecting to device at %s", host)
except exceptions.InvalidHost:
errors["base"] = "invalid_host"
_LOGGER.error("Invalid host at %s", host)
except Exception: # pylint: disable=broad-except
_LOGGER.exception("Unexpected exception")
errors["base"] = "unknown"
else:
return self.async_create_entry(
title=name,
data={CONF_HOST: host, CONF_NAME: name},
)
user_input = user_input or {}
return self.async_show_form(
step_id="user",
data_schema=vol.Schema(
{
vol.Required(
CONF_HOST, default=user_input.get(CONF_HOST) or ""
): str,
vol.Optional(
CONF_NAME, default=user_input.get(CONF_NAME) or DEFAULT_NAME
): str,
}
),
errors=errors,
) | [
"async",
"def",
"async_step_user",
"(",
"self",
",",
"user_input",
"=",
"None",
")",
":",
"errors",
"=",
"{",
"}",
"if",
"user_input",
"is",
"not",
"None",
":",
"host",
"=",
"user_input",
"[",
"CONF_HOST",
"]",
"name",
"=",
"user_input",
"[",
"CONF_NAME",
"]",
"if",
"await",
"self",
".",
"_async_endpoint_existed",
"(",
"host",
")",
":",
"return",
"self",
".",
"async_abort",
"(",
"reason",
"=",
"\"already_configured\"",
")",
"try",
":",
"await",
"self",
".",
"_async_try_connect",
"(",
"host",
")",
"except",
"exceptions",
".",
"ConnectError",
":",
"errors",
"[",
"\"base\"",
"]",
"=",
"\"cannot_connect\"",
"_LOGGER",
".",
"error",
"(",
"\"Error connecting to device at %s\"",
",",
"host",
")",
"except",
"exceptions",
".",
"InvalidHost",
":",
"errors",
"[",
"\"base\"",
"]",
"=",
"\"invalid_host\"",
"_LOGGER",
".",
"error",
"(",
"\"Invalid host at %s\"",
",",
"host",
")",
"except",
"Exception",
":",
"# pylint: disable=broad-except",
"_LOGGER",
".",
"exception",
"(",
"\"Unexpected exception\"",
")",
"errors",
"[",
"\"base\"",
"]",
"=",
"\"unknown\"",
"else",
":",
"return",
"self",
".",
"async_create_entry",
"(",
"title",
"=",
"name",
",",
"data",
"=",
"{",
"CONF_HOST",
":",
"host",
",",
"CONF_NAME",
":",
"name",
"}",
",",
")",
"user_input",
"=",
"user_input",
"or",
"{",
"}",
"return",
"self",
".",
"async_show_form",
"(",
"step_id",
"=",
"\"user\"",
",",
"data_schema",
"=",
"vol",
".",
"Schema",
"(",
"{",
"vol",
".",
"Required",
"(",
"CONF_HOST",
",",
"default",
"=",
"user_input",
".",
"get",
"(",
"CONF_HOST",
")",
"or",
"\"\"",
")",
":",
"str",
",",
"vol",
".",
"Optional",
"(",
"CONF_NAME",
",",
"default",
"=",
"user_input",
".",
"get",
"(",
"CONF_NAME",
")",
"or",
"DEFAULT_NAME",
")",
":",
"str",
",",
"}",
")",
",",
"errors",
"=",
"errors",
",",
")"
] | [
23,
4
] | [
65,
9
] | python | en | ['en', 'en', 'en'] | True |
FloEntity.__init__ | (
self,
entity_type: str,
name: str,
device: FloDeviceDataUpdateCoordinator,
**kwargs,
) | Init Flo entity. | Init Flo entity. | def __init__(
self,
entity_type: str,
name: str,
device: FloDeviceDataUpdateCoordinator,
**kwargs,
):
"""Init Flo entity."""
self._unique_id: str = f"{device.mac_address}_{entity_type}"
self._name: str = name
self._device: FloDeviceDataUpdateCoordinator = device
self._state: Any = None | [
"def",
"__init__",
"(",
"self",
",",
"entity_type",
":",
"str",
",",
"name",
":",
"str",
",",
"device",
":",
"FloDeviceDataUpdateCoordinator",
",",
"*",
"*",
"kwargs",
",",
")",
":",
"self",
".",
"_unique_id",
":",
"str",
"=",
"f\"{device.mac_address}_{entity_type}\"",
"self",
".",
"_name",
":",
"str",
"=",
"name",
"self",
".",
"_device",
":",
"FloDeviceDataUpdateCoordinator",
"=",
"device",
"self",
".",
"_state",
":",
"Any",
"=",
"None"
] | [
14,
4
] | [
25,
31
] | python | es | ['es', 'zu', 'it'] | False |
FloEntity.name | (self) | Return Entity's default name. | Return Entity's default name. | def name(self) -> str:
"""Return Entity's default name."""
return self._name | [
"def",
"name",
"(",
"self",
")",
"->",
"str",
":",
"return",
"self",
".",
"_name"
] | [
28,
4
] | [
30,
25
] | python | en | ['es', 'fr', 'en'] | False |
FloEntity.unique_id | (self) | Return a unique ID. | Return a unique ID. | def unique_id(self) -> str:
"""Return a unique ID."""
return self._unique_id | [
"def",
"unique_id",
"(",
"self",
")",
"->",
"str",
":",
"return",
"self",
".",
"_unique_id"
] | [
33,
4
] | [
35,
30
] | python | ca | ['fr', 'ca', 'en'] | False |
FloEntity.device_info | (self) | Return a device description for device registry. | Return a device description for device registry. | def device_info(self) -> Dict[str, Any]:
"""Return a device description for device registry."""
return {
"identifiers": {(FLO_DOMAIN, self._device.id)},
"connections": {(CONNECTION_NETWORK_MAC, self._device.mac_address)},
"manufacturer": self._device.manufacturer,
"model": self._device.model,
"name": self._device.device_name,
"sw_version": self._device.firmware_version,
} | [
"def",
"device_info",
"(",
"self",
")",
"->",
"Dict",
"[",
"str",
",",
"Any",
"]",
":",
"return",
"{",
"\"identifiers\"",
":",
"{",
"(",
"FLO_DOMAIN",
",",
"self",
".",
"_device",
".",
"id",
")",
"}",
",",
"\"connections\"",
":",
"{",
"(",
"CONNECTION_NETWORK_MAC",
",",
"self",
".",
"_device",
".",
"mac_address",
")",
"}",
",",
"\"manufacturer\"",
":",
"self",
".",
"_device",
".",
"manufacturer",
",",
"\"model\"",
":",
"self",
".",
"_device",
".",
"model",
",",
"\"name\"",
":",
"self",
".",
"_device",
".",
"device_name",
",",
"\"sw_version\"",
":",
"self",
".",
"_device",
".",
"firmware_version",
",",
"}"
] | [
38,
4
] | [
47,
9
] | python | en | ['ro', 'fr', 'en'] | False |
FloEntity.available | (self) | Return True if device is available. | Return True if device is available. | def available(self) -> bool:
"""Return True if device is available."""
return self._device.available | [
"def",
"available",
"(",
"self",
")",
"->",
"bool",
":",
"return",
"self",
".",
"_device",
".",
"available"
] | [
50,
4
] | [
52,
37
] | python | en | ['en', 'en', 'en'] | True |
FloEntity.force_update | (self) | Force update this entity. | Force update this entity. | def force_update(self) -> bool:
"""Force update this entity."""
return False | [
"def",
"force_update",
"(",
"self",
")",
"->",
"bool",
":",
"return",
"False"
] | [
55,
4
] | [
57,
20
] | python | en | ['en', 'en', 'en'] | True |
FloEntity.should_poll | (self) | Poll state from device. | Poll state from device. | def should_poll(self) -> bool:
"""Poll state from device."""
return False | [
"def",
"should_poll",
"(",
"self",
")",
"->",
"bool",
":",
"return",
"False"
] | [
60,
4
] | [
62,
20
] | python | en | ['en', 'en', 'en'] | True |
FloEntity.async_update | (self) | Update Flo entity. | Update Flo entity. | async def async_update(self):
"""Update Flo entity."""
await self._device.async_request_refresh() | [
"async",
"def",
"async_update",
"(",
"self",
")",
":",
"await",
"self",
".",
"_device",
".",
"async_request_refresh",
"(",
")"
] | [
64,
4
] | [
66,
50
] | python | en | ['es', 'en', 'en'] | True |
FloEntity.async_added_to_hass | (self) | When entity is added to hass. | When entity is added to hass. | async def async_added_to_hass(self):
"""When entity is added to hass."""
self.async_on_remove(self._device.async_add_listener(self.async_write_ha_state)) | [
"async",
"def",
"async_added_to_hass",
"(",
"self",
")",
":",
"self",
".",
"async_on_remove",
"(",
"self",
".",
"_device",
".",
"async_add_listener",
"(",
"self",
".",
"async_write_ha_state",
")",
")"
] | [
68,
4
] | [
70,
88
] | python | en | ['en', 'en', 'en'] | True |
setup_platform | (hass, config, add_entities, discovery_info=None) | Set up the Sharp Aquos TV platform. | Set up the Sharp Aquos TV platform. | def setup_platform(hass, config, add_entities, discovery_info=None):
"""Set up the Sharp Aquos TV platform."""
name = config[CONF_NAME]
port = config[CONF_PORT]
username = config[CONF_USERNAME]
password = config[CONF_PASSWORD]
power_on_enabled = config["power_on_enabled"]
if discovery_info:
_LOGGER.debug("%s", discovery_info)
vals = discovery_info.split(":")
if len(vals) > 1:
port = vals[1]
host = vals[0]
remote = sharp_aquos_rc.TV(host, port, username, password, timeout=20)
add_entities([SharpAquosTVDevice(name, remote, power_on_enabled)])
return True
host = config[CONF_HOST]
remote = sharp_aquos_rc.TV(host, port, username, password, 15, 1)
add_entities([SharpAquosTVDevice(name, remote, power_on_enabled)])
return True | [
"def",
"setup_platform",
"(",
"hass",
",",
"config",
",",
"add_entities",
",",
"discovery_info",
"=",
"None",
")",
":",
"name",
"=",
"config",
"[",
"CONF_NAME",
"]",
"port",
"=",
"config",
"[",
"CONF_PORT",
"]",
"username",
"=",
"config",
"[",
"CONF_USERNAME",
"]",
"password",
"=",
"config",
"[",
"CONF_PASSWORD",
"]",
"power_on_enabled",
"=",
"config",
"[",
"\"power_on_enabled\"",
"]",
"if",
"discovery_info",
":",
"_LOGGER",
".",
"debug",
"(",
"\"%s\"",
",",
"discovery_info",
")",
"vals",
"=",
"discovery_info",
".",
"split",
"(",
"\":\"",
")",
"if",
"len",
"(",
"vals",
")",
">",
"1",
":",
"port",
"=",
"vals",
"[",
"1",
"]",
"host",
"=",
"vals",
"[",
"0",
"]",
"remote",
"=",
"sharp_aquos_rc",
".",
"TV",
"(",
"host",
",",
"port",
",",
"username",
",",
"password",
",",
"timeout",
"=",
"20",
")",
"add_entities",
"(",
"[",
"SharpAquosTVDevice",
"(",
"name",
",",
"remote",
",",
"power_on_enabled",
")",
"]",
")",
"return",
"True",
"host",
"=",
"config",
"[",
"CONF_HOST",
"]",
"remote",
"=",
"sharp_aquos_rc",
".",
"TV",
"(",
"host",
",",
"port",
",",
"username",
",",
"password",
",",
"15",
",",
"1",
")",
"add_entities",
"(",
"[",
"SharpAquosTVDevice",
"(",
"name",
",",
"remote",
",",
"power_on_enabled",
")",
"]",
")",
"return",
"True"
] | [
78,
0
] | [
102,
15
] | python | en | ['en', 'lv', 'en'] | True |
_retry | (func) | Handle query retries. | Handle query retries. | def _retry(func):
"""Handle query retries."""
def wrapper(obj, *args, **kwargs):
"""Wrap all query functions."""
update_retries = 5
while update_retries > 0:
try:
func(obj, *args, **kwargs)
break
except (OSError, TypeError, ValueError):
update_retries -= 1
if update_retries == 0:
obj.set_state(STATE_OFF)
return wrapper | [
"def",
"_retry",
"(",
"func",
")",
":",
"def",
"wrapper",
"(",
"obj",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"\"\"\"Wrap all query functions.\"\"\"",
"update_retries",
"=",
"5",
"while",
"update_retries",
">",
"0",
":",
"try",
":",
"func",
"(",
"obj",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"break",
"except",
"(",
"OSError",
",",
"TypeError",
",",
"ValueError",
")",
":",
"update_retries",
"-=",
"1",
"if",
"update_retries",
"==",
"0",
":",
"obj",
".",
"set_state",
"(",
"STATE_OFF",
")",
"return",
"wrapper"
] | [
105,
0
] | [
120,
18
] | python | en | ['fr', 'pt', 'en'] | False |
SharpAquosTVDevice.__init__ | (self, name, remote, power_on_enabled=False) | Initialize the aquos device. | Initialize the aquos device. | def __init__(self, name, remote, power_on_enabled=False):
"""Initialize the aquos device."""
self._supported_features = SUPPORT_SHARPTV
self._power_on_enabled = power_on_enabled
if self._power_on_enabled:
self._supported_features |= SUPPORT_TURN_ON
# Save a reference to the imported class
self._name = name
# Assume that the TV is not muted
self._muted = False
self._state = None
self._remote = remote
self._volume = 0
self._source = None
self._source_list = list(SOURCES.values()) | [
"def",
"__init__",
"(",
"self",
",",
"name",
",",
"remote",
",",
"power_on_enabled",
"=",
"False",
")",
":",
"self",
".",
"_supported_features",
"=",
"SUPPORT_SHARPTV",
"self",
".",
"_power_on_enabled",
"=",
"power_on_enabled",
"if",
"self",
".",
"_power_on_enabled",
":",
"self",
".",
"_supported_features",
"|=",
"SUPPORT_TURN_ON",
"# Save a reference to the imported class",
"self",
".",
"_name",
"=",
"name",
"# Assume that the TV is not muted",
"self",
".",
"_muted",
"=",
"False",
"self",
".",
"_state",
"=",
"None",
"self",
".",
"_remote",
"=",
"remote",
"self",
".",
"_volume",
"=",
"0",
"self",
".",
"_source",
"=",
"None",
"self",
".",
"_source_list",
"=",
"list",
"(",
"SOURCES",
".",
"values",
"(",
")",
")"
] | [
126,
4
] | [
140,
50
] | python | en | ['en', 'en', 'en'] | True |
SharpAquosTVDevice.set_state | (self, state) | Set TV state. | Set TV state. | def set_state(self, state):
"""Set TV state."""
self._state = state | [
"def",
"set_state",
"(",
"self",
",",
"state",
")",
":",
"self",
".",
"_state",
"=",
"state"
] | [
142,
4
] | [
144,
27
] | python | en | ['en', 'jv', 'en'] | True |
SharpAquosTVDevice.update | (self) | Retrieve the latest data. | Retrieve the latest data. | def update(self):
"""Retrieve the latest data."""
if self._remote.power() == 1:
self._state = STATE_ON
else:
self._state = STATE_OFF
# Set TV to be able to remotely power on
if self._power_on_enabled:
self._remote.power_on_command_settings(2)
else:
self._remote.power_on_command_settings(0)
# Get mute state
if self._remote.mute() == 2:
self._muted = False
else:
self._muted = True
# Get source
self._source = SOURCES.get(self._remote.input())
# Get volume
self._volume = self._remote.volume() / 60 | [
"def",
"update",
"(",
"self",
")",
":",
"if",
"self",
".",
"_remote",
".",
"power",
"(",
")",
"==",
"1",
":",
"self",
".",
"_state",
"=",
"STATE_ON",
"else",
":",
"self",
".",
"_state",
"=",
"STATE_OFF",
"# Set TV to be able to remotely power on",
"if",
"self",
".",
"_power_on_enabled",
":",
"self",
".",
"_remote",
".",
"power_on_command_settings",
"(",
"2",
")",
"else",
":",
"self",
".",
"_remote",
".",
"power_on_command_settings",
"(",
"0",
")",
"# Get mute state",
"if",
"self",
".",
"_remote",
".",
"mute",
"(",
")",
"==",
"2",
":",
"self",
".",
"_muted",
"=",
"False",
"else",
":",
"self",
".",
"_muted",
"=",
"True",
"# Get source",
"self",
".",
"_source",
"=",
"SOURCES",
".",
"get",
"(",
"self",
".",
"_remote",
".",
"input",
"(",
")",
")",
"# Get volume",
"self",
".",
"_volume",
"=",
"self",
".",
"_remote",
".",
"volume",
"(",
")",
"/",
"60"
] | [
147,
4
] | [
166,
49
] | python | en | ['en', 'ga', 'en'] | True |
SharpAquosTVDevice.name | (self) | Return the name of the device. | Return the name of the device. | def name(self):
"""Return the name of the device."""
return self._name | [
"def",
"name",
"(",
"self",
")",
":",
"return",
"self",
".",
"_name"
] | [
169,
4
] | [
171,
25
] | python | en | ['en', 'en', 'en'] | True |
SharpAquosTVDevice.state | (self) | Return the state of the device. | Return the state of the device. | def state(self):
"""Return the state of the device."""
return self._state | [
"def",
"state",
"(",
"self",
")",
":",
"return",
"self",
".",
"_state"
] | [
174,
4
] | [
176,
26
] | python | en | ['en', 'en', 'en'] | True |
SharpAquosTVDevice.source | (self) | Return the current source. | Return the current source. | def source(self):
"""Return the current source."""
return self._source | [
"def",
"source",
"(",
"self",
")",
":",
"return",
"self",
".",
"_source"
] | [
179,
4
] | [
181,
27
] | python | en | ['en', 'en', 'en'] | True |
SharpAquosTVDevice.source_list | (self) | Return the source list. | Return the source list. | def source_list(self):
"""Return the source list."""
return self._source_list | [
"def",
"source_list",
"(",
"self",
")",
":",
"return",
"self",
".",
"_source_list"
] | [
184,
4
] | [
186,
32
] | python | en | ['en', 'bg', 'en'] | True |
SharpAquosTVDevice.volume_level | (self) | Volume level of the media player (0..1). | Volume level of the media player (0..1). | def volume_level(self):
"""Volume level of the media player (0..1)."""
return self._volume | [
"def",
"volume_level",
"(",
"self",
")",
":",
"return",
"self",
".",
"_volume"
] | [
189,
4
] | [
191,
27
] | python | en | ['en', 'en', 'en'] | True |
SharpAquosTVDevice.is_volume_muted | (self) | Boolean if volume is currently muted. | Boolean if volume is currently muted. | def is_volume_muted(self):
"""Boolean if volume is currently muted."""
return self._muted | [
"def",
"is_volume_muted",
"(",
"self",
")",
":",
"return",
"self",
".",
"_muted"
] | [
194,
4
] | [
196,
26
] | python | en | ['en', 'en', 'en'] | True |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.