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
InputValidationError.__init__
(self, base: str)
Initialize with error base.
Initialize with error base.
def __init__(self, base: str): """Initialize with error base.""" super().__init__() self.base = base
[ "def", "__init__", "(", "self", ",", "base", ":", "str", ")", ":", "super", "(", ")", ".", "__init__", "(", ")", "self", ".", "base", "=", "base" ]
[ 69, 4 ]
[ 72, 24 ]
python
en
['en', 'en', 'en']
True
read_last_line
(file_name)
read last line of a file and return None if file not found
read last line of a file and return None if file not found
def read_last_line(file_name): '''read last line of a file and return None if file not found''' try: *_, last_line = open(file_name) return last_line.strip() except (FileNotFoundError, ValueError): return None
[ "def", "read_last_line", "(", "file_name", ")", ":", "try", ":", "*", "_", ",", "last_line", "=", "open", "(", "file_name", ")", "return", "last_line", ".", "strip", "(", ")", "except", "(", "FileNotFoundError", ",", "ValueError", ")", ":", "return", "None" ]
[ 28, 0 ]
[ 34, 19 ]
python
en
['en', 'en', 'en']
True
remove_files
(file_list)
remove a list of files
remove a list of files
def remove_files(file_list): '''remove a list of files''' for file_path in file_list: with contextlib.suppress(FileNotFoundError): os.remove(file_path)
[ "def", "remove_files", "(", "file_list", ")", ":", "for", "file_path", "in", "file_list", ":", "with", "contextlib", ".", "suppress", "(", "FileNotFoundError", ")", ":", "os", ".", "remove", "(", "file_path", ")" ]
[ 36, 0 ]
[ 40, 32 ]
python
en
['en', 'en', 'en']
True
get_yml_content
(file_path)
Load yaml file content
Load yaml file content
def get_yml_content(file_path): '''Load yaml file content''' with open(file_path, 'r') as file: return yaml.safe_load(file)
[ "def", "get_yml_content", "(", "file_path", ")", ":", "with", "open", "(", "file_path", ",", "'r'", ")", "as", "file", ":", "return", "yaml", ".", "safe_load", "(", "file", ")" ]
[ 42, 0 ]
[ 45, 35 ]
python
en
['tr', 'en', 'sw']
False
dump_yml_content
(file_path, content)
Dump yaml file content
Dump yaml file content
def dump_yml_content(file_path, content): '''Dump yaml file content''' with open(file_path, 'w') as file: file.write(yaml.safe_dump(content, default_flow_style=False))
[ "def", "dump_yml_content", "(", "file_path", ",", "content", ")", ":", "with", "open", "(", "file_path", ",", "'w'", ")", "as", "file", ":", "file", ".", "write", "(", "yaml", ".", "safe_dump", "(", "content", ",", "default_flow_style", "=", "False", ")", ")" ]
[ 47, 0 ]
[ 50, 69 ]
python
ja
['tr', 'ja', 'sw']
False
setup_experiment
(installed=True)
setup the experiment if nni is not installed
setup the experiment if nni is not installed
def setup_experiment(installed=True): '''setup the experiment if nni is not installed''' if not installed: os.environ['PATH'] = os.environ['PATH'] + ':' + os.getcwd() sdk_path = os.path.abspath('../src/sdk/pynni') cmd_path = os.path.abspath('../tools') pypath = os.environ.get('PYTHONPATH') if pypath: pypath = ':'.join([pypath, sdk_path, cmd_path]) else: pypath = ':'.join([sdk_path, cmd_path]) os.environ['PYTHONPATH'] = pypath
[ "def", "setup_experiment", "(", "installed", "=", "True", ")", ":", "if", "not", "installed", ":", "os", ".", "environ", "[", "'PATH'", "]", "=", "os", ".", "environ", "[", "'PATH'", "]", "+", "':'", "+", "os", ".", "getcwd", "(", ")", "sdk_path", "=", "os", ".", "path", ".", "abspath", "(", "'../src/sdk/pynni'", ")", "cmd_path", "=", "os", ".", "path", ".", "abspath", "(", "'../tools'", ")", "pypath", "=", "os", ".", "environ", ".", "get", "(", "'PYTHONPATH'", ")", "if", "pypath", ":", "pypath", "=", "':'", ".", "join", "(", "[", "pypath", ",", "sdk_path", ",", "cmd_path", "]", ")", "else", ":", "pypath", "=", "':'", ".", "join", "(", "[", "sdk_path", ",", "cmd_path", "]", ")", "os", ".", "environ", "[", "'PYTHONPATH'", "]", "=", "pypath" ]
[ 52, 0 ]
[ 63, 41 ]
python
en
['en', 'en', 'en']
True
get_experiment_dir
(experiment_url=None, experiment_id=None)
get experiment root directory
get experiment root directory
def get_experiment_dir(experiment_url=None, experiment_id=None): '''get experiment root directory''' assert any([experiment_url, experiment_id]) if experiment_id is None: experiment_id = get_experiment_id(experiment_url) return os.path.join(os.path.expanduser('~'), 'nni-experiments', experiment_id)
[ "def", "get_experiment_dir", "(", "experiment_url", "=", "None", ",", "experiment_id", "=", "None", ")", ":", "assert", "any", "(", "[", "experiment_url", ",", "experiment_id", "]", ")", "if", "experiment_id", "is", "None", ":", "experiment_id", "=", "get_experiment_id", "(", "experiment_url", ")", "return", "os", ".", "path", ".", "join", "(", "os", ".", "path", ".", "expanduser", "(", "'~'", ")", ",", "'nni-experiments'", ",", "experiment_id", ")" ]
[ 69, 0 ]
[ 74, 82 ]
python
en
['sq', 'en', 'en']
True
get_nni_log_dir
(experiment_url=None, experiment_id=None)
get nni's log directory from nni's experiment url
get nni's log directory from nni's experiment url
def get_nni_log_dir(experiment_url=None, experiment_id=None): '''get nni's log directory from nni's experiment url''' return os.path.join(get_experiment_dir(experiment_url, experiment_id), 'log')
[ "def", "get_nni_log_dir", "(", "experiment_url", "=", "None", ",", "experiment_id", "=", "None", ")", ":", "return", "os", ".", "path", ".", "join", "(", "get_experiment_dir", "(", "experiment_url", ",", "experiment_id", ")", ",", "'log'", ")" ]
[ 76, 0 ]
[ 78, 81 ]
python
en
['en', 'en', 'en']
True
get_nni_log_path
(experiment_url)
get nni's log path from nni's experiment url
get nni's log path from nni's experiment url
def get_nni_log_path(experiment_url): '''get nni's log path from nni's experiment url''' return os.path.join(get_nni_log_dir(experiment_url), 'nnimanager.log')
[ "def", "get_nni_log_path", "(", "experiment_url", ")", ":", "return", "os", ".", "path", ".", "join", "(", "get_nni_log_dir", "(", "experiment_url", ")", ",", "'nnimanager.log'", ")" ]
[ 80, 0 ]
[ 82, 74 ]
python
en
['en', 'en', 'en']
True
is_experiment_done
(nnimanager_log_path)
check if the experiment is done successfully
check if the experiment is done successfully
def is_experiment_done(nnimanager_log_path): '''check if the experiment is done successfully''' assert os.path.exists(nnimanager_log_path), 'Experiment starts failed' with open(nnimanager_log_path, 'r') as f: log_content = f.read() return EXPERIMENT_DONE_SIGNAL in log_content
[ "def", "is_experiment_done", "(", "nnimanager_log_path", ")", ":", "assert", "os", ".", "path", ".", "exists", "(", "nnimanager_log_path", ")", ",", "'Experiment starts failed'", "with", "open", "(", "nnimanager_log_path", ",", "'r'", ")", "as", "f", ":", "log_content", "=", "f", ".", "read", "(", ")", "return", "EXPERIMENT_DONE_SIGNAL", "in", "log_content" ]
[ 84, 0 ]
[ 91, 48 ]
python
en
['en', 'en', 'en']
True
get_trial_jobs
(trial_jobs_url, status=None)
Return failed trial jobs
Return failed trial jobs
def get_trial_jobs(trial_jobs_url, status=None): '''Return failed trial jobs''' trial_jobs = requests.get(trial_jobs_url).json() res = [] for trial_job in trial_jobs: if status is None or trial_job['status'] == status: res.append(trial_job) return res
[ "def", "get_trial_jobs", "(", "trial_jobs_url", ",", "status", "=", "None", ")", ":", "trial_jobs", "=", "requests", ".", "get", "(", "trial_jobs_url", ")", ".", "json", "(", ")", "res", "=", "[", "]", "for", "trial_job", "in", "trial_jobs", ":", "if", "status", "is", "None", "or", "trial_job", "[", "'status'", "]", "==", "status", ":", "res", ".", "append", "(", "trial_job", ")", "return", "res" ]
[ 104, 0 ]
[ 111, 14 ]
python
en
['en', 'gd', 'en']
True
get_failed_trial_jobs
(trial_jobs_url)
Return failed trial jobs
Return failed trial jobs
def get_failed_trial_jobs(trial_jobs_url): '''Return failed trial jobs''' return get_trial_jobs(trial_jobs_url, 'FAILED')
[ "def", "get_failed_trial_jobs", "(", "trial_jobs_url", ")", ":", "return", "get_trial_jobs", "(", "trial_jobs_url", ",", "'FAILED'", ")" ]
[ 113, 0 ]
[ 115, 51 ]
python
en
['en', 'gd', 'en']
True
deep_update
(source, overrides)
Update a nested dictionary or similar mapping. Modify ``source`` in place.
Update a nested dictionary or similar mapping.
def deep_update(source, overrides): """Update a nested dictionary or similar mapping. Modify ``source`` in place. """ for key, value in overrides.items(): if isinstance(value, collections.Mapping) and value: returned = deep_update(source.get(key, {}), value) source[key] = returned else: source[key] = overrides[key] return source
[ "def", "deep_update", "(", "source", ",", "overrides", ")", ":", "for", "key", ",", "value", "in", "overrides", ".", "items", "(", ")", ":", "if", "isinstance", "(", "value", ",", "collections", ".", "Mapping", ")", "and", "value", ":", "returned", "=", "deep_update", "(", "source", ".", "get", "(", "key", ",", "{", "}", ")", ",", "value", ")", "source", "[", "key", "]", "=", "returned", "else", ":", "source", "[", "key", "]", "=", "overrides", "[", "key", "]", "return", "source" ]
[ 148, 0 ]
[ 159, 17 ]
python
en
['en', 'en', 'en']
True
detect_port
(port)
Detect if the port is used
Detect if the port is used
def detect_port(port): '''Detect if the port is used''' socket_test = socket.socket(socket.AF_INET,socket.SOCK_STREAM) try: socket_test.connect(('127.0.0.1', int(port))) socket_test.close() return True except: return False
[ "def", "detect_port", "(", "port", ")", ":", "socket_test", "=", "socket", ".", "socket", "(", "socket", ".", "AF_INET", ",", "socket", ".", "SOCK_STREAM", ")", "try", ":", "socket_test", ".", "connect", "(", "(", "'127.0.0.1'", ",", "int", "(", "port", ")", ")", ")", "socket_test", ".", "close", "(", ")", "return", "True", "except", ":", "return", "False" ]
[ 161, 0 ]
[ 169, 20 ]
python
en
['en', 'en', 'en']
True
setup_platform
(hass, config, add_entities, discovery_info=None)
Set up the Xbox platform.
Set up the Xbox platform.
def setup_platform(hass, config, add_entities, discovery_info=None): """Set up the Xbox platform.""" api = Client(api_key=config[CONF_API_KEY]) entities = [] # request profile info to check api connection response = api.api_get("profile") if not response.ok: _LOGGER.error( "Can't setup X API connection. Check your account or " "api key on xapi.us. Code: %s Description: %s ", response.status_code, response.reason, ) return users = config[CONF_XUID] interval = timedelta(minutes=1 * len(users)) interval = config.get(CONF_SCAN_INTERVAL, interval) for xuid in users: gamercard = get_user_gamercard(api, xuid) if gamercard is None: continue entities.append(XboxSensor(api, xuid, gamercard, interval)) if entities: add_entities(entities, True)
[ "def", "setup_platform", "(", "hass", ",", "config", ",", "add_entities", ",", "discovery_info", "=", "None", ")", ":", "api", "=", "Client", "(", "api_key", "=", "config", "[", "CONF_API_KEY", "]", ")", "entities", "=", "[", "]", "# request profile info to check api connection", "response", "=", "api", ".", "api_get", "(", "\"profile\"", ")", "if", "not", "response", ".", "ok", ":", "_LOGGER", ".", "error", "(", "\"Can't setup X API connection. Check your account or \"", "\"api key on xapi.us. Code: %s Description: %s \"", ",", "response", ".", "status_code", ",", "response", ".", "reason", ",", ")", "return", "users", "=", "config", "[", "CONF_XUID", "]", "interval", "=", "timedelta", "(", "minutes", "=", "1", "*", "len", "(", "users", ")", ")", "interval", "=", "config", ".", "get", "(", "CONF_SCAN_INTERVAL", ",", "interval", ")", "for", "xuid", "in", "users", ":", "gamercard", "=", "get_user_gamercard", "(", "api", ",", "xuid", ")", "if", "gamercard", "is", "None", ":", "continue", "entities", ".", "append", "(", "XboxSensor", "(", "api", ",", "xuid", ",", "gamercard", ",", "interval", ")", ")", "if", "entities", ":", "add_entities", "(", "entities", ",", "True", ")" ]
[ 28, 0 ]
[ 56, 36 ]
python
en
['en', 'lv', 'en']
True
get_user_gamercard
(api, xuid)
Get profile info.
Get profile info.
def get_user_gamercard(api, xuid): """Get profile info.""" gamercard = api.gamer(gamertag="", xuid=xuid).get("gamercard") _LOGGER.debug("User gamercard: %s", gamercard) if gamercard.get("success", True) and gamercard.get("code") is None: return gamercard _LOGGER.error( "Can't get user profile %s. Error Code: %s Description: %s", xuid, gamercard.get("code", "unknown"), gamercard.get("description", "unknown"), ) return None
[ "def", "get_user_gamercard", "(", "api", ",", "xuid", ")", ":", "gamercard", "=", "api", ".", "gamer", "(", "gamertag", "=", "\"\"", ",", "xuid", "=", "xuid", ")", ".", "get", "(", "\"gamercard\"", ")", "_LOGGER", ".", "debug", "(", "\"User gamercard: %s\"", ",", "gamercard", ")", "if", "gamercard", ".", "get", "(", "\"success\"", ",", "True", ")", "and", "gamercard", ".", "get", "(", "\"code\"", ")", "is", "None", ":", "return", "gamercard", "_LOGGER", ".", "error", "(", "\"Can't get user profile %s. Error Code: %s Description: %s\"", ",", "xuid", ",", "gamercard", ".", "get", "(", "\"code\"", ",", "\"unknown\"", ")", ",", "gamercard", ".", "get", "(", "\"description\"", ",", "\"unknown\"", ")", ",", ")", "return", "None" ]
[ 59, 0 ]
[ 72, 15 ]
python
en
['en', 'it', 'en']
True
XboxSensor.__init__
(self, api, xuid, gamercard, interval)
Initialize the sensor.
Initialize the sensor.
def __init__(self, api, xuid, gamercard, interval): """Initialize the sensor.""" self._state = None self._presence = [] self._xuid = xuid self._api = api self._gamertag = gamercard["gamertag"] self._gamerscore = gamercard["gamerscore"] self._interval = interval self._picture = gamercard["gamerpicSmallSslImagePath"] self._tier = gamercard["tier"]
[ "def", "__init__", "(", "self", ",", "api", ",", "xuid", ",", "gamercard", ",", "interval", ")", ":", "self", ".", "_state", "=", "None", "self", ".", "_presence", "=", "[", "]", "self", ".", "_xuid", "=", "xuid", "self", ".", "_api", "=", "api", "self", ".", "_gamertag", "=", "gamercard", "[", "\"gamertag\"", "]", "self", ".", "_gamerscore", "=", "gamercard", "[", "\"gamerscore\"", "]", "self", ".", "_interval", "=", "interval", "self", ".", "_picture", "=", "gamercard", "[", "\"gamerpicSmallSslImagePath\"", "]", "self", ".", "_tier", "=", "gamercard", "[", "\"tier\"", "]" ]
[ 78, 4 ]
[ 88, 38 ]
python
en
['en', 'en', 'en']
True
XboxSensor.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._gamertag
[ "def", "name", "(", "self", ")", ":", "return", "self", ".", "_gamertag" ]
[ 91, 4 ]
[ 93, 29 ]
python
en
['en', 'mi', 'en']
True
XboxSensor.should_poll
(self)
Return False as this entity has custom polling.
Return False as this entity has custom polling.
def should_poll(self): """Return False as this entity has custom polling.""" return False
[ "def", "should_poll", "(", "self", ")", ":", "return", "False" ]
[ 96, 4 ]
[ 98, 20 ]
python
en
['en', 'hmn', 'en']
True
XboxSensor.state
(self)
Return the state of the sensor.
Return the state of the sensor.
def state(self): """Return the state of the sensor.""" return self._state
[ "def", "state", "(", "self", ")", ":", "return", "self", ".", "_state" ]
[ 101, 4 ]
[ 103, 26 ]
python
en
['en', 'en', 'en']
True
XboxSensor.device_state_attributes
(self)
Return the state attributes.
Return the state attributes.
def device_state_attributes(self): """Return the state attributes.""" attributes = {"gamerscore": self._gamerscore, "tier": self._tier} for device in self._presence: for title in device["titles"]: attributes[f'{device["type"]} {title["placement"]}'] = title["name"] return attributes
[ "def", "device_state_attributes", "(", "self", ")", ":", "attributes", "=", "{", "\"gamerscore\"", ":", "self", ".", "_gamerscore", ",", "\"tier\"", ":", "self", ".", "_tier", "}", "for", "device", "in", "self", ".", "_presence", ":", "for", "title", "in", "device", "[", "\"titles\"", "]", ":", "attributes", "[", "f'{device[\"type\"]} {title[\"placement\"]}'", "]", "=", "title", "[", "\"name\"", "]", "return", "attributes" ]
[ 106, 4 ]
[ 114, 25 ]
python
en
['en', 'en', 'en']
True
XboxSensor.entity_picture
(self)
Avatar of the account.
Avatar of the account.
def entity_picture(self): """Avatar of the account.""" return self._picture
[ "def", "entity_picture", "(", "self", ")", ":", "return", "self", ".", "_picture" ]
[ 117, 4 ]
[ 119, 28 ]
python
en
['en', 'en', 'en']
True
XboxSensor.icon
(self)
Return the icon to use in the frontend.
Return the icon to use in the frontend.
def icon(self): """Return the icon to use in the frontend.""" return ICON
[ "def", "icon", "(", "self", ")", ":", "return", "ICON" ]
[ 122, 4 ]
[ 124, 19 ]
python
en
['en', 'en', 'en']
True
XboxSensor.async_added_to_hass
(self)
Start custom polling.
Start custom polling.
async def async_added_to_hass(self): """Start custom polling.""" @callback def async_update(event_time=None): """Update the entity.""" self.async_schedule_update_ha_state(True) async_track_time_interval(self.hass, async_update, self._interval)
[ "async", "def", "async_added_to_hass", "(", "self", ")", ":", "@", "callback", "def", "async_update", "(", "event_time", "=", "None", ")", ":", "\"\"\"Update the entity.\"\"\"", "self", ".", "async_schedule_update_ha_state", "(", "True", ")", "async_track_time_interval", "(", "self", ".", "hass", ",", "async_update", ",", "self", ".", "_interval", ")" ]
[ 126, 4 ]
[ 134, 74 ]
python
en
['en', 'no', 'en']
True
XboxSensor.update
(self)
Update state data from Xbox API.
Update state data from Xbox API.
def update(self): """Update state data from Xbox API.""" presence = self._api.gamer(gamertag="", xuid=self._xuid).get("presence") _LOGGER.debug("User presence: %s", presence) self._state = presence["state"] self._presence = presence.get("devices", [])
[ "def", "update", "(", "self", ")", ":", "presence", "=", "self", ".", "_api", ".", "gamer", "(", "gamertag", "=", "\"\"", ",", "xuid", "=", "self", ".", "_xuid", ")", ".", "get", "(", "\"presence\"", ")", "_LOGGER", ".", "debug", "(", "\"User presence: %s\"", ",", "presence", ")", "self", ".", "_state", "=", "presence", "[", "\"state\"", "]", "self", ".", "_presence", "=", "presence", ".", "get", "(", "\"devices\"", ",", "[", "]", ")" ]
[ 136, 4 ]
[ 141, 52 ]
python
en
['en', 'en', 'en']
True
_call_nix_update
(pkg, version)
calls nix-update from nixpkgs root dir
calls nix-update from nixpkgs root dir
def _call_nix_update(pkg, version): """calls nix-update from nixpkgs root dir""" nixpkgs_path = pathlib.Path(__file__).parent / '../../../../' return subprocess.check_output(['nix-update', pkg, '--version', version], cwd=nixpkgs_path)
[ "def", "_call_nix_update", "(", "pkg", ",", "version", ")", ":", "nixpkgs_path", "=", "pathlib", ".", "Path", "(", "__file__", ")", ".", "parent", "/", "'../../../../'", "return", "subprocess", ".", "check_output", "(", "[", "'nix-update'", ",", "pkg", ",", "'--version'", ",", "version", "]", ",", "cwd", "=", "nixpkgs_path", ")" ]
[ 88, 0 ]
[ 91, 95 ]
python
en
['en', 'id', 'sw']
False
update_data
(rev: str)
Update data.nix
Update data.nix
def update_data(rev: str): """Update data.nix""" repo = GitLabRepo() if rev == 'latest': # filter out pre and re releases rev = next(filter(lambda x: not ('rc' in x or x.endswith('pre')), repo.tags)) logger.debug(f"Using rev {rev}") version = repo.rev2version(rev) logger.debug(f"Using version {version}") data_file_path = pathlib.Path(__file__).parent / 'data.json' data = repo.get_data(rev) with open(data_file_path.as_posix(), 'w') as f: json.dump(data, f, indent=2) f.write("\n")
[ "def", "update_data", "(", "rev", ":", "str", ")", ":", "repo", "=", "GitLabRepo", "(", ")", "if", "rev", "==", "'latest'", ":", "# filter out pre and re releases", "rev", "=", "next", "(", "filter", "(", "lambda", "x", ":", "not", "(", "'rc'", "in", "x", "or", "x", ".", "endswith", "(", "'pre'", ")", ")", ",", "repo", ".", "tags", ")", ")", "logger", ".", "debug", "(", "f\"Using rev {rev}\"", ")", "version", "=", "repo", ".", "rev2version", "(", "rev", ")", "logger", ".", "debug", "(", "f\"Using version {version}\"", ")", "data_file_path", "=", "pathlib", ".", "Path", "(", "__file__", ")", ".", "parent", "/", "'data.json'", "data", "=", "repo", ".", "get_data", "(", "rev", ")", "with", "open", "(", "data_file_path", ".", "as_posix", "(", ")", ",", "'w'", ")", "as", "f", ":", "json", ".", "dump", "(", "data", ",", "f", ",", "indent", "=", "2", ")", "f", ".", "write", "(", "\"\\n\"", ")" ]
[ 102, 0 ]
[ 120, 21 ]
python
co
['fr', 'co', 'sw']
False
update_rubyenv
()
Update rubyEnv
Update rubyEnv
def update_rubyenv(): """Update rubyEnv""" repo = GitLabRepo() rubyenv_dir = pathlib.Path(__file__).parent / f"rubyEnv" # load rev from data.json data = _get_data_json() rev = data['rev'] with open(rubyenv_dir / 'Gemfile.lock', 'w') as f: f.write(repo.get_file('Gemfile.lock', rev)) with open(rubyenv_dir / 'Gemfile', 'w') as f: original = repo.get_file('Gemfile', rev) f.write(re.sub(r".*mail-smtp_pool.*", "", original)) subprocess.check_output(['bundle', 'lock'], cwd=rubyenv_dir) subprocess.check_output(['bundix'], cwd=rubyenv_dir)
[ "def", "update_rubyenv", "(", ")", ":", "repo", "=", "GitLabRepo", "(", ")", "rubyenv_dir", "=", "pathlib", ".", "Path", "(", "__file__", ")", ".", "parent", "/", "f\"rubyEnv\"", "# load rev from data.json", "data", "=", "_get_data_json", "(", ")", "rev", "=", "data", "[", "'rev'", "]", "with", "open", "(", "rubyenv_dir", "/", "'Gemfile.lock'", ",", "'w'", ")", "as", "f", ":", "f", ".", "write", "(", "repo", ".", "get_file", "(", "'Gemfile.lock'", ",", "rev", ")", ")", "with", "open", "(", "rubyenv_dir", "/", "'Gemfile'", ",", "'w'", ")", "as", "f", ":", "original", "=", "repo", ".", "get_file", "(", "'Gemfile'", ",", "rev", ")", "f", ".", "write", "(", "re", ".", "sub", "(", "r\".*mail-smtp_pool.*\"", ",", "\"\"", ",", "original", ")", ")", "subprocess", ".", "check_output", "(", "[", "'bundle'", ",", "'lock'", "]", ",", "cwd", "=", "rubyenv_dir", ")", "subprocess", ".", "check_output", "(", "[", "'bundix'", "]", ",", "cwd", "=", "rubyenv_dir", ")" ]
[ 124, 0 ]
[ 140, 56 ]
python
en
['en', 'kk', 'sw']
False
update_yarnpkgs
()
Update yarnPkgs
Update yarnPkgs
def update_yarnpkgs(): """Update yarnPkgs""" repo = GitLabRepo() yarnpkgs_dir = pathlib.Path(__file__).parent # load rev from data.json data = _get_data_json() rev = data['rev'] with open(yarnpkgs_dir / 'yarn.lock', 'w') as f: f.write(repo.get_file('yarn.lock', rev)) with open(yarnpkgs_dir / 'yarnPkgs.nix', 'w') as f: subprocess.run(['yarn2nix'], cwd=yarnpkgs_dir, check=True, stdout=f) os.unlink(yarnpkgs_dir / 'yarn.lock')
[ "def", "update_yarnpkgs", "(", ")", ":", "repo", "=", "GitLabRepo", "(", ")", "yarnpkgs_dir", "=", "pathlib", ".", "Path", "(", "__file__", ")", ".", "parent", "# load rev from data.json", "data", "=", "_get_data_json", "(", ")", "rev", "=", "data", "[", "'rev'", "]", "with", "open", "(", "yarnpkgs_dir", "/", "'yarn.lock'", ",", "'w'", ")", "as", "f", ":", "f", ".", "write", "(", "repo", ".", "get_file", "(", "'yarn.lock'", ",", "rev", ")", ")", "with", "open", "(", "yarnpkgs_dir", "/", "'yarnPkgs.nix'", ",", "'w'", ")", "as", "f", ":", "subprocess", ".", "run", "(", "[", "'yarn2nix'", "]", ",", "cwd", "=", "yarnpkgs_dir", ",", "check", "=", "True", ",", "stdout", "=", "f", ")", "os", ".", "unlink", "(", "yarnpkgs_dir", "/", "'yarn.lock'", ")" ]
[ 144, 0 ]
[ 160, 41 ]
python
tr
['tr', 'fy', 'tr']
False
update_gitaly
()
Update gitaly
Update gitaly
def update_gitaly(): """Update gitaly""" data = _get_data_json() gitaly_server_version = data['passthru']['GITALY_SERVER_VERSION'] repo = GitLabRepo(repo='gitaly') gitaly_dir = pathlib.Path(__file__).parent / 'gitaly' for fn in ['Gemfile.lock', 'Gemfile']: with open(gitaly_dir / fn, 'w') as f: f.write(repo.get_file(f"ruby/{fn}", f"v{gitaly_server_version}")) subprocess.check_output(['bundle', 'lock'], cwd=gitaly_dir) subprocess.check_output(['bundix'], cwd=gitaly_dir) _call_nix_update('gitaly', gitaly_server_version)
[ "def", "update_gitaly", "(", ")", ":", "data", "=", "_get_data_json", "(", ")", "gitaly_server_version", "=", "data", "[", "'passthru'", "]", "[", "'GITALY_SERVER_VERSION'", "]", "repo", "=", "GitLabRepo", "(", "repo", "=", "'gitaly'", ")", "gitaly_dir", "=", "pathlib", ".", "Path", "(", "__file__", ")", ".", "parent", "/", "'gitaly'", "for", "fn", "in", "[", "'Gemfile.lock'", ",", "'Gemfile'", "]", ":", "with", "open", "(", "gitaly_dir", "/", "fn", ",", "'w'", ")", "as", "f", ":", "f", ".", "write", "(", "repo", ".", "get_file", "(", "f\"ruby/{fn}\"", ",", "f\"v{gitaly_server_version}\"", ")", ")", "subprocess", ".", "check_output", "(", "[", "'bundle'", ",", "'lock'", "]", ",", "cwd", "=", "gitaly_dir", ")", "subprocess", ".", "check_output", "(", "[", "'bundix'", "]", ",", "cwd", "=", "gitaly_dir", ")", "_call_nix_update", "(", "'gitaly'", ",", "gitaly_server_version", ")" ]
[ 164, 0 ]
[ 178, 53 ]
python
en
['en', 'no', 'en']
False
update_gitlab_shell
()
Update gitlab-shell
Update gitlab-shell
def update_gitlab_shell(): """Update gitlab-shell""" data = _get_data_json() gitlab_shell_version = data['passthru']['GITLAB_SHELL_VERSION'] _call_nix_update('gitlab-shell', gitlab_shell_version)
[ "def", "update_gitlab_shell", "(", ")", ":", "data", "=", "_get_data_json", "(", ")", "gitlab_shell_version", "=", "data", "[", "'passthru'", "]", "[", "'GITLAB_SHELL_VERSION'", "]", "_call_nix_update", "(", "'gitlab-shell'", ",", "gitlab_shell_version", ")" ]
[ 182, 0 ]
[ 186, 58 ]
python
en
['en', 'no', 'en']
False
update_gitlab_workhorse
()
Update gitlab-workhorse
Update gitlab-workhorse
def update_gitlab_workhorse(): """Update gitlab-workhorse""" data = _get_data_json() gitlab_workhorse_version = data['passthru']['GITLAB_WORKHORSE_VERSION'] _call_nix_update('gitlab-workhorse', gitlab_workhorse_version)
[ "def", "update_gitlab_workhorse", "(", ")", ":", "data", "=", "_get_data_json", "(", ")", "gitlab_workhorse_version", "=", "data", "[", "'passthru'", "]", "[", "'GITLAB_WORKHORSE_VERSION'", "]", "_call_nix_update", "(", "'gitlab-workhorse'", ",", "gitlab_workhorse_version", ")" ]
[ 190, 0 ]
[ 194, 66 ]
python
en
['en', 'de', 'en']
False
update_all
(ctx, rev: str)
Update all gitlab components to the latest stable release
Update all gitlab components to the latest stable release
def update_all(ctx, rev: str): """Update all gitlab components to the latest stable release""" ctx.invoke(update_data, rev=rev) ctx.invoke(update_rubyenv) ctx.invoke(update_yarnpkgs) ctx.invoke(update_gitaly) ctx.invoke(update_gitlab_shell) ctx.invoke(update_gitlab_workhorse)
[ "def", "update_all", "(", "ctx", ",", "rev", ":", "str", ")", ":", "ctx", ".", "invoke", "(", "update_data", ",", "rev", "=", "rev", ")", "ctx", ".", "invoke", "(", "update_rubyenv", ")", "ctx", ".", "invoke", "(", "update_yarnpkgs", ")", "ctx", ".", "invoke", "(", "update_gitaly", ")", "ctx", ".", "invoke", "(", "update_gitlab_shell", ")", "ctx", ".", "invoke", "(", "update_gitlab_workhorse", ")" ]
[ 200, 0 ]
[ 207, 39 ]
python
en
['en', 'en', 'en']
True
GitLabRepo.rev2version
(tag: str)
normalize a tag to a version number. This obviously isn't very smart if we don't pass something that looks like a tag :param tag: the tag to normalize :return: a normalized version number
normalize a tag to a version number. This obviously isn't very smart if we don't pass something that looks like a tag :param tag: the tag to normalize :return: a normalized version number
def rev2version(tag: str) -> str: """ normalize a tag to a version number. This obviously isn't very smart if we don't pass something that looks like a tag :param tag: the tag to normalize :return: a normalized version number """ # strip v prefix version = re.sub(r"^v", '', tag) # strip -ee suffix return re.sub(r"-ee$", '', version)
[ "def", "rev2version", "(", "tag", ":", "str", ")", "->", "str", ":", "# strip v prefix", "version", "=", "re", ".", "sub", "(", "r\"^v\"", ",", "''", ",", "tag", ")", "# strip -ee suffix", "return", "re", ".", "sub", "(", "r\"-ee$\"", ",", "''", ",", "version", ")" ]
[ 45, 4 ]
[ 55, 43 ]
python
en
['en', 'error', 'th']
False
GitLabRepo.get_file
(self, filepath, rev)
returns file contents at a given rev :param filepath: the path to the file, relative to the repo root :param rev: the rev to fetch at :return:
returns file contents at a given rev :param filepath: the path to the file, relative to the repo root :param rev: the rev to fetch at :return:
def get_file(self, filepath, rev): """ returns file contents at a given rev :param filepath: the path to the file, relative to the repo root :param rev: the rev to fetch at :return: """ return requests.get(self.url + f"/raw/{rev}/{filepath}").text
[ "def", "get_file", "(", "self", ",", "filepath", ",", "rev", ")", ":", "return", "requests", ".", "get", "(", "self", ".", "url", "+", "f\"/raw/{rev}/{filepath}\"", ")", ".", "text" ]
[ 57, 4 ]
[ 64, 69 ]
python
en
['en', 'error', 'th']
False
async_setup
(hass: HomeAssistant, config: Config)
Set up configured StarLine.
Set up configured StarLine.
async def async_setup(hass: HomeAssistant, config: Config) -> bool: """Set up configured StarLine.""" return True
[ "async", "def", "async_setup", "(", "hass", ":", "HomeAssistant", ",", "config", ":", "Config", ")", "->", "bool", ":", "return", "True" ]
[ 18, 0 ]
[ 20, 15 ]
python
en
['en', 'nl', 'en']
True
async_setup_entry
(hass: HomeAssistant, config_entry: ConfigEntry)
Set up the StarLine device from a config entry.
Set up the StarLine device from a config entry.
async def async_setup_entry(hass: HomeAssistant, config_entry: ConfigEntry) -> bool: """Set up the StarLine device from a config entry.""" account = StarlineAccount(hass, config_entry) await account.update() if not account.api.available: raise ConfigEntryNotReady if DOMAIN not in hass.data: hass.data[DOMAIN] = {} hass.data[DOMAIN][config_entry.entry_id] = account device_registry = await hass.helpers.device_registry.async_get_registry() for device in account.api.devices.values(): device_registry.async_get_or_create( config_entry_id=config_entry.entry_id, **account.device_info(device) ) for domain in PLATFORMS: hass.async_create_task( hass.config_entries.async_forward_entry_setup(config_entry, domain) ) async def async_set_scan_interval(call): """Service for set scan interval.""" options = dict(config_entry.options) options[CONF_SCAN_INTERVAL] = call.data[CONF_SCAN_INTERVAL] hass.config_entries.async_update_entry(entry=config_entry, options=options) hass.services.async_register(DOMAIN, SERVICE_UPDATE_STATE, account.update) hass.services.async_register( DOMAIN, SERVICE_SET_SCAN_INTERVAL, async_set_scan_interval, schema=vol.Schema( { vol.Required(CONF_SCAN_INTERVAL): vol.All( vol.Coerce(int), vol.Range(min=10) ) } ), ) config_entry.add_update_listener(async_options_updated) await async_options_updated(hass, config_entry) return True
[ "async", "def", "async_setup_entry", "(", "hass", ":", "HomeAssistant", ",", "config_entry", ":", "ConfigEntry", ")", "->", "bool", ":", "account", "=", "StarlineAccount", "(", "hass", ",", "config_entry", ")", "await", "account", ".", "update", "(", ")", "if", "not", "account", ".", "api", ".", "available", ":", "raise", "ConfigEntryNotReady", "if", "DOMAIN", "not", "in", "hass", ".", "data", ":", "hass", ".", "data", "[", "DOMAIN", "]", "=", "{", "}", "hass", ".", "data", "[", "DOMAIN", "]", "[", "config_entry", ".", "entry_id", "]", "=", "account", "device_registry", "=", "await", "hass", ".", "helpers", ".", "device_registry", ".", "async_get_registry", "(", ")", "for", "device", "in", "account", ".", "api", ".", "devices", ".", "values", "(", ")", ":", "device_registry", ".", "async_get_or_create", "(", "config_entry_id", "=", "config_entry", ".", "entry_id", ",", "*", "*", "account", ".", "device_info", "(", "device", ")", ")", "for", "domain", "in", "PLATFORMS", ":", "hass", ".", "async_create_task", "(", "hass", ".", "config_entries", ".", "async_forward_entry_setup", "(", "config_entry", ",", "domain", ")", ")", "async", "def", "async_set_scan_interval", "(", "call", ")", ":", "\"\"\"Service for set scan interval.\"\"\"", "options", "=", "dict", "(", "config_entry", ".", "options", ")", "options", "[", "CONF_SCAN_INTERVAL", "]", "=", "call", ".", "data", "[", "CONF_SCAN_INTERVAL", "]", "hass", ".", "config_entries", ".", "async_update_entry", "(", "entry", "=", "config_entry", ",", "options", "=", "options", ")", "hass", ".", "services", ".", "async_register", "(", "DOMAIN", ",", "SERVICE_UPDATE_STATE", ",", "account", ".", "update", ")", "hass", ".", "services", ".", "async_register", "(", "DOMAIN", ",", "SERVICE_SET_SCAN_INTERVAL", ",", "async_set_scan_interval", ",", "schema", "=", "vol", ".", "Schema", "(", "{", "vol", ".", "Required", "(", "CONF_SCAN_INTERVAL", ")", ":", "vol", ".", "All", "(", "vol", ".", "Coerce", "(", "int", ")", ",", "vol", ".", "Range", "(", "min", "=", "10", ")", ")", "}", ")", ",", ")", "config_entry", ".", "add_update_listener", "(", "async_options_updated", ")", "await", "async_options_updated", "(", "hass", ",", "config_entry", ")", "return", "True" ]
[ 23, 0 ]
[ 68, 15 ]
python
en
['en', 'en', 'en']
True
async_unload_entry
(hass: HomeAssistant, config_entry: ConfigEntry)
Unload a config entry.
Unload a config entry.
async def async_unload_entry(hass: HomeAssistant, config_entry: ConfigEntry) -> bool: """Unload a config entry.""" for domain in PLATFORMS: await hass.config_entries.async_forward_entry_unload(config_entry, domain) account: StarlineAccount = hass.data[DOMAIN][config_entry.entry_id] account.unload() return True
[ "async", "def", "async_unload_entry", "(", "hass", ":", "HomeAssistant", ",", "config_entry", ":", "ConfigEntry", ")", "->", "bool", ":", "for", "domain", "in", "PLATFORMS", ":", "await", "hass", ".", "config_entries", ".", "async_forward_entry_unload", "(", "config_entry", ",", "domain", ")", "account", ":", "StarlineAccount", "=", "hass", ".", "data", "[", "DOMAIN", "]", "[", "config_entry", ".", "entry_id", "]", "account", ".", "unload", "(", ")", "return", "True" ]
[ 71, 0 ]
[ 78, 15 ]
python
en
['en', 'es', 'en']
True
async_options_updated
(hass: HomeAssistant, config_entry: ConfigEntry)
Triggered by config entry options updates.
Triggered by config entry options updates.
async def async_options_updated(hass: HomeAssistant, config_entry: ConfigEntry) -> None: """Triggered by config entry options updates.""" account: StarlineAccount = hass.data[DOMAIN][config_entry.entry_id] scan_interval = config_entry.options.get(CONF_SCAN_INTERVAL, DEFAULT_SCAN_INTERVAL) account.set_update_interval(scan_interval)
[ "async", "def", "async_options_updated", "(", "hass", ":", "HomeAssistant", ",", "config_entry", ":", "ConfigEntry", ")", "->", "None", ":", "account", ":", "StarlineAccount", "=", "hass", ".", "data", "[", "DOMAIN", "]", "[", "config_entry", ".", "entry_id", "]", "scan_interval", "=", "config_entry", ".", "options", ".", "get", "(", "CONF_SCAN_INTERVAL", ",", "DEFAULT_SCAN_INTERVAL", ")", "account", ".", "set_update_interval", "(", "scan_interval", ")" ]
[ 81, 0 ]
[ 85, 46 ]
python
en
['en', 'en', 'en']
True
VesselsParser.parse
(self, conf: dict)
Parse specified vessel configurations. Args: conf(dict): Configurations to parse. Returns: (Dict[str, int], List[VesselSetting]): Vessel mappings (name to index), and settings list for all vessels.
Parse specified vessel configurations.
def parse(self, conf: dict) -> (Dict[str, int], List[VesselSetting]): """Parse specified vessel configurations. Args: conf(dict): Configurations to parse. Returns: (Dict[str, int], List[VesselSetting]): Vessel mappings (name to index), and settings list for all vessels. """ mapping: Dict[str, int] = {} vessels: List[VesselSetting] = [] index = 0 for vessel_name, vessel_node in conf.items(): mapping[vessel_name] = index sailing = vessel_node["sailing"] parking = vessel_node["parking"] route = vessel_node["route"] vessels.append(VesselSetting( index, vessel_name, vessel_node["capacity"], route["route_name"], route["initial_port_name"], sailing["speed"], sailing["noise"], parking["duration"], parking["noise"], # default no empty vessel_node.get("empty", 0))) index += 1 return mapping, vessels
[ "def", "parse", "(", "self", ",", "conf", ":", "dict", ")", "->", "(", "Dict", "[", "str", ",", "int", "]", ",", "List", "[", "VesselSetting", "]", ")", ":", "mapping", ":", "Dict", "[", "str", ",", "int", "]", "=", "{", "}", "vessels", ":", "List", "[", "VesselSetting", "]", "=", "[", "]", "index", "=", "0", "for", "vessel_name", ",", "vessel_node", "in", "conf", ".", "items", "(", ")", ":", "mapping", "[", "vessel_name", "]", "=", "index", "sailing", "=", "vessel_node", "[", "\"sailing\"", "]", "parking", "=", "vessel_node", "[", "\"parking\"", "]", "route", "=", "vessel_node", "[", "\"route\"", "]", "vessels", ".", "append", "(", "VesselSetting", "(", "index", ",", "vessel_name", ",", "vessel_node", "[", "\"capacity\"", "]", ",", "route", "[", "\"route_name\"", "]", ",", "route", "[", "\"initial_port_name\"", "]", ",", "sailing", "[", "\"speed\"", "]", ",", "sailing", "[", "\"noise\"", "]", ",", "parking", "[", "\"duration\"", "]", ",", "parking", "[", "\"noise\"", "]", ",", "# default no empty", "vessel_node", ".", "get", "(", "\"empty\"", ",", "0", ")", ")", ")", "index", "+=", "1", "return", "mapping", ",", "vessels" ]
[ 12, 4 ]
[ 49, 31 ]
python
en
['en', 'en', 'en']
True
async_setup
(hass)
Initialize the HTTP API.
Initialize the HTTP API.
async def async_setup(hass): """Initialize the HTTP API.""" async_register_command = hass.components.websocket_api.async_register_command async_register_command(WS_TYPE_STATUS, websocket_cloud_status, SCHEMA_WS_STATUS) async_register_command( WS_TYPE_SUBSCRIPTION, websocket_subscription, SCHEMA_WS_SUBSCRIPTION ) async_register_command(websocket_update_prefs) async_register_command( WS_TYPE_HOOK_CREATE, websocket_hook_create, SCHEMA_WS_HOOK_CREATE ) async_register_command( WS_TYPE_HOOK_DELETE, websocket_hook_delete, SCHEMA_WS_HOOK_DELETE ) async_register_command(websocket_remote_connect) async_register_command(websocket_remote_disconnect) async_register_command(google_assistant_list) async_register_command(google_assistant_update) async_register_command(alexa_list) async_register_command(alexa_update) async_register_command(alexa_sync) async_register_command(thingtalk_convert) hass.http.register_view(GoogleActionsSyncView) hass.http.register_view(CloudLoginView) hass.http.register_view(CloudLogoutView) hass.http.register_view(CloudRegisterView) hass.http.register_view(CloudResendConfirmView) hass.http.register_view(CloudForgotPasswordView) _CLOUD_ERRORS.update( { auth.UserNotFound: (HTTP_BAD_REQUEST, "User does not exist."), auth.UserNotConfirmed: (HTTP_BAD_REQUEST, "Email not confirmed."), auth.UserExists: ( HTTP_BAD_REQUEST, "An account with the given email already exists.", ), auth.Unauthenticated: (HTTP_UNAUTHORIZED, "Authentication failed."), auth.PasswordChangeRequired: ( HTTP_BAD_REQUEST, "Password change required.", ), } )
[ "async", "def", "async_setup", "(", "hass", ")", ":", "async_register_command", "=", "hass", ".", "components", ".", "websocket_api", ".", "async_register_command", "async_register_command", "(", "WS_TYPE_STATUS", ",", "websocket_cloud_status", ",", "SCHEMA_WS_STATUS", ")", "async_register_command", "(", "WS_TYPE_SUBSCRIPTION", ",", "websocket_subscription", ",", "SCHEMA_WS_SUBSCRIPTION", ")", "async_register_command", "(", "websocket_update_prefs", ")", "async_register_command", "(", "WS_TYPE_HOOK_CREATE", ",", "websocket_hook_create", ",", "SCHEMA_WS_HOOK_CREATE", ")", "async_register_command", "(", "WS_TYPE_HOOK_DELETE", ",", "websocket_hook_delete", ",", "SCHEMA_WS_HOOK_DELETE", ")", "async_register_command", "(", "websocket_remote_connect", ")", "async_register_command", "(", "websocket_remote_disconnect", ")", "async_register_command", "(", "google_assistant_list", ")", "async_register_command", "(", "google_assistant_update", ")", "async_register_command", "(", "alexa_list", ")", "async_register_command", "(", "alexa_update", ")", "async_register_command", "(", "alexa_sync", ")", "async_register_command", "(", "thingtalk_convert", ")", "hass", ".", "http", ".", "register_view", "(", "GoogleActionsSyncView", ")", "hass", ".", "http", ".", "register_view", "(", "CloudLoginView", ")", "hass", ".", "http", ".", "register_view", "(", "CloudLogoutView", ")", "hass", ".", "http", ".", "register_view", "(", "CloudRegisterView", ")", "hass", ".", "http", ".", "register_view", "(", "CloudResendConfirmView", ")", "hass", ".", "http", ".", "register_view", "(", "CloudForgotPasswordView", ")", "_CLOUD_ERRORS", ".", "update", "(", "{", "auth", ".", "UserNotFound", ":", "(", "HTTP_BAD_REQUEST", ",", "\"User does not exist.\"", ")", ",", "auth", ".", "UserNotConfirmed", ":", "(", "HTTP_BAD_REQUEST", ",", "\"Email not confirmed.\"", ")", ",", "auth", ".", "UserExists", ":", "(", "HTTP_BAD_REQUEST", ",", "\"An account with the given email already exists.\"", ",", ")", ",", "auth", ".", "Unauthenticated", ":", "(", "HTTP_UNAUTHORIZED", ",", "\"Authentication failed.\"", ")", ",", "auth", ".", "PasswordChangeRequired", ":", "(", "HTTP_BAD_REQUEST", ",", "\"Password change required.\"", ",", ")", ",", "}", ")" ]
[ 92, 0 ]
[ 139, 5 ]
python
en
['en', 'en', 'en']
True
_handle_cloud_errors
(handler)
Webview decorator to handle auth errors.
Webview decorator to handle auth errors.
def _handle_cloud_errors(handler): """Webview decorator to handle auth errors.""" @wraps(handler) async def error_handler(view, request, *args, **kwargs): """Handle exceptions that raise from the wrapped request handler.""" try: result = await handler(view, request, *args, **kwargs) return result except Exception as err: # pylint: disable=broad-except status, msg = _process_cloud_exception(err, request.path) return view.json_message( msg, status_code=status, message_code=err.__class__.__name__.lower() ) return error_handler
[ "def", "_handle_cloud_errors", "(", "handler", ")", ":", "@", "wraps", "(", "handler", ")", "async", "def", "error_handler", "(", "view", ",", "request", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "\"\"\"Handle exceptions that raise from the wrapped request handler.\"\"\"", "try", ":", "result", "=", "await", "handler", "(", "view", ",", "request", ",", "*", "args", ",", "*", "*", "kwargs", ")", "return", "result", "except", "Exception", "as", "err", ":", "# pylint: disable=broad-except", "status", ",", "msg", "=", "_process_cloud_exception", "(", "err", ",", "request", ".", "path", ")", "return", "view", ".", "json_message", "(", "msg", ",", "status_code", "=", "status", ",", "message_code", "=", "err", ".", "__class__", ".", "__name__", ".", "lower", "(", ")", ")", "return", "error_handler" ]
[ 142, 0 ]
[ 158, 24 ]
python
en
['en', 'en', 'en']
True
_ws_handle_cloud_errors
(handler)
Websocket decorator to handle auth errors.
Websocket decorator to handle auth errors.
def _ws_handle_cloud_errors(handler): """Websocket decorator to handle auth errors.""" @wraps(handler) async def error_handler(hass, connection, msg): """Handle exceptions that raise from the wrapped handler.""" try: return await handler(hass, connection, msg) except Exception as err: # pylint: disable=broad-except err_status, err_msg = _process_cloud_exception(err, msg["type"]) connection.send_error(msg["id"], err_status, err_msg) return error_handler
[ "def", "_ws_handle_cloud_errors", "(", "handler", ")", ":", "@", "wraps", "(", "handler", ")", "async", "def", "error_handler", "(", "hass", ",", "connection", ",", "msg", ")", ":", "\"\"\"Handle exceptions that raise from the wrapped handler.\"\"\"", "try", ":", "return", "await", "handler", "(", "hass", ",", "connection", ",", "msg", ")", "except", "Exception", "as", "err", ":", "# pylint: disable=broad-except", "err_status", ",", "err_msg", "=", "_process_cloud_exception", "(", "err", ",", "msg", "[", "\"type\"", "]", ")", "connection", ".", "send_error", "(", "msg", "[", "\"id\"", "]", ",", "err_status", ",", "err_msg", ")", "return", "error_handler" ]
[ 161, 0 ]
[ 174, 24 ]
python
en
['en', 'en', 'en']
True
_process_cloud_exception
(exc, where)
Process a cloud exception.
Process a cloud exception.
def _process_cloud_exception(exc, where): """Process a cloud exception.""" err_info = None for err, value_info in _CLOUD_ERRORS.items(): if isinstance(exc, err): err_info = value_info break if err_info is None: _LOGGER.exception("Unexpected error processing request for %s", where) err_info = (HTTP_BAD_GATEWAY, f"Unexpected error: {exc}") return err_info
[ "def", "_process_cloud_exception", "(", "exc", ",", "where", ")", ":", "err_info", "=", "None", "for", "err", ",", "value_info", "in", "_CLOUD_ERRORS", ".", "items", "(", ")", ":", "if", "isinstance", "(", "exc", ",", "err", ")", ":", "err_info", "=", "value_info", "break", "if", "err_info", "is", "None", ":", "_LOGGER", ".", "exception", "(", "\"Unexpected error processing request for %s\"", ",", "where", ")", "err_info", "=", "(", "HTTP_BAD_GATEWAY", ",", "f\"Unexpected error: {exc}\"", ")", "return", "err_info" ]
[ 177, 0 ]
[ 190, 19 ]
python
en
['en', 'fr', 'en']
True
websocket_cloud_status
(hass, connection, msg)
Handle request for account info. Async friendly.
Handle request for account info.
def websocket_cloud_status(hass, connection, msg): """Handle request for account info. Async friendly. """ cloud = hass.data[DOMAIN] connection.send_message( websocket_api.result_message(msg["id"], _account_data(cloud)) )
[ "def", "websocket_cloud_status", "(", "hass", ",", "connection", ",", "msg", ")", ":", "cloud", "=", "hass", ".", "data", "[", "DOMAIN", "]", "connection", ".", "send_message", "(", "websocket_api", ".", "result_message", "(", "msg", "[", "\"id\"", "]", ",", "_account_data", "(", "cloud", ")", ")", ")" ]
[ 310, 0 ]
[ 318, 5 ]
python
en
['en', 'en', 'en']
True
_require_cloud_login
(handler)
Websocket decorator that requires cloud to be logged in.
Websocket decorator that requires cloud to be logged in.
def _require_cloud_login(handler): """Websocket decorator that requires cloud to be logged in.""" @wraps(handler) def with_cloud_auth(hass, connection, msg): """Require to be logged into the cloud.""" cloud = hass.data[DOMAIN] if not cloud.is_logged_in: connection.send_message( websocket_api.error_message( msg["id"], "not_logged_in", "You need to be logged in to the cloud." ) ) return handler(hass, connection, msg) return with_cloud_auth
[ "def", "_require_cloud_login", "(", "handler", ")", ":", "@", "wraps", "(", "handler", ")", "def", "with_cloud_auth", "(", "hass", ",", "connection", ",", "msg", ")", ":", "\"\"\"Require to be logged into the cloud.\"\"\"", "cloud", "=", "hass", ".", "data", "[", "DOMAIN", "]", "if", "not", "cloud", ".", "is_logged_in", ":", "connection", ".", "send_message", "(", "websocket_api", ".", "error_message", "(", "msg", "[", "\"id\"", "]", ",", "\"not_logged_in\"", ",", "\"You need to be logged in to the cloud.\"", ")", ")", "return", "handler", "(", "hass", ",", "connection", ",", "msg", ")", "return", "with_cloud_auth" ]
[ 321, 0 ]
[ 338, 26 ]
python
en
['en', 'en', 'en']
True
websocket_subscription
(hass, connection, msg)
Handle request for account info.
Handle request for account info.
async def websocket_subscription(hass, connection, msg): """Handle request for account info.""" cloud = hass.data[DOMAIN] with async_timeout.timeout(REQUEST_TIMEOUT): response = await cloud.fetch_subscription_info() if response.status != HTTP_OK: connection.send_message( websocket_api.error_message( msg["id"], "request_failed", "Failed to request subscription" ) ) data = await response.json() # Check if a user is subscribed but local info is outdated # In that case, let's refresh and reconnect if data.get("provider") and not cloud.is_connected: _LOGGER.debug("Found disconnected account with valid subscriotion, connecting") await cloud.auth.async_renew_access_token() # Cancel reconnect in progress if cloud.iot.state != STATE_DISCONNECTED: await cloud.iot.disconnect() hass.async_create_task(cloud.iot.connect()) connection.send_message(websocket_api.result_message(msg["id"], data))
[ "async", "def", "websocket_subscription", "(", "hass", ",", "connection", ",", "msg", ")", ":", "cloud", "=", "hass", ".", "data", "[", "DOMAIN", "]", "with", "async_timeout", ".", "timeout", "(", "REQUEST_TIMEOUT", ")", ":", "response", "=", "await", "cloud", ".", "fetch_subscription_info", "(", ")", "if", "response", ".", "status", "!=", "HTTP_OK", ":", "connection", ".", "send_message", "(", "websocket_api", ".", "error_message", "(", "msg", "[", "\"id\"", "]", ",", "\"request_failed\"", ",", "\"Failed to request subscription\"", ")", ")", "data", "=", "await", "response", ".", "json", "(", ")", "# Check if a user is subscribed but local info is outdated", "# In that case, let's refresh and reconnect", "if", "data", ".", "get", "(", "\"provider\"", ")", "and", "not", "cloud", ".", "is_connected", ":", "_LOGGER", ".", "debug", "(", "\"Found disconnected account with valid subscriotion, connecting\"", ")", "await", "cloud", ".", "auth", ".", "async_renew_access_token", "(", ")", "# Cancel reconnect in progress", "if", "cloud", ".", "iot", ".", "state", "!=", "STATE_DISCONNECTED", ":", "await", "cloud", ".", "iot", ".", "disconnect", "(", ")", "hass", ".", "async_create_task", "(", "cloud", ".", "iot", ".", "connect", "(", ")", ")", "connection", ".", "send_message", "(", "websocket_api", ".", "result_message", "(", "msg", "[", "\"id\"", "]", ",", "data", ")", ")" ]
[ 343, 0 ]
[ 372, 74 ]
python
en
['en', 'en', 'en']
True
websocket_update_prefs
(hass, connection, msg)
Handle request for account info.
Handle request for account info.
async def websocket_update_prefs(hass, connection, msg): """Handle request for account info.""" cloud = hass.data[DOMAIN] changes = dict(msg) changes.pop("id") changes.pop("type") # If we turn alexa linking on, validate that we can fetch access token if changes.get(PREF_ALEXA_REPORT_STATE): try: with async_timeout.timeout(10): await cloud.client.alexa_config.async_get_access_token() except asyncio.TimeoutError: connection.send_error( msg["id"], "alexa_timeout", "Timeout validating Alexa access token." ) return except (alexa_errors.NoTokenAvailable, RequireRelink): connection.send_error( msg["id"], "alexa_relink", "Please go to the Alexa app and re-link the Home Assistant " "skill and then try to enable state reporting.", ) return await cloud.client.prefs.async_update(**changes) connection.send_message(websocket_api.result_message(msg["id"]))
[ "async", "def", "websocket_update_prefs", "(", "hass", ",", "connection", ",", "msg", ")", ":", "cloud", "=", "hass", ".", "data", "[", "DOMAIN", "]", "changes", "=", "dict", "(", "msg", ")", "changes", ".", "pop", "(", "\"id\"", ")", "changes", ".", "pop", "(", "\"type\"", ")", "# If we turn alexa linking on, validate that we can fetch access token", "if", "changes", ".", "get", "(", "PREF_ALEXA_REPORT_STATE", ")", ":", "try", ":", "with", "async_timeout", ".", "timeout", "(", "10", ")", ":", "await", "cloud", ".", "client", ".", "alexa_config", ".", "async_get_access_token", "(", ")", "except", "asyncio", ".", "TimeoutError", ":", "connection", ".", "send_error", "(", "msg", "[", "\"id\"", "]", ",", "\"alexa_timeout\"", ",", "\"Timeout validating Alexa access token.\"", ")", "return", "except", "(", "alexa_errors", ".", "NoTokenAvailable", ",", "RequireRelink", ")", ":", "connection", ".", "send_error", "(", "msg", "[", "\"id\"", "]", ",", "\"alexa_relink\"", ",", "\"Please go to the Alexa app and re-link the Home Assistant \"", "\"skill and then try to enable state reporting.\"", ",", ")", "return", "await", "cloud", ".", "client", ".", "prefs", ".", "async_update", "(", "*", "*", "changes", ")", "connection", ".", "send_message", "(", "websocket_api", ".", "result_message", "(", "msg", "[", "\"id\"", "]", ")", ")" ]
[ 389, 0 ]
[ 418, 68 ]
python
en
['en', 'en', 'en']
True
websocket_hook_create
(hass, connection, msg)
Handle request for account info.
Handle request for account info.
async def websocket_hook_create(hass, connection, msg): """Handle request for account info.""" cloud = hass.data[DOMAIN] hook = await cloud.cloudhooks.async_create(msg["webhook_id"], False) connection.send_message(websocket_api.result_message(msg["id"], hook))
[ "async", "def", "websocket_hook_create", "(", "hass", ",", "connection", ",", "msg", ")", ":", "cloud", "=", "hass", ".", "data", "[", "DOMAIN", "]", "hook", "=", "await", "cloud", ".", "cloudhooks", ".", "async_create", "(", "msg", "[", "\"webhook_id\"", "]", ",", "False", ")", "connection", ".", "send_message", "(", "websocket_api", ".", "result_message", "(", "msg", "[", "\"id\"", "]", ",", "hook", ")", ")" ]
[ 424, 0 ]
[ 428, 74 ]
python
en
['en', 'en', 'en']
True
websocket_hook_delete
(hass, connection, msg)
Handle request for account info.
Handle request for account info.
async def websocket_hook_delete(hass, connection, msg): """Handle request for account info.""" cloud = hass.data[DOMAIN] await cloud.cloudhooks.async_delete(msg["webhook_id"]) connection.send_message(websocket_api.result_message(msg["id"]))
[ "async", "def", "websocket_hook_delete", "(", "hass", ",", "connection", ",", "msg", ")", ":", "cloud", "=", "hass", ".", "data", "[", "DOMAIN", "]", "await", "cloud", ".", "cloudhooks", ".", "async_delete", "(", "msg", "[", "\"webhook_id\"", "]", ")", "connection", ".", "send_message", "(", "websocket_api", ".", "result_message", "(", "msg", "[", "\"id\"", "]", ")", ")" ]
[ 434, 0 ]
[ 438, 68 ]
python
en
['en', 'en', 'en']
True
_account_data
(cloud)
Generate the auth data JSON response.
Generate the auth data JSON response.
def _account_data(cloud): """Generate the auth data JSON response.""" if not cloud.is_logged_in: return {"logged_in": False, "cloud": STATE_DISCONNECTED} claims = cloud.claims client = cloud.client remote = cloud.remote # Load remote certificate if remote.certificate: certificate = attr.asdict(remote.certificate) else: certificate = None return { "logged_in": True, "email": claims["email"], "cloud": cloud.iot.state, "prefs": client.prefs.as_dict(), "google_entities": client.google_user_config["filter"].config, "alexa_entities": client.alexa_user_config["filter"].config, "remote_domain": remote.instance_domain, "remote_connected": remote.is_connected, "remote_certificate": certificate, }
[ "def", "_account_data", "(", "cloud", ")", ":", "if", "not", "cloud", ".", "is_logged_in", ":", "return", "{", "\"logged_in\"", ":", "False", ",", "\"cloud\"", ":", "STATE_DISCONNECTED", "}", "claims", "=", "cloud", ".", "claims", "client", "=", "cloud", ".", "client", "remote", "=", "cloud", ".", "remote", "# Load remote certificate", "if", "remote", ".", "certificate", ":", "certificate", "=", "attr", ".", "asdict", "(", "remote", ".", "certificate", ")", "else", ":", "certificate", "=", "None", "return", "{", "\"logged_in\"", ":", "True", ",", "\"email\"", ":", "claims", "[", "\"email\"", "]", ",", "\"cloud\"", ":", "cloud", ".", "iot", ".", "state", ",", "\"prefs\"", ":", "client", ".", "prefs", ".", "as_dict", "(", ")", ",", "\"google_entities\"", ":", "client", ".", "google_user_config", "[", "\"filter\"", "]", ".", "config", ",", "\"alexa_entities\"", ":", "client", ".", "alexa_user_config", "[", "\"filter\"", "]", ".", "config", ",", "\"remote_domain\"", ":", "remote", ".", "instance_domain", ",", "\"remote_connected\"", ":", "remote", ".", "is_connected", ",", "\"remote_certificate\"", ":", "certificate", ",", "}" ]
[ 441, 0 ]
[ 467, 5 ]
python
en
['en', 'en', 'en']
True
websocket_remote_connect
(hass, connection, msg)
Handle request for connect remote.
Handle request for connect remote.
async def websocket_remote_connect(hass, connection, msg): """Handle request for connect remote.""" cloud = hass.data[DOMAIN] await cloud.client.prefs.async_update(remote_enabled=True) await cloud.remote.connect() connection.send_result(msg["id"], _account_data(cloud))
[ "async", "def", "websocket_remote_connect", "(", "hass", ",", "connection", ",", "msg", ")", ":", "cloud", "=", "hass", ".", "data", "[", "DOMAIN", "]", "await", "cloud", ".", "client", ".", "prefs", ".", "async_update", "(", "remote_enabled", "=", "True", ")", "await", "cloud", ".", "remote", ".", "connect", "(", ")", "connection", ".", "send_result", "(", "msg", "[", "\"id\"", "]", ",", "_account_data", "(", "cloud", ")", ")" ]
[ 475, 0 ]
[ 480, 59 ]
python
en
['en', 'en', 'en']
True
websocket_remote_disconnect
(hass, connection, msg)
Handle request for disconnect remote.
Handle request for disconnect remote.
async def websocket_remote_disconnect(hass, connection, msg): """Handle request for disconnect remote.""" cloud = hass.data[DOMAIN] await cloud.client.prefs.async_update(remote_enabled=False) await cloud.remote.disconnect() connection.send_result(msg["id"], _account_data(cloud))
[ "async", "def", "websocket_remote_disconnect", "(", "hass", ",", "connection", ",", "msg", ")", ":", "cloud", "=", "hass", ".", "data", "[", "DOMAIN", "]", "await", "cloud", ".", "client", ".", "prefs", ".", "async_update", "(", "remote_enabled", "=", "False", ")", "await", "cloud", ".", "remote", ".", "disconnect", "(", ")", "connection", ".", "send_result", "(", "msg", "[", "\"id\"", "]", ",", "_account_data", "(", "cloud", ")", ")" ]
[ 488, 0 ]
[ 493, 59 ]
python
en
['da', 'en', 'en']
True
google_assistant_list
(hass, connection, msg)
List all google assistant entities.
List all google assistant entities.
async def google_assistant_list(hass, connection, msg): """List all google assistant entities.""" cloud = hass.data[DOMAIN] gconf = await cloud.client.get_google_config() entities = google_helpers.async_get_entities(hass, gconf) result = [] for entity in entities: result.append( { "entity_id": entity.entity_id, "traits": [trait.name for trait in entity.traits()], "might_2fa": entity.might_2fa_traits(), } ) connection.send_result(msg["id"], result)
[ "async", "def", "google_assistant_list", "(", "hass", ",", "connection", ",", "msg", ")", ":", "cloud", "=", "hass", ".", "data", "[", "DOMAIN", "]", "gconf", "=", "await", "cloud", ".", "client", ".", "get_google_config", "(", ")", "entities", "=", "google_helpers", ".", "async_get_entities", "(", "hass", ",", "gconf", ")", "result", "=", "[", "]", "for", "entity", "in", "entities", ":", "result", ".", "append", "(", "{", "\"entity_id\"", ":", "entity", ".", "entity_id", ",", "\"traits\"", ":", "[", "trait", ".", "name", "for", "trait", "in", "entity", ".", "traits", "(", ")", "]", ",", "\"might_2fa\"", ":", "entity", ".", "might_2fa_traits", "(", ")", ",", "}", ")", "connection", ".", "send_result", "(", "msg", "[", "\"id\"", "]", ",", "result", ")" ]
[ 501, 0 ]
[ 518, 45 ]
python
en
['br', 'en', 'en']
True
google_assistant_update
(hass, connection, msg)
Update google assistant config.
Update google assistant config.
async def google_assistant_update(hass, connection, msg): """Update google assistant config.""" cloud = hass.data[DOMAIN] changes = dict(msg) changes.pop("type") changes.pop("id") await cloud.client.prefs.async_update_google_entity_config(**changes) connection.send_result( msg["id"], cloud.client.prefs.google_entity_configs.get(msg["entity_id"]) )
[ "async", "def", "google_assistant_update", "(", "hass", ",", "connection", ",", "msg", ")", ":", "cloud", "=", "hass", ".", "data", "[", "DOMAIN", "]", "changes", "=", "dict", "(", "msg", ")", "changes", ".", "pop", "(", "\"type\"", ")", "changes", ".", "pop", "(", "\"id\"", ")", "await", "cloud", ".", "client", ".", "prefs", ".", "async_update_google_entity_config", "(", "*", "*", "changes", ")", "connection", ".", "send_result", "(", "msg", "[", "\"id\"", "]", ",", "cloud", ".", "client", ".", "prefs", ".", "google_entity_configs", ".", "get", "(", "msg", "[", "\"entity_id\"", "]", ")", ")" ]
[ 535, 0 ]
[ 546, 5 ]
python
en
['fr', 'en', 'en']
True
alexa_list
(hass, connection, msg)
List all alexa entities.
List all alexa entities.
async def alexa_list(hass, connection, msg): """List all alexa entities.""" cloud = hass.data[DOMAIN] entities = alexa_entities.async_get_entities(hass, cloud.client.alexa_config) result = [] for entity in entities: result.append( { "entity_id": entity.entity_id, "display_categories": entity.default_display_categories(), "interfaces": [ifc.name() for ifc in entity.interfaces()], } ) connection.send_result(msg["id"], result)
[ "async", "def", "alexa_list", "(", "hass", ",", "connection", ",", "msg", ")", ":", "cloud", "=", "hass", ".", "data", "[", "DOMAIN", "]", "entities", "=", "alexa_entities", ".", "async_get_entities", "(", "hass", ",", "cloud", ".", "client", ".", "alexa_config", ")", "result", "=", "[", "]", "for", "entity", "in", "entities", ":", "result", ".", "append", "(", "{", "\"entity_id\"", ":", "entity", ".", "entity_id", ",", "\"display_categories\"", ":", "entity", ".", "default_display_categories", "(", ")", ",", "\"interfaces\"", ":", "[", "ifc", ".", "name", "(", ")", "for", "ifc", "in", "entity", ".", "interfaces", "(", ")", "]", ",", "}", ")", "connection", ".", "send_result", "(", "msg", "[", "\"id\"", "]", ",", "result", ")" ]
[ 554, 0 ]
[ 570, 45 ]
python
ca
['ca', 'et', 'en']
False
alexa_update
(hass, connection, msg)
Update alexa entity config.
Update alexa entity config.
async def alexa_update(hass, connection, msg): """Update alexa entity config.""" cloud = hass.data[DOMAIN] changes = dict(msg) changes.pop("type") changes.pop("id") await cloud.client.prefs.async_update_alexa_entity_config(**changes) connection.send_result( msg["id"], cloud.client.prefs.alexa_entity_configs.get(msg["entity_id"]) )
[ "async", "def", "alexa_update", "(", "hass", ",", "connection", ",", "msg", ")", ":", "cloud", "=", "hass", ".", "data", "[", "DOMAIN", "]", "changes", "=", "dict", "(", "msg", ")", "changes", ".", "pop", "(", "\"type\"", ")", "changes", ".", "pop", "(", "\"id\"", ")", "await", "cloud", ".", "client", ".", "prefs", ".", "async_update_alexa_entity_config", "(", "*", "*", "changes", ")", "connection", ".", "send_result", "(", "msg", "[", "\"id\"", "]", ",", "cloud", ".", "client", ".", "prefs", ".", "alexa_entity_configs", ".", "get", "(", "msg", "[", "\"entity_id\"", "]", ")", ")" ]
[ 584, 0 ]
[ 595, 5 ]
python
en
['mg', 'sr', 'en']
False
alexa_sync
(hass, connection, msg)
Sync with Alexa.
Sync with Alexa.
async def alexa_sync(hass, connection, msg): """Sync with Alexa.""" cloud = hass.data[DOMAIN] with async_timeout.timeout(10): try: success = await cloud.client.alexa_config.async_sync_entities() except alexa_errors.NoTokenAvailable: connection.send_error( msg["id"], "alexa_relink", "Please go to the Alexa app and re-link the Home Assistant skill.", ) return if success: connection.send_result(msg["id"]) else: connection.send_error(msg["id"], ws_const.ERR_UNKNOWN_ERROR, "Unknown error")
[ "async", "def", "alexa_sync", "(", "hass", ",", "connection", ",", "msg", ")", ":", "cloud", "=", "hass", ".", "data", "[", "DOMAIN", "]", "with", "async_timeout", ".", "timeout", "(", "10", ")", ":", "try", ":", "success", "=", "await", "cloud", ".", "client", ".", "alexa_config", ".", "async_sync_entities", "(", ")", "except", "alexa_errors", ".", "NoTokenAvailable", ":", "connection", ".", "send_error", "(", "msg", "[", "\"id\"", "]", ",", "\"alexa_relink\"", ",", "\"Please go to the Alexa app and re-link the Home Assistant skill.\"", ",", ")", "return", "if", "success", ":", "connection", ".", "send_result", "(", "msg", "[", "\"id\"", "]", ")", "else", ":", "connection", ".", "send_error", "(", "msg", "[", "\"id\"", "]", ",", "ws_const", ".", "ERR_UNKNOWN_ERROR", ",", "\"Unknown error\"", ")" ]
[ 602, 0 ]
[ 620, 85 ]
python
en
['en', 'mg', 'en']
True
thingtalk_convert
(hass, connection, msg)
Convert a query.
Convert a query.
async def thingtalk_convert(hass, connection, msg): """Convert a query.""" cloud = hass.data[DOMAIN] with async_timeout.timeout(10): try: connection.send_result( msg["id"], await thingtalk.async_convert(cloud, msg["query"]) ) except thingtalk.ThingTalkConversionError as err: connection.send_error(msg["id"], ws_const.ERR_UNKNOWN_ERROR, str(err))
[ "async", "def", "thingtalk_convert", "(", "hass", ",", "connection", ",", "msg", ")", ":", "cloud", "=", "hass", ".", "data", "[", "DOMAIN", "]", "with", "async_timeout", ".", "timeout", "(", "10", ")", ":", "try", ":", "connection", ".", "send_result", "(", "msg", "[", "\"id\"", "]", ",", "await", "thingtalk", ".", "async_convert", "(", "cloud", ",", "msg", "[", "\"query\"", "]", ")", ")", "except", "thingtalk", ".", "ThingTalkConversionError", "as", "err", ":", "connection", ".", "send_error", "(", "msg", "[", "\"id\"", "]", ",", "ws_const", ".", "ERR_UNKNOWN_ERROR", ",", "str", "(", "err", ")", ")" ]
[ 625, 0 ]
[ 635, 82 ]
python
es
['es', 'lb', 'es']
True
GoogleActionsSyncView.post
(self, request)
Trigger a Google Actions sync.
Trigger a Google Actions sync.
async def post(self, request): """Trigger a Google Actions sync.""" hass = request.app["hass"] cloud: Cloud = hass.data[DOMAIN] gconf = await cloud.client.get_google_config() status = await gconf.async_sync_entities(gconf.agent_user_id) return self.json({}, status_code=status)
[ "async", "def", "post", "(", "self", ",", "request", ")", ":", "hass", "=", "request", ".", "app", "[", "\"hass\"", "]", "cloud", ":", "Cloud", "=", "hass", ".", "data", "[", "DOMAIN", "]", "gconf", "=", "await", "cloud", ".", "client", ".", "get_google_config", "(", ")", "status", "=", "await", "gconf", ".", "async_sync_entities", "(", "gconf", ".", "agent_user_id", ")", "return", "self", ".", "json", "(", "{", "}", ",", "status_code", "=", "status", ")" ]
[ 200, 4 ]
[ 206, 48 ]
python
en
['en', 'en', 'en']
True
CloudLoginView.post
(self, request, data)
Handle login request.
Handle login request.
async def post(self, request, data): """Handle login request.""" hass = request.app["hass"] cloud = hass.data[DOMAIN] await cloud.login(data["email"], data["password"]) return self.json({"success": True})
[ "async", "def", "post", "(", "self", ",", "request", ",", "data", ")", ":", "hass", "=", "request", ".", "app", "[", "\"hass\"", "]", "cloud", "=", "hass", ".", "data", "[", "DOMAIN", "]", "await", "cloud", ".", "login", "(", "data", "[", "\"email\"", "]", ",", "data", "[", "\"password\"", "]", ")", "return", "self", ".", "json", "(", "{", "\"success\"", ":", "True", "}", ")" ]
[ 219, 4 ]
[ 224, 43 ]
python
en
['es', 'nl', 'en']
False
CloudLogoutView.post
(self, request)
Handle logout request.
Handle logout request.
async def post(self, request): """Handle logout request.""" hass = request.app["hass"] cloud = hass.data[DOMAIN] with async_timeout.timeout(REQUEST_TIMEOUT): await cloud.logout() return self.json_message("ok")
[ "async", "def", "post", "(", "self", ",", "request", ")", ":", "hass", "=", "request", ".", "app", "[", "\"hass\"", "]", "cloud", "=", "hass", ".", "data", "[", "DOMAIN", "]", "with", "async_timeout", ".", "timeout", "(", "REQUEST_TIMEOUT", ")", ":", "await", "cloud", ".", "logout", "(", ")", "return", "self", ".", "json_message", "(", "\"ok\"", ")" ]
[ 234, 4 ]
[ 242, 38 ]
python
en
['en', 'fr', 'en']
True
CloudRegisterView.post
(self, request, data)
Handle registration request.
Handle registration request.
async def post(self, request, data): """Handle registration request.""" hass = request.app["hass"] cloud = hass.data[DOMAIN] with async_timeout.timeout(REQUEST_TIMEOUT): await cloud.auth.async_register(data["email"], data["password"]) return self.json_message("ok")
[ "async", "def", "post", "(", "self", ",", "request", ",", "data", ")", ":", "hass", "=", "request", ".", "app", "[", "\"hass\"", "]", "cloud", "=", "hass", ".", "data", "[", "DOMAIN", "]", "with", "async_timeout", ".", "timeout", "(", "REQUEST_TIMEOUT", ")", ":", "await", "cloud", ".", "auth", ".", "async_register", "(", "data", "[", "\"email\"", "]", ",", "data", "[", "\"password\"", "]", ")", "return", "self", ".", "json_message", "(", "\"ok\"", ")" ]
[ 260, 4 ]
[ 268, 38 ]
python
en
['en', 'fr', 'en']
True
CloudResendConfirmView.post
(self, request, data)
Handle resending confirm email code request.
Handle resending confirm email code request.
async def post(self, request, data): """Handle resending confirm email code request.""" hass = request.app["hass"] cloud = hass.data[DOMAIN] with async_timeout.timeout(REQUEST_TIMEOUT): await cloud.auth.async_resend_email_confirm(data["email"]) return self.json_message("ok")
[ "async", "def", "post", "(", "self", ",", "request", ",", "data", ")", ":", "hass", "=", "request", ".", "app", "[", "\"hass\"", "]", "cloud", "=", "hass", ".", "data", "[", "DOMAIN", "]", "with", "async_timeout", ".", "timeout", "(", "REQUEST_TIMEOUT", ")", ":", "await", "cloud", ".", "auth", ".", "async_resend_email_confirm", "(", "data", "[", "\"email\"", "]", ")", "return", "self", ".", "json_message", "(", "\"ok\"", ")" ]
[ 279, 4 ]
[ 287, 38 ]
python
en
['it', 'en', 'en']
True
CloudForgotPasswordView.post
(self, request, data)
Handle forgot password request.
Handle forgot password request.
async def post(self, request, data): """Handle forgot password request.""" hass = request.app["hass"] cloud = hass.data[DOMAIN] with async_timeout.timeout(REQUEST_TIMEOUT): await cloud.auth.async_forgot_password(data["email"]) return self.json_message("ok")
[ "async", "def", "post", "(", "self", ",", "request", ",", "data", ")", ":", "hass", "=", "request", ".", "app", "[", "\"hass\"", "]", "cloud", "=", "hass", ".", "data", "[", "DOMAIN", "]", "with", "async_timeout", ".", "timeout", "(", "REQUEST_TIMEOUT", ")", ":", "await", "cloud", ".", "auth", ".", "async_forgot_password", "(", "data", "[", "\"email\"", "]", ")", "return", "self", ".", "json_message", "(", "\"ok\"", ")" ]
[ 298, 4 ]
[ 306, 38 ]
python
en
['fr', 'nl', 'en']
False
setup_platform
(hass, config, add_entities, discovery_info=None)
Set up the Zengge platform.
Set up the Zengge platform.
def setup_platform(hass, config, add_entities, discovery_info=None): """Set up the Zengge platform.""" lights = [] for address, device_config in config[CONF_DEVICES].items(): device = {} device["name"] = device_config[CONF_NAME] device["address"] = address light = ZenggeLight(device) if light.is_valid: lights.append(light) add_entities(lights, True)
[ "def", "setup_platform", "(", "hass", ",", "config", ",", "add_entities", ",", "discovery_info", "=", "None", ")", ":", "lights", "=", "[", "]", "for", "address", ",", "device_config", "in", "config", "[", "CONF_DEVICES", "]", ".", "items", "(", ")", ":", "device", "=", "{", "}", "device", "[", "\"name\"", "]", "=", "device_config", "[", "CONF_NAME", "]", "device", "[", "\"address\"", "]", "=", "address", "light", "=", "ZenggeLight", "(", "device", ")", "if", "light", ".", "is_valid", ":", "lights", ".", "append", "(", "light", ")", "add_entities", "(", "lights", ",", "True", ")" ]
[ 31, 0 ]
[ 42, 30 ]
python
en
['en', 'jv', 'en']
True
ZenggeLight.__init__
(self, device)
Initialize the light.
Initialize the light.
def __init__(self, device): """Initialize the light.""" self._name = device["name"] self._address = device["address"] self.is_valid = True self._bulb = zengge(self._address) self._white = 0 self._brightness = 0 self._hs_color = (0, 0) self._state = False if self._bulb.connect() is False: self.is_valid = False _LOGGER.error("Failed to connect to bulb %s, %s", self._address, self._name) return
[ "def", "__init__", "(", "self", ",", "device", ")", ":", "self", ".", "_name", "=", "device", "[", "\"name\"", "]", "self", ".", "_address", "=", "device", "[", "\"address\"", "]", "self", ".", "is_valid", "=", "True", "self", ".", "_bulb", "=", "zengge", "(", "self", ".", "_address", ")", "self", ".", "_white", "=", "0", "self", ".", "_brightness", "=", "0", "self", ".", "_hs_color", "=", "(", "0", ",", "0", ")", "self", ".", "_state", "=", "False", "if", "self", ".", "_bulb", ".", "connect", "(", ")", "is", "False", ":", "self", ".", "is_valid", "=", "False", "_LOGGER", ".", "error", "(", "\"Failed to connect to bulb %s, %s\"", ",", "self", ".", "_address", ",", "self", ".", "_name", ")", "return" ]
[ 48, 4 ]
[ 62, 18 ]
python
en
['en', 'en', 'en']
True
ZenggeLight.unique_id
(self)
Return the ID of this light.
Return the ID of this light.
def unique_id(self): """Return the ID of this light.""" return self._address
[ "def", "unique_id", "(", "self", ")", ":", "return", "self", ".", "_address" ]
[ 65, 4 ]
[ 67, 28 ]
python
en
['en', 'en', 'en']
True
ZenggeLight.name
(self)
Return the name of the device if any.
Return the name of the device if any.
def name(self): """Return the name of the device if any.""" return self._name
[ "def", "name", "(", "self", ")", ":", "return", "self", ".", "_name" ]
[ 70, 4 ]
[ 72, 25 ]
python
en
['en', 'en', 'en']
True
ZenggeLight.is_on
(self)
Return true if device is on.
Return true if device is on.
def is_on(self): """Return true if device is on.""" return self._state
[ "def", "is_on", "(", "self", ")", ":", "return", "self", ".", "_state" ]
[ 75, 4 ]
[ 77, 26 ]
python
en
['en', 'fy', 'en']
True
ZenggeLight.brightness
(self)
Return the brightness property.
Return the brightness property.
def brightness(self): """Return the brightness property.""" return self._brightness
[ "def", "brightness", "(", "self", ")", ":", "return", "self", ".", "_brightness" ]
[ 80, 4 ]
[ 82, 31 ]
python
en
['en', 'ru-Latn', 'en']
True
ZenggeLight.hs_color
(self)
Return the color property.
Return the color property.
def hs_color(self): """Return the color property.""" return self._hs_color
[ "def", "hs_color", "(", "self", ")", ":", "return", "self", ".", "_hs_color" ]
[ 85, 4 ]
[ 87, 29 ]
python
en
['en', 'en', 'en']
True
ZenggeLight.white_value
(self)
Return the white property.
Return the white property.
def white_value(self): """Return the white property.""" return self._white
[ "def", "white_value", "(", "self", ")", ":", "return", "self", ".", "_white" ]
[ 90, 4 ]
[ 92, 26 ]
python
en
['en', 'en', 'en']
True
ZenggeLight.supported_features
(self)
Flag supported features.
Flag supported features.
def supported_features(self): """Flag supported features.""" return SUPPORT_ZENGGE_LED
[ "def", "supported_features", "(", "self", ")", ":", "return", "SUPPORT_ZENGGE_LED" ]
[ 95, 4 ]
[ 97, 33 ]
python
en
['da', 'en', 'en']
True
ZenggeLight.assumed_state
(self)
We can report the actual state.
We can report the actual state.
def assumed_state(self): """We can report the actual state.""" return False
[ "def", "assumed_state", "(", "self", ")", ":", "return", "False" ]
[ 100, 4 ]
[ 102, 20 ]
python
en
['en', 'en', 'en']
True
ZenggeLight.set_rgb
(self, red, green, blue)
Set the rgb state.
Set the rgb state.
def set_rgb(self, red, green, blue): """Set the rgb state.""" return self._bulb.set_rgb(red, green, blue)
[ "def", "set_rgb", "(", "self", ",", "red", ",", "green", ",", "blue", ")", ":", "return", "self", ".", "_bulb", ".", "set_rgb", "(", "red", ",", "green", ",", "blue", ")" ]
[ 104, 4 ]
[ 106, 51 ]
python
en
['en', 'en', 'en']
True
ZenggeLight.set_white
(self, white)
Set the white state.
Set the white state.
def set_white(self, white): """Set the white state.""" return self._bulb.set_white(white)
[ "def", "set_white", "(", "self", ",", "white", ")", ":", "return", "self", ".", "_bulb", ".", "set_white", "(", "white", ")" ]
[ 108, 4 ]
[ 110, 42 ]
python
en
['en', 'en', 'en']
True
ZenggeLight.turn_on
(self, **kwargs)
Turn the specified light on.
Turn the specified light on.
def turn_on(self, **kwargs): """Turn the specified light on.""" self._state = True self._bulb.on() hs_color = kwargs.get(ATTR_HS_COLOR) white = kwargs.get(ATTR_WHITE_VALUE) brightness = kwargs.get(ATTR_BRIGHTNESS) if white is not None: self._white = white self._hs_color = (0, 0) if hs_color is not None: self._white = 0 self._hs_color = hs_color if brightness is not None: self._white = 0 self._brightness = brightness if self._white != 0: self.set_white(self._white) else: rgb = color_util.color_hsv_to_RGB( self._hs_color[0], self._hs_color[1], self._brightness / 255 * 100 ) self.set_rgb(*rgb)
[ "def", "turn_on", "(", "self", ",", "*", "*", "kwargs", ")", ":", "self", ".", "_state", "=", "True", "self", ".", "_bulb", ".", "on", "(", ")", "hs_color", "=", "kwargs", ".", "get", "(", "ATTR_HS_COLOR", ")", "white", "=", "kwargs", ".", "get", "(", "ATTR_WHITE_VALUE", ")", "brightness", "=", "kwargs", ".", "get", "(", "ATTR_BRIGHTNESS", ")", "if", "white", "is", "not", "None", ":", "self", ".", "_white", "=", "white", "self", ".", "_hs_color", "=", "(", "0", ",", "0", ")", "if", "hs_color", "is", "not", "None", ":", "self", ".", "_white", "=", "0", "self", ".", "_hs_color", "=", "hs_color", "if", "brightness", "is", "not", "None", ":", "self", ".", "_white", "=", "0", "self", ".", "_brightness", "=", "brightness", "if", "self", ".", "_white", "!=", "0", ":", "self", ".", "set_white", "(", "self", ".", "_white", ")", "else", ":", "rgb", "=", "color_util", ".", "color_hsv_to_RGB", "(", "self", ".", "_hs_color", "[", "0", "]", ",", "self", ".", "_hs_color", "[", "1", "]", ",", "self", ".", "_brightness", "/", "255", "*", "100", ")", "self", ".", "set_rgb", "(", "*", "rgb", ")" ]
[ 112, 4 ]
[ 139, 30 ]
python
en
['en', 'en', 'en']
True
ZenggeLight.turn_off
(self, **kwargs)
Turn the specified light off.
Turn the specified light off.
def turn_off(self, **kwargs): """Turn the specified light off.""" self._state = False self._bulb.off()
[ "def", "turn_off", "(", "self", ",", "*", "*", "kwargs", ")", ":", "self", ".", "_state", "=", "False", "self", ".", "_bulb", ".", "off", "(", ")" ]
[ 141, 4 ]
[ 144, 24 ]
python
en
['en', 'en', 'en']
True
ZenggeLight.update
(self)
Synchronise internal state with the actual light state.
Synchronise internal state with the actual light state.
def update(self): """Synchronise internal state with the actual light state.""" rgb = self._bulb.get_colour() hsv = color_util.color_RGB_to_hsv(*rgb) self._hs_color = hsv[:2] self._brightness = (hsv[2] / 100) * 255 self._white = self._bulb.get_white() self._state = self._bulb.get_on()
[ "def", "update", "(", "self", ")", ":", "rgb", "=", "self", ".", "_bulb", ".", "get_colour", "(", ")", "hsv", "=", "color_util", ".", "color_RGB_to_hsv", "(", "*", "rgb", ")", "self", ".", "_hs_color", "=", "hsv", "[", ":", "2", "]", "self", ".", "_brightness", "=", "(", "hsv", "[", "2", "]", "/", "100", ")", "*", "255", "self", ".", "_white", "=", "self", ".", "_bulb", ".", "get_white", "(", ")", "self", ".", "_state", "=", "self", ".", "_bulb", ".", "get_on", "(", ")" ]
[ 146, 4 ]
[ 153, 41 ]
python
en
['en', 'en', 'en']
True
test_sensors
(hass, config_entry, aioclient_mock_fixture)
Test Flo by Moen sensors.
Test Flo by Moen sensors.
async def test_sensors(hass, config_entry, aioclient_mock_fixture): """Test Flo by Moen sensors.""" config_entry.add_to_hass(hass) assert await async_setup_component( hass, FLO_DOMAIN, {CONF_USERNAME: TEST_USER_ID, CONF_PASSWORD: TEST_PASSWORD} ) await hass.async_block_till_done() assert len(hass.data[FLO_DOMAIN][config_entry.entry_id]["devices"]) == 1 # we should have 5 entities for the device assert hass.states.get("sensor.current_system_mode").state == "home" assert hass.states.get("sensor.today_s_water_usage").state == "3.7" assert hass.states.get("sensor.water_flow_rate").state == "0" assert hass.states.get("sensor.water_pressure").state == "54.2" assert hass.states.get("sensor.water_temperature").state == "21.1"
[ "async", "def", "test_sensors", "(", "hass", ",", "config_entry", ",", "aioclient_mock_fixture", ")", ":", "config_entry", ".", "add_to_hass", "(", "hass", ")", "assert", "await", "async_setup_component", "(", "hass", ",", "FLO_DOMAIN", ",", "{", "CONF_USERNAME", ":", "TEST_USER_ID", ",", "CONF_PASSWORD", ":", "TEST_PASSWORD", "}", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "assert", "len", "(", "hass", ".", "data", "[", "FLO_DOMAIN", "]", "[", "config_entry", ".", "entry_id", "]", "[", "\"devices\"", "]", ")", "==", "1", "# we should have 5 entities for the device", "assert", "hass", ".", "states", ".", "get", "(", "\"sensor.current_system_mode\"", ")", ".", "state", "==", "\"home\"", "assert", "hass", ".", "states", ".", "get", "(", "\"sensor.today_s_water_usage\"", ")", ".", "state", "==", "\"3.7\"", "assert", "hass", ".", "states", ".", "get", "(", "\"sensor.water_flow_rate\"", ")", ".", "state", "==", "\"0\"", "assert", "hass", ".", "states", ".", "get", "(", "\"sensor.water_pressure\"", ")", ".", "state", "==", "\"54.2\"", "assert", "hass", ".", "states", ".", "get", "(", "\"sensor.water_temperature\"", ")", ".", "state", "==", "\"21.1\"" ]
[ 8, 0 ]
[ 23, 70 ]
python
en
['en', 'no', 'en']
True
test_manual_update_entity
( hass, config_entry, aioclient_mock_fixture, aioclient_mock )
Test manual update entity via service homeasasistant/update_entity.
Test manual update entity via service homeasasistant/update_entity.
async def test_manual_update_entity( hass, config_entry, aioclient_mock_fixture, aioclient_mock ): """Test manual update entity via service homeasasistant/update_entity.""" config_entry.add_to_hass(hass) assert await async_setup_component( hass, FLO_DOMAIN, {CONF_USERNAME: TEST_USER_ID, CONF_PASSWORD: TEST_PASSWORD} ) await hass.async_block_till_done() assert len(hass.data[FLO_DOMAIN][config_entry.entry_id]["devices"]) == 1 await async_setup_component(hass, "homeassistant", {}) call_count = aioclient_mock.call_count await hass.services.async_call( "homeassistant", "update_entity", {ATTR_ENTITY_ID: ["sensor.current_system_mode"]}, blocking=True, ) assert aioclient_mock.call_count == call_count + 2
[ "async", "def", "test_manual_update_entity", "(", "hass", ",", "config_entry", ",", "aioclient_mock_fixture", ",", "aioclient_mock", ")", ":", "config_entry", ".", "add_to_hass", "(", "hass", ")", "assert", "await", "async_setup_component", "(", "hass", ",", "FLO_DOMAIN", ",", "{", "CONF_USERNAME", ":", "TEST_USER_ID", ",", "CONF_PASSWORD", ":", "TEST_PASSWORD", "}", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "assert", "len", "(", "hass", ".", "data", "[", "FLO_DOMAIN", "]", "[", "config_entry", ".", "entry_id", "]", "[", "\"devices\"", "]", ")", "==", "1", "await", "async_setup_component", "(", "hass", ",", "\"homeassistant\"", ",", "{", "}", ")", "call_count", "=", "aioclient_mock", ".", "call_count", "await", "hass", ".", "services", ".", "async_call", "(", "\"homeassistant\"", ",", "\"update_entity\"", ",", "{", "ATTR_ENTITY_ID", ":", "[", "\"sensor.current_system_mode\"", "]", "}", ",", "blocking", "=", "True", ",", ")", "assert", "aioclient_mock", ".", "call_count", "==", "call_count", "+", "2" ]
[ 26, 0 ]
[ 47, 54 ]
python
en
['en', 'en', 'en']
True
dsmr_transform
(value)
Transform DSMR version value to right format.
Transform DSMR version value to right format.
def dsmr_transform(value): """Transform DSMR version value to right format.""" if value.isdigit(): return float(value) / 10 return value
[ "def", "dsmr_transform", "(", "value", ")", ":", "if", "value", ".", "isdigit", "(", ")", ":", "return", "float", "(", "value", ")", "/", "10", "return", "value" ]
[ 17, 0 ]
[ 21, 16 ]
python
en
['en', 'sv', 'en']
True
tariff_transform
(value)
Transform tariff from number to description.
Transform tariff from number to description.
def tariff_transform(value): """Transform tariff from number to description.""" if value == "1": return "low" return "high"
[ "def", "tariff_transform", "(", "value", ")", ":", "if", "value", "==", "\"1\"", ":", "return", "\"low\"", "return", "\"high\"" ]
[ 24, 0 ]
[ 28, 17 ]
python
en
['en', 'en', 'en']
True
setup_platform
(hass, config, add_entities, discovery_info=None)
Set up the Crime Reports platform.
Set up the Crime Reports platform.
def setup_platform(hass, config, add_entities, discovery_info=None): """Set up the Crime Reports platform.""" latitude = config.get(CONF_LATITUDE, hass.config.latitude) longitude = config.get(CONF_LONGITUDE, hass.config.longitude) name = config[CONF_NAME] radius = config[CONF_RADIUS] api_key = config[CONF_API_KEY] days = config.get(CONF_DAYS) include = config.get(CONF_INCLUDE) exclude = config.get(CONF_EXCLUDE) add_entities( [ SpotCrimeSensor( name, latitude, longitude, radius, include, exclude, api_key, days ) ], True, )
[ "def", "setup_platform", "(", "hass", ",", "config", ",", "add_entities", ",", "discovery_info", "=", "None", ")", ":", "latitude", "=", "config", ".", "get", "(", "CONF_LATITUDE", ",", "hass", ".", "config", ".", "latitude", ")", "longitude", "=", "config", ".", "get", "(", "CONF_LONGITUDE", ",", "hass", ".", "config", ".", "longitude", ")", "name", "=", "config", "[", "CONF_NAME", "]", "radius", "=", "config", "[", "CONF_RADIUS", "]", "api_key", "=", "config", "[", "CONF_API_KEY", "]", "days", "=", "config", ".", "get", "(", "CONF_DAYS", ")", "include", "=", "config", ".", "get", "(", "CONF_INCLUDE", ")", "exclude", "=", "config", ".", "get", "(", "CONF_EXCLUDE", ")", "add_entities", "(", "[", "SpotCrimeSensor", "(", "name", ",", "latitude", ",", "longitude", ",", "radius", ",", "include", ",", "exclude", ",", "api_key", ",", "days", ")", "]", ",", "True", ",", ")" ]
[ 47, 0 ]
[ 65, 5 ]
python
en
['en', 'da', 'en']
True
SpotCrimeSensor.__init__
( self, name, latitude, longitude, radius, include, exclude, api_key, days )
Initialize the Spot Crime sensor.
Initialize the Spot Crime sensor.
def __init__( self, name, latitude, longitude, radius, include, exclude, api_key, days ): """Initialize the Spot Crime sensor.""" self._name = name self._include = include self._exclude = exclude self.api_key = api_key self.days = days self._spotcrime = spotcrime.SpotCrime( (latitude, longitude), radius, self._include, self._exclude, self.api_key, self.days, ) self._attributes = None self._state = None self._previous_incidents = set() self._attributes = {ATTR_ATTRIBUTION: spotcrime.ATTRIBUTION}
[ "def", "__init__", "(", "self", ",", "name", ",", "latitude", ",", "longitude", ",", "radius", ",", "include", ",", "exclude", ",", "api_key", ",", "days", ")", ":", "self", ".", "_name", "=", "name", "self", ".", "_include", "=", "include", "self", ".", "_exclude", "=", "exclude", "self", ".", "api_key", "=", "api_key", "self", ".", "days", "=", "days", "self", ".", "_spotcrime", "=", "spotcrime", ".", "SpotCrime", "(", "(", "latitude", ",", "longitude", ")", ",", "radius", ",", "self", ".", "_include", ",", "self", ".", "_exclude", ",", "self", ".", "api_key", ",", "self", ".", "days", ",", ")", "self", ".", "_attributes", "=", "None", "self", ".", "_state", "=", "None", "self", ".", "_previous_incidents", "=", "set", "(", ")", "self", ".", "_attributes", "=", "{", "ATTR_ATTRIBUTION", ":", "spotcrime", ".", "ATTRIBUTION", "}" ]
[ 71, 4 ]
[ 92, 68 ]
python
en
['en', 'sq', 'en']
True
SpotCrimeSensor.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" ]
[ 95, 4 ]
[ 97, 25 ]
python
en
['en', 'mi', 'en']
True
SpotCrimeSensor.state
(self)
Return the state of the sensor.
Return the state of the sensor.
def state(self): """Return the state of the sensor.""" return self._state
[ "def", "state", "(", "self", ")", ":", "return", "self", ".", "_state" ]
[ 100, 4 ]
[ 102, 26 ]
python
en
['en', 'en', 'en']
True
SpotCrimeSensor.device_state_attributes
(self)
Return the state attributes.
Return the state attributes.
def device_state_attributes(self): """Return the state attributes.""" return self._attributes
[ "def", "device_state_attributes", "(", "self", ")", ":", "return", "self", ".", "_attributes" ]
[ 105, 4 ]
[ 107, 31 ]
python
en
['en', 'en', 'en']
True
SpotCrimeSensor.update
(self)
Update device state.
Update device state.
def update(self): """Update device state.""" incident_counts = defaultdict(int) incidents = self._spotcrime.get_incidents() if len(incidents) < len(self._previous_incidents): self._previous_incidents = set() for incident in incidents: incident_type = slugify(incident.get("type")) incident_counts[incident_type] += 1 if ( self._previous_incidents and incident.get("id") not in self._previous_incidents ): self._incident_event(incident) self._previous_incidents.add(incident.get("id")) self._attributes.update(incident_counts) self._state = len(incidents)
[ "def", "update", "(", "self", ")", ":", "incident_counts", "=", "defaultdict", "(", "int", ")", "incidents", "=", "self", ".", "_spotcrime", ".", "get_incidents", "(", ")", "if", "len", "(", "incidents", ")", "<", "len", "(", "self", ".", "_previous_incidents", ")", ":", "self", ".", "_previous_incidents", "=", "set", "(", ")", "for", "incident", "in", "incidents", ":", "incident_type", "=", "slugify", "(", "incident", ".", "get", "(", "\"type\"", ")", ")", "incident_counts", "[", "incident_type", "]", "+=", "1", "if", "(", "self", ".", "_previous_incidents", "and", "incident", ".", "get", "(", "\"id\"", ")", "not", "in", "self", ".", "_previous_incidents", ")", ":", "self", ".", "_incident_event", "(", "incident", ")", "self", ".", "_previous_incidents", ".", "add", "(", "incident", ".", "get", "(", "\"id\"", ")", ")", "self", ".", "_attributes", ".", "update", "(", "incident_counts", ")", "self", ".", "_state", "=", "len", "(", "incidents", ")" ]
[ 124, 4 ]
[ 140, 36 ]
python
en
['fr', 'en', 'en']
True
mock_client
()
Pytest fixture for statsd library.
Pytest fixture for statsd library.
def mock_client(): """Pytest fixture for statsd library.""" with patch("statsd.StatsClient") as mock_client: yield mock_client.return_value
[ "def", "mock_client", "(", ")", ":", "with", "patch", "(", "\"statsd.StatsClient\"", ")", "as", "mock_client", ":", "yield", "mock_client", ".", "return_value" ]
[ 15, 0 ]
[ 18, 38 ]
python
en
['en', 'en', 'en']
True
test_invalid_config
()
Test configuration with defaults.
Test configuration with defaults.
def test_invalid_config(): """Test configuration with defaults.""" config = {"statsd": {"host1": "host1"}} with pytest.raises(vol.Invalid): statsd.CONFIG_SCHEMA(None) with pytest.raises(vol.Invalid): statsd.CONFIG_SCHEMA(config)
[ "def", "test_invalid_config", "(", ")", ":", "config", "=", "{", "\"statsd\"", ":", "{", "\"host1\"", ":", "\"host1\"", "}", "}", "with", "pytest", ".", "raises", "(", "vol", ".", "Invalid", ")", ":", "statsd", ".", "CONFIG_SCHEMA", "(", "None", ")", "with", "pytest", ".", "raises", "(", "vol", ".", "Invalid", ")", ":", "statsd", ".", "CONFIG_SCHEMA", "(", "config", ")" ]
[ 21, 0 ]
[ 28, 36 ]
python
en
['en', 'en', 'en']
True
test_statsd_setup_full
(hass)
Test setup with all data.
Test setup with all data.
async def test_statsd_setup_full(hass): """Test setup with all data.""" config = {"statsd": {"host": "host", "port": 123, "rate": 1, "prefix": "foo"}} hass.bus.listen = MagicMock() with patch("statsd.StatsClient") as mock_init: assert await async_setup_component(hass, statsd.DOMAIN, config) assert mock_init.call_count == 1 assert mock_init.call_args == mock.call(host="host", port=123, prefix="foo") assert hass.bus.listen.called assert EVENT_STATE_CHANGED == hass.bus.listen.call_args_list[0][0][0]
[ "async", "def", "test_statsd_setup_full", "(", "hass", ")", ":", "config", "=", "{", "\"statsd\"", ":", "{", "\"host\"", ":", "\"host\"", ",", "\"port\"", ":", "123", ",", "\"rate\"", ":", "1", ",", "\"prefix\"", ":", "\"foo\"", "}", "}", "hass", ".", "bus", ".", "listen", "=", "MagicMock", "(", ")", "with", "patch", "(", "\"statsd.StatsClient\"", ")", "as", "mock_init", ":", "assert", "await", "async_setup_component", "(", "hass", ",", "statsd", ".", "DOMAIN", ",", "config", ")", "assert", "mock_init", ".", "call_count", "==", "1", "assert", "mock_init", ".", "call_args", "==", "mock", ".", "call", "(", "host", "=", "\"host\"", ",", "port", "=", "123", ",", "prefix", "=", "\"foo\"", ")", "assert", "hass", ".", "bus", ".", "listen", ".", "called", "assert", "EVENT_STATE_CHANGED", "==", "hass", ".", "bus", ".", "listen", ".", "call_args_list", "[", "0", "]", "[", "0", "]", "[", "0", "]" ]
[ 31, 0 ]
[ 42, 73 ]
python
en
['en', 'en', 'en']
True
test_statsd_setup_defaults
(hass)
Test setup with defaults.
Test setup with defaults.
async def test_statsd_setup_defaults(hass): """Test setup with defaults.""" config = {"statsd": {"host": "host"}} config["statsd"][statsd.CONF_PORT] = statsd.DEFAULT_PORT config["statsd"][statsd.CONF_PREFIX] = statsd.DEFAULT_PREFIX hass.bus.listen = MagicMock() with patch("statsd.StatsClient") as mock_init: assert await async_setup_component(hass, statsd.DOMAIN, config) assert mock_init.call_count == 1 assert mock_init.call_args == mock.call(host="host", port=8125, prefix="hass") assert hass.bus.listen.called
[ "async", "def", "test_statsd_setup_defaults", "(", "hass", ")", ":", "config", "=", "{", "\"statsd\"", ":", "{", "\"host\"", ":", "\"host\"", "}", "}", "config", "[", "\"statsd\"", "]", "[", "statsd", ".", "CONF_PORT", "]", "=", "statsd", ".", "DEFAULT_PORT", "config", "[", "\"statsd\"", "]", "[", "statsd", ".", "CONF_PREFIX", "]", "=", "statsd", ".", "DEFAULT_PREFIX", "hass", ".", "bus", ".", "listen", "=", "MagicMock", "(", ")", "with", "patch", "(", "\"statsd.StatsClient\"", ")", "as", "mock_init", ":", "assert", "await", "async_setup_component", "(", "hass", ",", "statsd", ".", "DOMAIN", ",", "config", ")", "assert", "mock_init", ".", "call_count", "==", "1", "assert", "mock_init", ".", "call_args", "==", "mock", ".", "call", "(", "host", "=", "\"host\"", ",", "port", "=", "8125", ",", "prefix", "=", "\"hass\"", ")", "assert", "hass", ".", "bus", ".", "listen", ".", "called" ]
[ 45, 0 ]
[ 58, 33 ]
python
en
['en', 'en', 'en']
True
test_event_listener_defaults
(hass, mock_client)
Test event listener.
Test event listener.
async def test_event_listener_defaults(hass, mock_client): """Test event listener.""" config = {"statsd": {"host": "host", "value_mapping": {"custom": 3}}} config["statsd"][statsd.CONF_RATE] = statsd.DEFAULT_RATE hass.bus.listen = MagicMock() await async_setup_component(hass, statsd.DOMAIN, config) assert hass.bus.listen.called handler_method = hass.bus.listen.call_args_list[0][0][1] valid = {"1": 1, "1.0": 1.0, "custom": 3, STATE_ON: 1, STATE_OFF: 0} for in_, out in valid.items(): state = MagicMock(state=in_, attributes={"attribute key": 3.2}) handler_method(MagicMock(data={"new_state": state})) mock_client.gauge.assert_has_calls( [mock.call(state.entity_id, out, statsd.DEFAULT_RATE)] ) mock_client.gauge.reset_mock() assert mock_client.incr.call_count == 1 assert mock_client.incr.call_args == mock.call( state.entity_id, rate=statsd.DEFAULT_RATE ) mock_client.incr.reset_mock() for invalid in ("foo", "", object): handler_method( MagicMock(data={"new_state": ha.State("domain.test", invalid, {})}) ) assert not mock_client.gauge.called assert mock_client.incr.called
[ "async", "def", "test_event_listener_defaults", "(", "hass", ",", "mock_client", ")", ":", "config", "=", "{", "\"statsd\"", ":", "{", "\"host\"", ":", "\"host\"", ",", "\"value_mapping\"", ":", "{", "\"custom\"", ":", "3", "}", "}", "}", "config", "[", "\"statsd\"", "]", "[", "statsd", ".", "CONF_RATE", "]", "=", "statsd", ".", "DEFAULT_RATE", "hass", ".", "bus", ".", "listen", "=", "MagicMock", "(", ")", "await", "async_setup_component", "(", "hass", ",", "statsd", ".", "DOMAIN", ",", "config", ")", "assert", "hass", ".", "bus", ".", "listen", ".", "called", "handler_method", "=", "hass", ".", "bus", ".", "listen", ".", "call_args_list", "[", "0", "]", "[", "0", "]", "[", "1", "]", "valid", "=", "{", "\"1\"", ":", "1", ",", "\"1.0\"", ":", "1.0", ",", "\"custom\"", ":", "3", ",", "STATE_ON", ":", "1", ",", "STATE_OFF", ":", "0", "}", "for", "in_", ",", "out", "in", "valid", ".", "items", "(", ")", ":", "state", "=", "MagicMock", "(", "state", "=", "in_", ",", "attributes", "=", "{", "\"attribute key\"", ":", "3.2", "}", ")", "handler_method", "(", "MagicMock", "(", "data", "=", "{", "\"new_state\"", ":", "state", "}", ")", ")", "mock_client", ".", "gauge", ".", "assert_has_calls", "(", "[", "mock", ".", "call", "(", "state", ".", "entity_id", ",", "out", ",", "statsd", ".", "DEFAULT_RATE", ")", "]", ")", "mock_client", ".", "gauge", ".", "reset_mock", "(", ")", "assert", "mock_client", ".", "incr", ".", "call_count", "==", "1", "assert", "mock_client", ".", "incr", ".", "call_args", "==", "mock", ".", "call", "(", "state", ".", "entity_id", ",", "rate", "=", "statsd", ".", "DEFAULT_RATE", ")", "mock_client", ".", "incr", ".", "reset_mock", "(", ")", "for", "invalid", "in", "(", "\"foo\"", ",", "\"\"", ",", "object", ")", ":", "handler_method", "(", "MagicMock", "(", "data", "=", "{", "\"new_state\"", ":", "ha", ".", "State", "(", "\"domain.test\"", ",", "invalid", ",", "{", "}", ")", "}", ")", ")", "assert", "not", "mock_client", ".", "gauge", ".", "called", "assert", "mock_client", ".", "incr", ".", "called" ]
[ 61, 0 ]
[ 93, 38 ]
python
de
['fr', 'de', 'nl']
False
test_event_listener_attr_details
(hass, mock_client)
Test event listener.
Test event listener.
async def test_event_listener_attr_details(hass, mock_client): """Test event listener.""" config = {"statsd": {"host": "host", "log_attributes": True}} config["statsd"][statsd.CONF_RATE] = statsd.DEFAULT_RATE hass.bus.listen = MagicMock() await async_setup_component(hass, statsd.DOMAIN, config) assert hass.bus.listen.called handler_method = hass.bus.listen.call_args_list[0][0][1] valid = {"1": 1, "1.0": 1.0, STATE_ON: 1, STATE_OFF: 0} for in_, out in valid.items(): state = MagicMock(state=in_, attributes={"attribute key": 3.2}) handler_method(MagicMock(data={"new_state": state})) mock_client.gauge.assert_has_calls( [ mock.call("%s.state" % state.entity_id, out, statsd.DEFAULT_RATE), mock.call( "%s.attribute_key" % state.entity_id, 3.2, statsd.DEFAULT_RATE ), ] ) mock_client.gauge.reset_mock() assert mock_client.incr.call_count == 1 assert mock_client.incr.call_args == mock.call( state.entity_id, rate=statsd.DEFAULT_RATE ) mock_client.incr.reset_mock() for invalid in ("foo", "", object): handler_method( MagicMock(data={"new_state": ha.State("domain.test", invalid, {})}) ) assert not mock_client.gauge.called assert mock_client.incr.called
[ "async", "def", "test_event_listener_attr_details", "(", "hass", ",", "mock_client", ")", ":", "config", "=", "{", "\"statsd\"", ":", "{", "\"host\"", ":", "\"host\"", ",", "\"log_attributes\"", ":", "True", "}", "}", "config", "[", "\"statsd\"", "]", "[", "statsd", ".", "CONF_RATE", "]", "=", "statsd", ".", "DEFAULT_RATE", "hass", ".", "bus", ".", "listen", "=", "MagicMock", "(", ")", "await", "async_setup_component", "(", "hass", ",", "statsd", ".", "DOMAIN", ",", "config", ")", "assert", "hass", ".", "bus", ".", "listen", ".", "called", "handler_method", "=", "hass", ".", "bus", ".", "listen", ".", "call_args_list", "[", "0", "]", "[", "0", "]", "[", "1", "]", "valid", "=", "{", "\"1\"", ":", "1", ",", "\"1.0\"", ":", "1.0", ",", "STATE_ON", ":", "1", ",", "STATE_OFF", ":", "0", "}", "for", "in_", ",", "out", "in", "valid", ".", "items", "(", ")", ":", "state", "=", "MagicMock", "(", "state", "=", "in_", ",", "attributes", "=", "{", "\"attribute key\"", ":", "3.2", "}", ")", "handler_method", "(", "MagicMock", "(", "data", "=", "{", "\"new_state\"", ":", "state", "}", ")", ")", "mock_client", ".", "gauge", ".", "assert_has_calls", "(", "[", "mock", ".", "call", "(", "\"%s.state\"", "%", "state", ".", "entity_id", ",", "out", ",", "statsd", ".", "DEFAULT_RATE", ")", ",", "mock", ".", "call", "(", "\"%s.attribute_key\"", "%", "state", ".", "entity_id", ",", "3.2", ",", "statsd", ".", "DEFAULT_RATE", ")", ",", "]", ")", "mock_client", ".", "gauge", ".", "reset_mock", "(", ")", "assert", "mock_client", ".", "incr", ".", "call_count", "==", "1", "assert", "mock_client", ".", "incr", ".", "call_args", "==", "mock", ".", "call", "(", "state", ".", "entity_id", ",", "rate", "=", "statsd", ".", "DEFAULT_RATE", ")", "mock_client", ".", "incr", ".", "reset_mock", "(", ")", "for", "invalid", "in", "(", "\"foo\"", ",", "\"\"", ",", "object", ")", ":", "handler_method", "(", "MagicMock", "(", "data", "=", "{", "\"new_state\"", ":", "ha", ".", "State", "(", "\"domain.test\"", ",", "invalid", ",", "{", "}", ")", "}", ")", ")", "assert", "not", "mock_client", ".", "gauge", ".", "called", "assert", "mock_client", ".", "incr", ".", "called" ]
[ 96, 0 ]
[ 133, 38 ]
python
de
['fr', 'de', 'nl']
False
async_setup_entry
(hass, entry, async_add_entities)
Set up the Netatmo energy platform.
Set up the Netatmo energy platform.
async def async_setup_entry(hass, entry, async_add_entities): """Set up the Netatmo energy platform.""" data_handler = hass.data[DOMAIN][entry.entry_id][DATA_HANDLER] await data_handler.register_data_class( HOMEDATA_DATA_CLASS_NAME, HOMEDATA_DATA_CLASS_NAME, None ) home_data = data_handler.data.get(HOMEDATA_DATA_CLASS_NAME) if not home_data: return async def get_entities(): """Retrieve Netatmo entities.""" entities = [] for home_id in get_all_home_ids(home_data): _LOGGER.debug("Setting up home %s ...", home_id) for room_id in home_data.rooms[home_id].keys(): room_name = home_data.rooms[home_id][room_id]["name"] _LOGGER.debug("Setting up room %s (%s) ...", room_name, room_id) signal_name = f"{HOMESTATUS_DATA_CLASS_NAME}-{home_id}" await data_handler.register_data_class( HOMESTATUS_DATA_CLASS_NAME, signal_name, None, home_id=home_id ) home_status = data_handler.data.get(signal_name) if home_status and room_id in home_status.rooms: entities.append(NetatmoThermostat(data_handler, home_id, room_id)) hass.data[DOMAIN][DATA_SCHEDULES][home_id] = { schedule_id: schedule_data.get("name") for schedule_id, schedule_data in ( data_handler.data[HOMEDATA_DATA_CLASS_NAME] .schedules[home_id] .items() ) } hass.data[DOMAIN][DATA_HOMES] = { home_id: home_data.get("name") for home_id, home_data in ( data_handler.data[HOMEDATA_DATA_CLASS_NAME].homes.items() ) } return entities async_add_entities(await get_entities(), True) platform = entity_platform.current_platform.get() if home_data is not None: platform.async_register_entity_service( SERVICE_SET_SCHEDULE, {vol.Required(ATTR_SCHEDULE_NAME): cv.string}, "_service_set_schedule", )
[ "async", "def", "async_setup_entry", "(", "hass", ",", "entry", ",", "async_add_entities", ")", ":", "data_handler", "=", "hass", ".", "data", "[", "DOMAIN", "]", "[", "entry", ".", "entry_id", "]", "[", "DATA_HANDLER", "]", "await", "data_handler", ".", "register_data_class", "(", "HOMEDATA_DATA_CLASS_NAME", ",", "HOMEDATA_DATA_CLASS_NAME", ",", "None", ")", "home_data", "=", "data_handler", ".", "data", ".", "get", "(", "HOMEDATA_DATA_CLASS_NAME", ")", "if", "not", "home_data", ":", "return", "async", "def", "get_entities", "(", ")", ":", "\"\"\"Retrieve Netatmo entities.\"\"\"", "entities", "=", "[", "]", "for", "home_id", "in", "get_all_home_ids", "(", "home_data", ")", ":", "_LOGGER", ".", "debug", "(", "\"Setting up home %s ...\"", ",", "home_id", ")", "for", "room_id", "in", "home_data", ".", "rooms", "[", "home_id", "]", ".", "keys", "(", ")", ":", "room_name", "=", "home_data", ".", "rooms", "[", "home_id", "]", "[", "room_id", "]", "[", "\"name\"", "]", "_LOGGER", ".", "debug", "(", "\"Setting up room %s (%s) ...\"", ",", "room_name", ",", "room_id", ")", "signal_name", "=", "f\"{HOMESTATUS_DATA_CLASS_NAME}-{home_id}\"", "await", "data_handler", ".", "register_data_class", "(", "HOMESTATUS_DATA_CLASS_NAME", ",", "signal_name", ",", "None", ",", "home_id", "=", "home_id", ")", "home_status", "=", "data_handler", ".", "data", ".", "get", "(", "signal_name", ")", "if", "home_status", "and", "room_id", "in", "home_status", ".", "rooms", ":", "entities", ".", "append", "(", "NetatmoThermostat", "(", "data_handler", ",", "home_id", ",", "room_id", ")", ")", "hass", ".", "data", "[", "DOMAIN", "]", "[", "DATA_SCHEDULES", "]", "[", "home_id", "]", "=", "{", "schedule_id", ":", "schedule_data", ".", "get", "(", "\"name\"", ")", "for", "schedule_id", ",", "schedule_data", "in", "(", "data_handler", ".", "data", "[", "HOMEDATA_DATA_CLASS_NAME", "]", ".", "schedules", "[", "home_id", "]", ".", "items", "(", ")", ")", "}", "hass", ".", "data", "[", "DOMAIN", "]", "[", "DATA_HOMES", "]", "=", "{", "home_id", ":", "home_data", ".", "get", "(", "\"name\"", ")", "for", "home_id", ",", "home_data", "in", "(", "data_handler", ".", "data", "[", "HOMEDATA_DATA_CLASS_NAME", "]", ".", "homes", ".", "items", "(", ")", ")", "}", "return", "entities", "async_add_entities", "(", "await", "get_entities", "(", ")", ",", "True", ")", "platform", "=", "entity_platform", ".", "current_platform", ".", "get", "(", ")", "if", "home_data", "is", "not", "None", ":", "platform", ".", "async_register_entity_service", "(", "SERVICE_SET_SCHEDULE", ",", "{", "vol", ".", "Required", "(", "ATTR_SCHEDULE_NAME", ")", ":", "cv", ".", "string", "}", ",", "\"_service_set_schedule\"", ",", ")" ]
[ 101, 0 ]
[ 157, 9 ]
python
en
['en', 'zu', 'en']
True
interpolate
(batterylevel, module_type)
Interpolate battery level depending on device type.
Interpolate battery level depending on device type.
def interpolate(batterylevel, module_type): """Interpolate battery level depending on device type.""" na_battery_levels = { NA_THERM: { "full": 4100, "high": 3600, "medium": 3300, "low": 3000, "empty": 2800, }, NA_VALVE: { "full": 3200, "high": 2700, "medium": 2400, "low": 2200, "empty": 2200, }, } levels = sorted(na_battery_levels[module_type].values()) steps = [20, 50, 80, 100] na_battery_level = na_battery_levels[module_type] if batterylevel >= na_battery_level["full"]: return 100 if batterylevel >= na_battery_level["high"]: i = 3 elif batterylevel >= na_battery_level["medium"]: i = 2 elif batterylevel >= na_battery_level["low"]: i = 1 else: return 0 pct = steps[i - 1] + ( (steps[i] - steps[i - 1]) * (batterylevel - levels[i]) / (levels[i + 1] - levels[i]) ) return int(pct)
[ "def", "interpolate", "(", "batterylevel", ",", "module_type", ")", ":", "na_battery_levels", "=", "{", "NA_THERM", ":", "{", "\"full\"", ":", "4100", ",", "\"high\"", ":", "3600", ",", "\"medium\"", ":", "3300", ",", "\"low\"", ":", "3000", ",", "\"empty\"", ":", "2800", ",", "}", ",", "NA_VALVE", ":", "{", "\"full\"", ":", "3200", ",", "\"high\"", ":", "2700", ",", "\"medium\"", ":", "2400", ",", "\"low\"", ":", "2200", ",", "\"empty\"", ":", "2200", ",", "}", ",", "}", "levels", "=", "sorted", "(", "na_battery_levels", "[", "module_type", "]", ".", "values", "(", ")", ")", "steps", "=", "[", "20", ",", "50", ",", "80", ",", "100", "]", "na_battery_level", "=", "na_battery_levels", "[", "module_type", "]", "if", "batterylevel", ">=", "na_battery_level", "[", "\"full\"", "]", ":", "return", "100", "if", "batterylevel", ">=", "na_battery_level", "[", "\"high\"", "]", ":", "i", "=", "3", "elif", "batterylevel", ">=", "na_battery_level", "[", "\"medium\"", "]", ":", "i", "=", "2", "elif", "batterylevel", ">=", "na_battery_level", "[", "\"low\"", "]", ":", "i", "=", "1", "else", ":", "return", "0", "pct", "=", "steps", "[", "i", "-", "1", "]", "+", "(", "(", "steps", "[", "i", "]", "-", "steps", "[", "i", "-", "1", "]", ")", "*", "(", "batterylevel", "-", "levels", "[", "i", "]", ")", "/", "(", "levels", "[", "i", "+", "1", "]", "-", "levels", "[", "i", "]", ")", ")", "return", "int", "(", "pct", ")" ]
[ 534, 0 ]
[ 573, 19 ]
python
en
['fr', 'en', 'en']
True
get_all_home_ids
(home_data)
Get all the home ids returned by NetAtmo API.
Get all the home ids returned by NetAtmo API.
def get_all_home_ids(home_data): """Get all the home ids returned by NetAtmo API.""" if home_data is None: return [] return [ home_data.homes[home_id]["id"] for home_id in home_data.homes if ( "therm_schedules" in home_data.homes[home_id] and "modules" in home_data.homes[home_id] ) ]
[ "def", "get_all_home_ids", "(", "home_data", ")", ":", "if", "home_data", "is", "None", ":", "return", "[", "]", "return", "[", "home_data", ".", "homes", "[", "home_id", "]", "[", "\"id\"", "]", "for", "home_id", "in", "home_data", ".", "homes", "if", "(", "\"therm_schedules\"", "in", "home_data", ".", "homes", "[", "home_id", "]", "and", "\"modules\"", "in", "home_data", ".", "homes", "[", "home_id", "]", ")", "]" ]
[ 576, 0 ]
[ 587, 5 ]
python
en
['en', 'haw', 'en']
True
NetatmoThermostat.__init__
(self, data_handler, home_id, room_id)
Initialize the sensor.
Initialize the sensor.
def __init__(self, data_handler, home_id, room_id): """Initialize the sensor.""" ClimateEntity.__init__(self) super().__init__(data_handler) self._id = room_id self._home_id = home_id self._home_status_class = f"{HOMESTATUS_DATA_CLASS_NAME}-{self._home_id}" self._data_classes.extend( [ { "name": HOMEDATA_DATA_CLASS_NAME, SIGNAL_NAME: HOMEDATA_DATA_CLASS_NAME, }, { "name": HOMESTATUS_DATA_CLASS_NAME, "home_id": self._home_id, SIGNAL_NAME: self._home_status_class, }, ] ) self._home_status = self.data_handler.data[self._home_status_class] self._room_status = self._home_status.rooms[room_id] self._room_data = self._data.rooms[home_id][room_id] self._model = NA_VALVE for module in self._room_data.get("module_ids"): if self._home_status.thermostats.get(module): self._model = NA_THERM break self._state = None self._device_name = self._data.rooms[home_id][room_id]["name"] self._name = f"{MANUFACTURER} {self._device_name}" self._current_temperature = None self._target_temperature = None self._preset = None self._away = None self._operation_list = [HVAC_MODE_AUTO, HVAC_MODE_HEAT] self._support_flags = SUPPORT_FLAGS self._hvac_mode = None self._battery_level = None self._connected = None self._away_temperature = None self._hg_temperature = None self._boilerstatus = None self._setpoint_duration = None if self._model == NA_THERM: self._operation_list.append(HVAC_MODE_OFF) self._unique_id = f"{self._id}-{self._model}"
[ "def", "__init__", "(", "self", ",", "data_handler", ",", "home_id", ",", "room_id", ")", ":", "ClimateEntity", ".", "__init__", "(", "self", ")", "super", "(", ")", ".", "__init__", "(", "data_handler", ")", "self", ".", "_id", "=", "room_id", "self", ".", "_home_id", "=", "home_id", "self", ".", "_home_status_class", "=", "f\"{HOMESTATUS_DATA_CLASS_NAME}-{self._home_id}\"", "self", ".", "_data_classes", ".", "extend", "(", "[", "{", "\"name\"", ":", "HOMEDATA_DATA_CLASS_NAME", ",", "SIGNAL_NAME", ":", "HOMEDATA_DATA_CLASS_NAME", ",", "}", ",", "{", "\"name\"", ":", "HOMESTATUS_DATA_CLASS_NAME", ",", "\"home_id\"", ":", "self", ".", "_home_id", ",", "SIGNAL_NAME", ":", "self", ".", "_home_status_class", ",", "}", ",", "]", ")", "self", ".", "_home_status", "=", "self", ".", "data_handler", ".", "data", "[", "self", ".", "_home_status_class", "]", "self", ".", "_room_status", "=", "self", ".", "_home_status", ".", "rooms", "[", "room_id", "]", "self", ".", "_room_data", "=", "self", ".", "_data", ".", "rooms", "[", "home_id", "]", "[", "room_id", "]", "self", ".", "_model", "=", "NA_VALVE", "for", "module", "in", "self", ".", "_room_data", ".", "get", "(", "\"module_ids\"", ")", ":", "if", "self", ".", "_home_status", ".", "thermostats", ".", "get", "(", "module", ")", ":", "self", ".", "_model", "=", "NA_THERM", "break", "self", ".", "_state", "=", "None", "self", ".", "_device_name", "=", "self", ".", "_data", ".", "rooms", "[", "home_id", "]", "[", "room_id", "]", "[", "\"name\"", "]", "self", ".", "_name", "=", "f\"{MANUFACTURER} {self._device_name}\"", "self", ".", "_current_temperature", "=", "None", "self", ".", "_target_temperature", "=", "None", "self", ".", "_preset", "=", "None", "self", ".", "_away", "=", "None", "self", ".", "_operation_list", "=", "[", "HVAC_MODE_AUTO", ",", "HVAC_MODE_HEAT", "]", "self", ".", "_support_flags", "=", "SUPPORT_FLAGS", "self", ".", "_hvac_mode", "=", "None", "self", ".", "_battery_level", "=", "None", "self", ".", "_connected", "=", "None", "self", ".", "_away_temperature", "=", "None", "self", ".", "_hg_temperature", "=", "None", "self", ".", "_boilerstatus", "=", "None", "self", ".", "_setpoint_duration", "=", "None", "if", "self", ".", "_model", "==", "NA_THERM", ":", "self", ".", "_operation_list", ".", "append", "(", "HVAC_MODE_OFF", ")", "self", ".", "_unique_id", "=", "f\"{self._id}-{self._model}\"" ]
[ 163, 4 ]
[ 218, 53 ]
python
en
['en', 'en', 'en']
True