id
int32 0
252k
| repo
stringlengths 7
55
| path
stringlengths 4
127
| func_name
stringlengths 1
88
| original_string
stringlengths 75
19.8k
| language
stringclasses 1
value | code
stringlengths 51
19.8k
| code_tokens
sequence | docstring
stringlengths 3
17.3k
| docstring_tokens
sequence | sha
stringlengths 40
40
| url
stringlengths 87
242
|
---|---|---|---|---|---|---|---|---|---|---|---|
248,300 | GoogleCloudPlatform/compute-image-packages | packages/python-google-compute-engine/google_compute_engine/accounts/accounts_utils.py | AccountsUtils.SetConfiguredUsers | def SetConfiguredUsers(self, users):
"""Set the list of configured Google user accounts.
Args:
users: list, the username strings of the Linux accounts.
"""
prefix = self.logger.name + '-'
with tempfile.NamedTemporaryFile(
mode='w', prefix=prefix, delete=True) as updated_users:
updated_users_file = updated_users.name
for user in users:
updated_users.write(user + '\n')
updated_users.flush()
if not os.path.exists(self.google_users_dir):
os.makedirs(self.google_users_dir)
shutil.copy(updated_users_file, self.google_users_file)
file_utils.SetPermissions(self.google_users_file, mode=0o600, uid=0, gid=0) | python | def SetConfiguredUsers(self, users):
prefix = self.logger.name + '-'
with tempfile.NamedTemporaryFile(
mode='w', prefix=prefix, delete=True) as updated_users:
updated_users_file = updated_users.name
for user in users:
updated_users.write(user + '\n')
updated_users.flush()
if not os.path.exists(self.google_users_dir):
os.makedirs(self.google_users_dir)
shutil.copy(updated_users_file, self.google_users_file)
file_utils.SetPermissions(self.google_users_file, mode=0o600, uid=0, gid=0) | [
"def",
"SetConfiguredUsers",
"(",
"self",
",",
"users",
")",
":",
"prefix",
"=",
"self",
".",
"logger",
".",
"name",
"+",
"'-'",
"with",
"tempfile",
".",
"NamedTemporaryFile",
"(",
"mode",
"=",
"'w'",
",",
"prefix",
"=",
"prefix",
",",
"delete",
"=",
"True",
")",
"as",
"updated_users",
":",
"updated_users_file",
"=",
"updated_users",
".",
"name",
"for",
"user",
"in",
"users",
":",
"updated_users",
".",
"write",
"(",
"user",
"+",
"'\\n'",
")",
"updated_users",
".",
"flush",
"(",
")",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"self",
".",
"google_users_dir",
")",
":",
"os",
".",
"makedirs",
"(",
"self",
".",
"google_users_dir",
")",
"shutil",
".",
"copy",
"(",
"updated_users_file",
",",
"self",
".",
"google_users_file",
")",
"file_utils",
".",
"SetPermissions",
"(",
"self",
".",
"google_users_file",
",",
"mode",
"=",
"0o600",
",",
"uid",
"=",
"0",
",",
"gid",
"=",
"0",
")"
] | Set the list of configured Google user accounts.
Args:
users: list, the username strings of the Linux accounts. | [
"Set",
"the",
"list",
"of",
"configured",
"Google",
"user",
"accounts",
"."
] | 53ea8cd069fb4d9a1984d1c167e54c133033f8da | https://github.com/GoogleCloudPlatform/compute-image-packages/blob/53ea8cd069fb4d9a1984d1c167e54c133033f8da/packages/python-google-compute-engine/google_compute_engine/accounts/accounts_utils.py#L310-L327 |
248,301 | GoogleCloudPlatform/compute-image-packages | packages/python-google-compute-engine/google_compute_engine/accounts/accounts_utils.py | AccountsUtils.UpdateUser | def UpdateUser(self, user, ssh_keys):
"""Update a Linux user with authorized SSH keys.
Args:
user: string, the name of the Linux user account.
ssh_keys: list, the SSH key strings associated with the user.
Returns:
bool, True if the user account updated successfully.
"""
if not bool(USER_REGEX.match(user)):
self.logger.warning('Invalid user account name %s.', user)
return False
if not self._GetUser(user):
# User does not exist. Attempt to create the user and add them to the
# appropriate user groups.
if not (self._AddUser(user)
and self._UpdateUserGroups(user, self.groups)):
return False
# Add the user to the google sudoers group.
if not self._UpdateSudoer(user, sudoer=True):
return False
# Don't try to manage account SSH keys with a shell set to disable
# logins. This helps avoid problems caused by operator and root sharing
# a home directory in CentOS and RHEL.
pw_entry = self._GetUser(user)
if pw_entry and os.path.basename(pw_entry.pw_shell) == 'nologin':
message = 'Not updating user %s. User set `nologin` as login shell.'
self.logger.debug(message, user)
return True
try:
self._UpdateAuthorizedKeys(user, ssh_keys)
except (IOError, OSError) as e:
message = 'Could not update the authorized keys file for user %s. %s.'
self.logger.warning(message, user, str(e))
return False
else:
return True | python | def UpdateUser(self, user, ssh_keys):
if not bool(USER_REGEX.match(user)):
self.logger.warning('Invalid user account name %s.', user)
return False
if not self._GetUser(user):
# User does not exist. Attempt to create the user and add them to the
# appropriate user groups.
if not (self._AddUser(user)
and self._UpdateUserGroups(user, self.groups)):
return False
# Add the user to the google sudoers group.
if not self._UpdateSudoer(user, sudoer=True):
return False
# Don't try to manage account SSH keys with a shell set to disable
# logins. This helps avoid problems caused by operator and root sharing
# a home directory in CentOS and RHEL.
pw_entry = self._GetUser(user)
if pw_entry and os.path.basename(pw_entry.pw_shell) == 'nologin':
message = 'Not updating user %s. User set `nologin` as login shell.'
self.logger.debug(message, user)
return True
try:
self._UpdateAuthorizedKeys(user, ssh_keys)
except (IOError, OSError) as e:
message = 'Could not update the authorized keys file for user %s. %s.'
self.logger.warning(message, user, str(e))
return False
else:
return True | [
"def",
"UpdateUser",
"(",
"self",
",",
"user",
",",
"ssh_keys",
")",
":",
"if",
"not",
"bool",
"(",
"USER_REGEX",
".",
"match",
"(",
"user",
")",
")",
":",
"self",
".",
"logger",
".",
"warning",
"(",
"'Invalid user account name %s.'",
",",
"user",
")",
"return",
"False",
"if",
"not",
"self",
".",
"_GetUser",
"(",
"user",
")",
":",
"# User does not exist. Attempt to create the user and add them to the",
"# appropriate user groups.",
"if",
"not",
"(",
"self",
".",
"_AddUser",
"(",
"user",
")",
"and",
"self",
".",
"_UpdateUserGroups",
"(",
"user",
",",
"self",
".",
"groups",
")",
")",
":",
"return",
"False",
"# Add the user to the google sudoers group.",
"if",
"not",
"self",
".",
"_UpdateSudoer",
"(",
"user",
",",
"sudoer",
"=",
"True",
")",
":",
"return",
"False",
"# Don't try to manage account SSH keys with a shell set to disable",
"# logins. This helps avoid problems caused by operator and root sharing",
"# a home directory in CentOS and RHEL.",
"pw_entry",
"=",
"self",
".",
"_GetUser",
"(",
"user",
")",
"if",
"pw_entry",
"and",
"os",
".",
"path",
".",
"basename",
"(",
"pw_entry",
".",
"pw_shell",
")",
"==",
"'nologin'",
":",
"message",
"=",
"'Not updating user %s. User set `nologin` as login shell.'",
"self",
".",
"logger",
".",
"debug",
"(",
"message",
",",
"user",
")",
"return",
"True",
"try",
":",
"self",
".",
"_UpdateAuthorizedKeys",
"(",
"user",
",",
"ssh_keys",
")",
"except",
"(",
"IOError",
",",
"OSError",
")",
"as",
"e",
":",
"message",
"=",
"'Could not update the authorized keys file for user %s. %s.'",
"self",
".",
"logger",
".",
"warning",
"(",
"message",
",",
"user",
",",
"str",
"(",
"e",
")",
")",
"return",
"False",
"else",
":",
"return",
"True"
] | Update a Linux user with authorized SSH keys.
Args:
user: string, the name of the Linux user account.
ssh_keys: list, the SSH key strings associated with the user.
Returns:
bool, True if the user account updated successfully. | [
"Update",
"a",
"Linux",
"user",
"with",
"authorized",
"SSH",
"keys",
"."
] | 53ea8cd069fb4d9a1984d1c167e54c133033f8da | https://github.com/GoogleCloudPlatform/compute-image-packages/blob/53ea8cd069fb4d9a1984d1c167e54c133033f8da/packages/python-google-compute-engine/google_compute_engine/accounts/accounts_utils.py#L329-L368 |
248,302 | GoogleCloudPlatform/compute-image-packages | packages/python-google-compute-engine/google_compute_engine/accounts/accounts_utils.py | AccountsUtils.RemoveUser | def RemoveUser(self, user):
"""Remove a Linux user account.
Args:
user: string, the Linux user account to remove.
"""
self.logger.info('Removing user %s.', user)
if self.remove:
command = self.userdel_cmd.format(user=user)
try:
subprocess.check_call(command.split(' '))
except subprocess.CalledProcessError as e:
self.logger.warning('Could not remove user %s. %s.', user, str(e))
else:
self.logger.info('Removed user account %s.', user)
self._RemoveAuthorizedKeys(user)
self._UpdateSudoer(user, sudoer=False) | python | def RemoveUser(self, user):
self.logger.info('Removing user %s.', user)
if self.remove:
command = self.userdel_cmd.format(user=user)
try:
subprocess.check_call(command.split(' '))
except subprocess.CalledProcessError as e:
self.logger.warning('Could not remove user %s. %s.', user, str(e))
else:
self.logger.info('Removed user account %s.', user)
self._RemoveAuthorizedKeys(user)
self._UpdateSudoer(user, sudoer=False) | [
"def",
"RemoveUser",
"(",
"self",
",",
"user",
")",
":",
"self",
".",
"logger",
".",
"info",
"(",
"'Removing user %s.'",
",",
"user",
")",
"if",
"self",
".",
"remove",
":",
"command",
"=",
"self",
".",
"userdel_cmd",
".",
"format",
"(",
"user",
"=",
"user",
")",
"try",
":",
"subprocess",
".",
"check_call",
"(",
"command",
".",
"split",
"(",
"' '",
")",
")",
"except",
"subprocess",
".",
"CalledProcessError",
"as",
"e",
":",
"self",
".",
"logger",
".",
"warning",
"(",
"'Could not remove user %s. %s.'",
",",
"user",
",",
"str",
"(",
"e",
")",
")",
"else",
":",
"self",
".",
"logger",
".",
"info",
"(",
"'Removed user account %s.'",
",",
"user",
")",
"self",
".",
"_RemoveAuthorizedKeys",
"(",
"user",
")",
"self",
".",
"_UpdateSudoer",
"(",
"user",
",",
"sudoer",
"=",
"False",
")"
] | Remove a Linux user account.
Args:
user: string, the Linux user account to remove. | [
"Remove",
"a",
"Linux",
"user",
"account",
"."
] | 53ea8cd069fb4d9a1984d1c167e54c133033f8da | https://github.com/GoogleCloudPlatform/compute-image-packages/blob/53ea8cd069fb4d9a1984d1c167e54c133033f8da/packages/python-google-compute-engine/google_compute_engine/accounts/accounts_utils.py#L370-L386 |
248,303 | GoogleCloudPlatform/compute-image-packages | packages/python-google-compute-engine/google_compute_engine/accounts/oslogin_utils.py | OsLoginUtils._RunOsLoginControl | def _RunOsLoginControl(self, params):
"""Run the OS Login control script.
Args:
params: list, the params to pass to the script
Returns:
int, the return code from the call, or None if the script is not found.
"""
try:
return subprocess.call([constants.OSLOGIN_CONTROL_SCRIPT] + params)
except OSError as e:
if e.errno == errno.ENOENT:
return None
else:
raise | python | def _RunOsLoginControl(self, params):
try:
return subprocess.call([constants.OSLOGIN_CONTROL_SCRIPT] + params)
except OSError as e:
if e.errno == errno.ENOENT:
return None
else:
raise | [
"def",
"_RunOsLoginControl",
"(",
"self",
",",
"params",
")",
":",
"try",
":",
"return",
"subprocess",
".",
"call",
"(",
"[",
"constants",
".",
"OSLOGIN_CONTROL_SCRIPT",
"]",
"+",
"params",
")",
"except",
"OSError",
"as",
"e",
":",
"if",
"e",
".",
"errno",
"==",
"errno",
".",
"ENOENT",
":",
"return",
"None",
"else",
":",
"raise"
] | Run the OS Login control script.
Args:
params: list, the params to pass to the script
Returns:
int, the return code from the call, or None if the script is not found. | [
"Run",
"the",
"OS",
"Login",
"control",
"script",
"."
] | 53ea8cd069fb4d9a1984d1c167e54c133033f8da | https://github.com/GoogleCloudPlatform/compute-image-packages/blob/53ea8cd069fb4d9a1984d1c167e54c133033f8da/packages/python-google-compute-engine/google_compute_engine/accounts/oslogin_utils.py#L41-L56 |
248,304 | GoogleCloudPlatform/compute-image-packages | packages/python-google-compute-engine/google_compute_engine/accounts/oslogin_utils.py | OsLoginUtils._GetStatus | def _GetStatus(self, two_factor=False):
"""Check whether OS Login is installed.
Args:
two_factor: bool, True if two factor should be enabled.
Returns:
bool, True if OS Login is installed.
"""
params = ['status']
if two_factor:
params += ['--twofactor']
retcode = self._RunOsLoginControl(params)
if retcode is None:
if self.oslogin_installed:
self.logger.warning('OS Login not installed.')
self.oslogin_installed = False
return None
# Prevent log spam when OS Login is not installed.
self.oslogin_installed = True
if not os.path.exists(constants.OSLOGIN_NSS_CACHE):
return False
return not retcode | python | def _GetStatus(self, two_factor=False):
params = ['status']
if two_factor:
params += ['--twofactor']
retcode = self._RunOsLoginControl(params)
if retcode is None:
if self.oslogin_installed:
self.logger.warning('OS Login not installed.')
self.oslogin_installed = False
return None
# Prevent log spam when OS Login is not installed.
self.oslogin_installed = True
if not os.path.exists(constants.OSLOGIN_NSS_CACHE):
return False
return not retcode | [
"def",
"_GetStatus",
"(",
"self",
",",
"two_factor",
"=",
"False",
")",
":",
"params",
"=",
"[",
"'status'",
"]",
"if",
"two_factor",
":",
"params",
"+=",
"[",
"'--twofactor'",
"]",
"retcode",
"=",
"self",
".",
"_RunOsLoginControl",
"(",
"params",
")",
"if",
"retcode",
"is",
"None",
":",
"if",
"self",
".",
"oslogin_installed",
":",
"self",
".",
"logger",
".",
"warning",
"(",
"'OS Login not installed.'",
")",
"self",
".",
"oslogin_installed",
"=",
"False",
"return",
"None",
"# Prevent log spam when OS Login is not installed.",
"self",
".",
"oslogin_installed",
"=",
"True",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"constants",
".",
"OSLOGIN_NSS_CACHE",
")",
":",
"return",
"False",
"return",
"not",
"retcode"
] | Check whether OS Login is installed.
Args:
two_factor: bool, True if two factor should be enabled.
Returns:
bool, True if OS Login is installed. | [
"Check",
"whether",
"OS",
"Login",
"is",
"installed",
"."
] | 53ea8cd069fb4d9a1984d1c167e54c133033f8da | https://github.com/GoogleCloudPlatform/compute-image-packages/blob/53ea8cd069fb4d9a1984d1c167e54c133033f8da/packages/python-google-compute-engine/google_compute_engine/accounts/oslogin_utils.py#L58-L81 |
248,305 | GoogleCloudPlatform/compute-image-packages | packages/python-google-compute-engine/google_compute_engine/accounts/oslogin_utils.py | OsLoginUtils._RunOsLoginNssCache | def _RunOsLoginNssCache(self):
"""Run the OS Login NSS cache binary.
Returns:
int, the return code from the call, or None if the script is not found.
"""
try:
return subprocess.call([constants.OSLOGIN_NSS_CACHE_SCRIPT])
except OSError as e:
if e.errno == errno.ENOENT:
return None
else:
raise | python | def _RunOsLoginNssCache(self):
try:
return subprocess.call([constants.OSLOGIN_NSS_CACHE_SCRIPT])
except OSError as e:
if e.errno == errno.ENOENT:
return None
else:
raise | [
"def",
"_RunOsLoginNssCache",
"(",
"self",
")",
":",
"try",
":",
"return",
"subprocess",
".",
"call",
"(",
"[",
"constants",
".",
"OSLOGIN_NSS_CACHE_SCRIPT",
"]",
")",
"except",
"OSError",
"as",
"e",
":",
"if",
"e",
".",
"errno",
"==",
"errno",
".",
"ENOENT",
":",
"return",
"None",
"else",
":",
"raise"
] | Run the OS Login NSS cache binary.
Returns:
int, the return code from the call, or None if the script is not found. | [
"Run",
"the",
"OS",
"Login",
"NSS",
"cache",
"binary",
"."
] | 53ea8cd069fb4d9a1984d1c167e54c133033f8da | https://github.com/GoogleCloudPlatform/compute-image-packages/blob/53ea8cd069fb4d9a1984d1c167e54c133033f8da/packages/python-google-compute-engine/google_compute_engine/accounts/oslogin_utils.py#L83-L95 |
248,306 | GoogleCloudPlatform/compute-image-packages | packages/python-google-compute-engine/google_compute_engine/accounts/oslogin_utils.py | OsLoginUtils._RemoveOsLoginNssCache | def _RemoveOsLoginNssCache(self):
"""Remove the OS Login NSS cache file."""
if os.path.exists(constants.OSLOGIN_NSS_CACHE):
try:
os.remove(constants.OSLOGIN_NSS_CACHE)
except OSError as e:
if e.errno != errno.ENOENT:
raise | python | def _RemoveOsLoginNssCache(self):
if os.path.exists(constants.OSLOGIN_NSS_CACHE):
try:
os.remove(constants.OSLOGIN_NSS_CACHE)
except OSError as e:
if e.errno != errno.ENOENT:
raise | [
"def",
"_RemoveOsLoginNssCache",
"(",
"self",
")",
":",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"constants",
".",
"OSLOGIN_NSS_CACHE",
")",
":",
"try",
":",
"os",
".",
"remove",
"(",
"constants",
".",
"OSLOGIN_NSS_CACHE",
")",
"except",
"OSError",
"as",
"e",
":",
"if",
"e",
".",
"errno",
"!=",
"errno",
".",
"ENOENT",
":",
"raise"
] | Remove the OS Login NSS cache file. | [
"Remove",
"the",
"OS",
"Login",
"NSS",
"cache",
"file",
"."
] | 53ea8cd069fb4d9a1984d1c167e54c133033f8da | https://github.com/GoogleCloudPlatform/compute-image-packages/blob/53ea8cd069fb4d9a1984d1c167e54c133033f8da/packages/python-google-compute-engine/google_compute_engine/accounts/oslogin_utils.py#L97-L104 |
248,307 | GoogleCloudPlatform/compute-image-packages | packages/python-google-compute-engine/google_compute_engine/accounts/oslogin_utils.py | OsLoginUtils.UpdateOsLogin | def UpdateOsLogin(self, oslogin_desired, two_factor_desired=False):
"""Update whether OS Login is enabled and update NSS cache if necessary.
Args:
oslogin_desired: bool, enable OS Login if True, disable if False.
two_factor_desired: bool, enable two factor if True, disable if False.
Returns:
int, the return code from updating OS Login, or None if not present.
"""
oslogin_configured = self._GetStatus(two_factor=False)
if oslogin_configured is None:
return None
two_factor_configured = self._GetStatus(two_factor=True)
# Two factor can only be enabled when OS Login is enabled.
two_factor_desired = two_factor_desired and oslogin_desired
if oslogin_desired:
params = ['activate']
if two_factor_desired:
params += ['--twofactor']
# OS Login is desired and not enabled.
if not oslogin_configured:
self.logger.info('Activating OS Login.')
return self._RunOsLoginControl(params) or self._RunOsLoginNssCache()
# Enable two factor authentication.
if two_factor_desired and not two_factor_configured:
self.logger.info('Activating OS Login two factor authentication.')
return self._RunOsLoginControl(params) or self._RunOsLoginNssCache()
# Deactivate two factor authentication.
if two_factor_configured and not two_factor_desired:
self.logger.info('Reactivating OS Login with two factor disabled.')
return (self._RunOsLoginControl(['deactivate'])
or self._RunOsLoginControl(params))
# OS Login features are already enabled. Update the cache if appropriate.
current_time = time.time()
if current_time - self.update_time > NSS_CACHE_DURATION_SEC:
self.update_time = current_time
return self._RunOsLoginNssCache()
elif oslogin_configured:
self.logger.info('Deactivating OS Login.')
return (self._RunOsLoginControl(['deactivate'])
or self._RemoveOsLoginNssCache())
# No action was needed.
return 0 | python | def UpdateOsLogin(self, oslogin_desired, two_factor_desired=False):
oslogin_configured = self._GetStatus(two_factor=False)
if oslogin_configured is None:
return None
two_factor_configured = self._GetStatus(two_factor=True)
# Two factor can only be enabled when OS Login is enabled.
two_factor_desired = two_factor_desired and oslogin_desired
if oslogin_desired:
params = ['activate']
if two_factor_desired:
params += ['--twofactor']
# OS Login is desired and not enabled.
if not oslogin_configured:
self.logger.info('Activating OS Login.')
return self._RunOsLoginControl(params) or self._RunOsLoginNssCache()
# Enable two factor authentication.
if two_factor_desired and not two_factor_configured:
self.logger.info('Activating OS Login two factor authentication.')
return self._RunOsLoginControl(params) or self._RunOsLoginNssCache()
# Deactivate two factor authentication.
if two_factor_configured and not two_factor_desired:
self.logger.info('Reactivating OS Login with two factor disabled.')
return (self._RunOsLoginControl(['deactivate'])
or self._RunOsLoginControl(params))
# OS Login features are already enabled. Update the cache if appropriate.
current_time = time.time()
if current_time - self.update_time > NSS_CACHE_DURATION_SEC:
self.update_time = current_time
return self._RunOsLoginNssCache()
elif oslogin_configured:
self.logger.info('Deactivating OS Login.')
return (self._RunOsLoginControl(['deactivate'])
or self._RemoveOsLoginNssCache())
# No action was needed.
return 0 | [
"def",
"UpdateOsLogin",
"(",
"self",
",",
"oslogin_desired",
",",
"two_factor_desired",
"=",
"False",
")",
":",
"oslogin_configured",
"=",
"self",
".",
"_GetStatus",
"(",
"two_factor",
"=",
"False",
")",
"if",
"oslogin_configured",
"is",
"None",
":",
"return",
"None",
"two_factor_configured",
"=",
"self",
".",
"_GetStatus",
"(",
"two_factor",
"=",
"True",
")",
"# Two factor can only be enabled when OS Login is enabled.",
"two_factor_desired",
"=",
"two_factor_desired",
"and",
"oslogin_desired",
"if",
"oslogin_desired",
":",
"params",
"=",
"[",
"'activate'",
"]",
"if",
"two_factor_desired",
":",
"params",
"+=",
"[",
"'--twofactor'",
"]",
"# OS Login is desired and not enabled.",
"if",
"not",
"oslogin_configured",
":",
"self",
".",
"logger",
".",
"info",
"(",
"'Activating OS Login.'",
")",
"return",
"self",
".",
"_RunOsLoginControl",
"(",
"params",
")",
"or",
"self",
".",
"_RunOsLoginNssCache",
"(",
")",
"# Enable two factor authentication.",
"if",
"two_factor_desired",
"and",
"not",
"two_factor_configured",
":",
"self",
".",
"logger",
".",
"info",
"(",
"'Activating OS Login two factor authentication.'",
")",
"return",
"self",
".",
"_RunOsLoginControl",
"(",
"params",
")",
"or",
"self",
".",
"_RunOsLoginNssCache",
"(",
")",
"# Deactivate two factor authentication.",
"if",
"two_factor_configured",
"and",
"not",
"two_factor_desired",
":",
"self",
".",
"logger",
".",
"info",
"(",
"'Reactivating OS Login with two factor disabled.'",
")",
"return",
"(",
"self",
".",
"_RunOsLoginControl",
"(",
"[",
"'deactivate'",
"]",
")",
"or",
"self",
".",
"_RunOsLoginControl",
"(",
"params",
")",
")",
"# OS Login features are already enabled. Update the cache if appropriate.",
"current_time",
"=",
"time",
".",
"time",
"(",
")",
"if",
"current_time",
"-",
"self",
".",
"update_time",
">",
"NSS_CACHE_DURATION_SEC",
":",
"self",
".",
"update_time",
"=",
"current_time",
"return",
"self",
".",
"_RunOsLoginNssCache",
"(",
")",
"elif",
"oslogin_configured",
":",
"self",
".",
"logger",
".",
"info",
"(",
"'Deactivating OS Login.'",
")",
"return",
"(",
"self",
".",
"_RunOsLoginControl",
"(",
"[",
"'deactivate'",
"]",
")",
"or",
"self",
".",
"_RemoveOsLoginNssCache",
"(",
")",
")",
"# No action was needed.",
"return",
"0"
] | Update whether OS Login is enabled and update NSS cache if necessary.
Args:
oslogin_desired: bool, enable OS Login if True, disable if False.
two_factor_desired: bool, enable two factor if True, disable if False.
Returns:
int, the return code from updating OS Login, or None if not present. | [
"Update",
"whether",
"OS",
"Login",
"is",
"enabled",
"and",
"update",
"NSS",
"cache",
"if",
"necessary",
"."
] | 53ea8cd069fb4d9a1984d1c167e54c133033f8da | https://github.com/GoogleCloudPlatform/compute-image-packages/blob/53ea8cd069fb4d9a1984d1c167e54c133033f8da/packages/python-google-compute-engine/google_compute_engine/accounts/oslogin_utils.py#L106-L152 |
248,308 | GoogleCloudPlatform/compute-image-packages | packages/python-google-compute-engine/google_compute_engine/distro_lib/helpers.py | CallDhclient | def CallDhclient(
interfaces, logger, dhclient_script=None):
"""Configure the network interfaces using dhclient.
Args:
interfaces: list of string, the output device names to enable.
logger: logger object, used to write to SysLog and serial port.
dhclient_script: string, the path to a dhclient script used by dhclient.
"""
logger.info('Enabling the Ethernet interfaces %s.', interfaces)
dhclient_command = ['dhclient']
if dhclient_script and os.path.exists(dhclient_script):
dhclient_command += ['-sf', dhclient_script]
try:
subprocess.check_call(dhclient_command + ['-x'] + interfaces)
subprocess.check_call(dhclient_command + interfaces)
except subprocess.CalledProcessError:
logger.warning('Could not enable interfaces %s.', interfaces) | python | def CallDhclient(
interfaces, logger, dhclient_script=None):
logger.info('Enabling the Ethernet interfaces %s.', interfaces)
dhclient_command = ['dhclient']
if dhclient_script and os.path.exists(dhclient_script):
dhclient_command += ['-sf', dhclient_script]
try:
subprocess.check_call(dhclient_command + ['-x'] + interfaces)
subprocess.check_call(dhclient_command + interfaces)
except subprocess.CalledProcessError:
logger.warning('Could not enable interfaces %s.', interfaces) | [
"def",
"CallDhclient",
"(",
"interfaces",
",",
"logger",
",",
"dhclient_script",
"=",
"None",
")",
":",
"logger",
".",
"info",
"(",
"'Enabling the Ethernet interfaces %s.'",
",",
"interfaces",
")",
"dhclient_command",
"=",
"[",
"'dhclient'",
"]",
"if",
"dhclient_script",
"and",
"os",
".",
"path",
".",
"exists",
"(",
"dhclient_script",
")",
":",
"dhclient_command",
"+=",
"[",
"'-sf'",
",",
"dhclient_script",
"]",
"try",
":",
"subprocess",
".",
"check_call",
"(",
"dhclient_command",
"+",
"[",
"'-x'",
"]",
"+",
"interfaces",
")",
"subprocess",
".",
"check_call",
"(",
"dhclient_command",
"+",
"interfaces",
")",
"except",
"subprocess",
".",
"CalledProcessError",
":",
"logger",
".",
"warning",
"(",
"'Could not enable interfaces %s.'",
",",
"interfaces",
")"
] | Configure the network interfaces using dhclient.
Args:
interfaces: list of string, the output device names to enable.
logger: logger object, used to write to SysLog and serial port.
dhclient_script: string, the path to a dhclient script used by dhclient. | [
"Configure",
"the",
"network",
"interfaces",
"using",
"dhclient",
"."
] | 53ea8cd069fb4d9a1984d1c167e54c133033f8da | https://github.com/GoogleCloudPlatform/compute-image-packages/blob/53ea8cd069fb4d9a1984d1c167e54c133033f8da/packages/python-google-compute-engine/google_compute_engine/distro_lib/helpers.py#L22-L42 |
248,309 | GoogleCloudPlatform/compute-image-packages | packages/python-google-compute-engine/google_compute_engine/distro_lib/helpers.py | CallHwclock | def CallHwclock(logger):
"""Sync clock using hwclock.
Args:
logger: logger object, used to write to SysLog and serial port.
"""
command = ['/sbin/hwclock', '--hctosys']
try:
subprocess.check_call(command)
except subprocess.CalledProcessError:
logger.warning('Failed to sync system time with hardware clock.')
else:
logger.info('Synced system time with hardware clock.') | python | def CallHwclock(logger):
command = ['/sbin/hwclock', '--hctosys']
try:
subprocess.check_call(command)
except subprocess.CalledProcessError:
logger.warning('Failed to sync system time with hardware clock.')
else:
logger.info('Synced system time with hardware clock.') | [
"def",
"CallHwclock",
"(",
"logger",
")",
":",
"command",
"=",
"[",
"'/sbin/hwclock'",
",",
"'--hctosys'",
"]",
"try",
":",
"subprocess",
".",
"check_call",
"(",
"command",
")",
"except",
"subprocess",
".",
"CalledProcessError",
":",
"logger",
".",
"warning",
"(",
"'Failed to sync system time with hardware clock.'",
")",
"else",
":",
"logger",
".",
"info",
"(",
"'Synced system time with hardware clock.'",
")"
] | Sync clock using hwclock.
Args:
logger: logger object, used to write to SysLog and serial port. | [
"Sync",
"clock",
"using",
"hwclock",
"."
] | 53ea8cd069fb4d9a1984d1c167e54c133033f8da | https://github.com/GoogleCloudPlatform/compute-image-packages/blob/53ea8cd069fb4d9a1984d1c167e54c133033f8da/packages/python-google-compute-engine/google_compute_engine/distro_lib/helpers.py#L45-L57 |
248,310 | GoogleCloudPlatform/compute-image-packages | packages/python-google-compute-engine/google_compute_engine/distro_lib/helpers.py | CallNtpdate | def CallNtpdate(logger):
"""Sync clock using ntpdate.
Args:
logger: logger object, used to write to SysLog and serial port.
"""
ntpd_inactive = subprocess.call(['service', 'ntpd', 'status'])
try:
if not ntpd_inactive:
subprocess.check_call(['service', 'ntpd', 'stop'])
subprocess.check_call(
'ntpdate `awk \'$1=="server" {print $2}\' /etc/ntp.conf`', shell=True)
if not ntpd_inactive:
subprocess.check_call(['service', 'ntpd', 'start'])
except subprocess.CalledProcessError:
logger.warning('Failed to sync system time with ntp server.')
else:
logger.info('Synced system time with ntp server.') | python | def CallNtpdate(logger):
ntpd_inactive = subprocess.call(['service', 'ntpd', 'status'])
try:
if not ntpd_inactive:
subprocess.check_call(['service', 'ntpd', 'stop'])
subprocess.check_call(
'ntpdate `awk \'$1=="server" {print $2}\' /etc/ntp.conf`', shell=True)
if not ntpd_inactive:
subprocess.check_call(['service', 'ntpd', 'start'])
except subprocess.CalledProcessError:
logger.warning('Failed to sync system time with ntp server.')
else:
logger.info('Synced system time with ntp server.') | [
"def",
"CallNtpdate",
"(",
"logger",
")",
":",
"ntpd_inactive",
"=",
"subprocess",
".",
"call",
"(",
"[",
"'service'",
",",
"'ntpd'",
",",
"'status'",
"]",
")",
"try",
":",
"if",
"not",
"ntpd_inactive",
":",
"subprocess",
".",
"check_call",
"(",
"[",
"'service'",
",",
"'ntpd'",
",",
"'stop'",
"]",
")",
"subprocess",
".",
"check_call",
"(",
"'ntpdate `awk \\'$1==\"server\" {print $2}\\' /etc/ntp.conf`'",
",",
"shell",
"=",
"True",
")",
"if",
"not",
"ntpd_inactive",
":",
"subprocess",
".",
"check_call",
"(",
"[",
"'service'",
",",
"'ntpd'",
",",
"'start'",
"]",
")",
"except",
"subprocess",
".",
"CalledProcessError",
":",
"logger",
".",
"warning",
"(",
"'Failed to sync system time with ntp server.'",
")",
"else",
":",
"logger",
".",
"info",
"(",
"'Synced system time with ntp server.'",
")"
] | Sync clock using ntpdate.
Args:
logger: logger object, used to write to SysLog and serial port. | [
"Sync",
"clock",
"using",
"ntpdate",
"."
] | 53ea8cd069fb4d9a1984d1c167e54c133033f8da | https://github.com/GoogleCloudPlatform/compute-image-packages/blob/53ea8cd069fb4d9a1984d1c167e54c133033f8da/packages/python-google-compute-engine/google_compute_engine/distro_lib/helpers.py#L60-L77 |
248,311 | GoogleCloudPlatform/compute-image-packages | packages/python-google-compute-engine/google_compute_engine/boto/boto_config.py | BotoConfig._GetNumericProjectId | def _GetNumericProjectId(self):
"""Get the numeric project ID for this VM.
Returns:
string, the numeric project ID if one is found.
"""
project_id = 'project/numeric-project-id'
return self.watcher.GetMetadata(metadata_key=project_id, recursive=False) | python | def _GetNumericProjectId(self):
project_id = 'project/numeric-project-id'
return self.watcher.GetMetadata(metadata_key=project_id, recursive=False) | [
"def",
"_GetNumericProjectId",
"(",
"self",
")",
":",
"project_id",
"=",
"'project/numeric-project-id'",
"return",
"self",
".",
"watcher",
".",
"GetMetadata",
"(",
"metadata_key",
"=",
"project_id",
",",
"recursive",
"=",
"False",
")"
] | Get the numeric project ID for this VM.
Returns:
string, the numeric project ID if one is found. | [
"Get",
"the",
"numeric",
"project",
"ID",
"for",
"this",
"VM",
"."
] | 53ea8cd069fb4d9a1984d1c167e54c133033f8da | https://github.com/GoogleCloudPlatform/compute-image-packages/blob/53ea8cd069fb4d9a1984d1c167e54c133033f8da/packages/python-google-compute-engine/google_compute_engine/boto/boto_config.py#L57-L64 |
248,312 | GoogleCloudPlatform/compute-image-packages | packages/python-google-compute-engine/google_compute_engine/boto/boto_config.py | BotoConfig._CreateConfig | def _CreateConfig(self, project_id):
"""Create the boto config to support standalone GSUtil.
Args:
project_id: string, the project ID to use in the config file.
"""
project_id = project_id or self._GetNumericProjectId()
# Our project doesn't support service accounts.
if not project_id:
return
self.boto_config_header %= (
self.boto_config_script, self.boto_config_template)
config = config_manager.ConfigManager(
config_file=self.boto_config_template,
config_header=self.boto_config_header)
boto_dir = os.path.dirname(self.boto_config_script)
config.SetOption('GSUtil', 'default_project_id', project_id)
config.SetOption('GSUtil', 'default_api_version', '2')
config.SetOption('GoogleCompute', 'service_account', 'default')
config.SetOption('Plugin', 'plugin_directory', boto_dir)
config.WriteConfig(config_file=self.boto_config) | python | def _CreateConfig(self, project_id):
project_id = project_id or self._GetNumericProjectId()
# Our project doesn't support service accounts.
if not project_id:
return
self.boto_config_header %= (
self.boto_config_script, self.boto_config_template)
config = config_manager.ConfigManager(
config_file=self.boto_config_template,
config_header=self.boto_config_header)
boto_dir = os.path.dirname(self.boto_config_script)
config.SetOption('GSUtil', 'default_project_id', project_id)
config.SetOption('GSUtil', 'default_api_version', '2')
config.SetOption('GoogleCompute', 'service_account', 'default')
config.SetOption('Plugin', 'plugin_directory', boto_dir)
config.WriteConfig(config_file=self.boto_config) | [
"def",
"_CreateConfig",
"(",
"self",
",",
"project_id",
")",
":",
"project_id",
"=",
"project_id",
"or",
"self",
".",
"_GetNumericProjectId",
"(",
")",
"# Our project doesn't support service accounts.",
"if",
"not",
"project_id",
":",
"return",
"self",
".",
"boto_config_header",
"%=",
"(",
"self",
".",
"boto_config_script",
",",
"self",
".",
"boto_config_template",
")",
"config",
"=",
"config_manager",
".",
"ConfigManager",
"(",
"config_file",
"=",
"self",
".",
"boto_config_template",
",",
"config_header",
"=",
"self",
".",
"boto_config_header",
")",
"boto_dir",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"self",
".",
"boto_config_script",
")",
"config",
".",
"SetOption",
"(",
"'GSUtil'",
",",
"'default_project_id'",
",",
"project_id",
")",
"config",
".",
"SetOption",
"(",
"'GSUtil'",
",",
"'default_api_version'",
",",
"'2'",
")",
"config",
".",
"SetOption",
"(",
"'GoogleCompute'",
",",
"'service_account'",
",",
"'default'",
")",
"config",
".",
"SetOption",
"(",
"'Plugin'",
",",
"'plugin_directory'",
",",
"boto_dir",
")",
"config",
".",
"WriteConfig",
"(",
"config_file",
"=",
"self",
".",
"boto_config",
")"
] | Create the boto config to support standalone GSUtil.
Args:
project_id: string, the project ID to use in the config file. | [
"Create",
"the",
"boto",
"config",
"to",
"support",
"standalone",
"GSUtil",
"."
] | 53ea8cd069fb4d9a1984d1c167e54c133033f8da | https://github.com/GoogleCloudPlatform/compute-image-packages/blob/53ea8cd069fb4d9a1984d1c167e54c133033f8da/packages/python-google-compute-engine/google_compute_engine/boto/boto_config.py#L66-L89 |
248,313 | GoogleCloudPlatform/compute-image-packages | packages/python-google-compute-engine/google_compute_engine/distro_lib/ip_forwarding_utils.py | IpForwardingUtilsIproute._CreateRouteOptions | def _CreateRouteOptions(self, **kwargs):
"""Create a dictionary of parameters to append to the ip route command.
Args:
**kwargs: dict, the string parameters to update in the ip route command.
Returns:
dict, the string parameters to append to the ip route command.
"""
options = {
'proto': self.proto_id,
'scope': 'host',
}
options.update(kwargs)
return options | python | def _CreateRouteOptions(self, **kwargs):
options = {
'proto': self.proto_id,
'scope': 'host',
}
options.update(kwargs)
return options | [
"def",
"_CreateRouteOptions",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"options",
"=",
"{",
"'proto'",
":",
"self",
".",
"proto_id",
",",
"'scope'",
":",
"'host'",
",",
"}",
"options",
".",
"update",
"(",
"kwargs",
")",
"return",
"options"
] | Create a dictionary of parameters to append to the ip route command.
Args:
**kwargs: dict, the string parameters to update in the ip route command.
Returns:
dict, the string parameters to append to the ip route command. | [
"Create",
"a",
"dictionary",
"of",
"parameters",
"to",
"append",
"to",
"the",
"ip",
"route",
"command",
"."
] | 53ea8cd069fb4d9a1984d1c167e54c133033f8da | https://github.com/GoogleCloudPlatform/compute-image-packages/blob/53ea8cd069fb4d9a1984d1c167e54c133033f8da/packages/python-google-compute-engine/google_compute_engine/distro_lib/ip_forwarding_utils.py#L97-L111 |
248,314 | GoogleCloudPlatform/compute-image-packages | packages/python-google-compute-engine/google_compute_engine/distro_lib/ip_forwarding_utils.py | IpForwardingUtilsIproute._RunIpRoute | def _RunIpRoute(self, args=None, options=None):
"""Run a command with ip route and return the response.
Args:
args: list, the string ip route command args to execute.
options: dict, the string parameters to append to the ip route command.
Returns:
string, the standard output from the ip route command execution.
"""
args = args or []
options = options or {}
command = ['ip', 'route']
command.extend(args)
for item in options.items():
command.extend(item)
try:
process = subprocess.Popen(
command, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
stdout, stderr = process.communicate()
except OSError as e:
self.logger.warning('Exception running %s. %s.', command, str(e))
else:
if process.returncode:
message = 'Non-zero exit status running %s. %s.'
self.logger.warning(message, command, stderr.strip())
else:
return stdout.decode('utf-8', 'replace')
return '' | python | def _RunIpRoute(self, args=None, options=None):
args = args or []
options = options or {}
command = ['ip', 'route']
command.extend(args)
for item in options.items():
command.extend(item)
try:
process = subprocess.Popen(
command, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
stdout, stderr = process.communicate()
except OSError as e:
self.logger.warning('Exception running %s. %s.', command, str(e))
else:
if process.returncode:
message = 'Non-zero exit status running %s. %s.'
self.logger.warning(message, command, stderr.strip())
else:
return stdout.decode('utf-8', 'replace')
return '' | [
"def",
"_RunIpRoute",
"(",
"self",
",",
"args",
"=",
"None",
",",
"options",
"=",
"None",
")",
":",
"args",
"=",
"args",
"or",
"[",
"]",
"options",
"=",
"options",
"or",
"{",
"}",
"command",
"=",
"[",
"'ip'",
",",
"'route'",
"]",
"command",
".",
"extend",
"(",
"args",
")",
"for",
"item",
"in",
"options",
".",
"items",
"(",
")",
":",
"command",
".",
"extend",
"(",
"item",
")",
"try",
":",
"process",
"=",
"subprocess",
".",
"Popen",
"(",
"command",
",",
"stdout",
"=",
"subprocess",
".",
"PIPE",
",",
"stderr",
"=",
"subprocess",
".",
"PIPE",
")",
"stdout",
",",
"stderr",
"=",
"process",
".",
"communicate",
"(",
")",
"except",
"OSError",
"as",
"e",
":",
"self",
".",
"logger",
".",
"warning",
"(",
"'Exception running %s. %s.'",
",",
"command",
",",
"str",
"(",
"e",
")",
")",
"else",
":",
"if",
"process",
".",
"returncode",
":",
"message",
"=",
"'Non-zero exit status running %s. %s.'",
"self",
".",
"logger",
".",
"warning",
"(",
"message",
",",
"command",
",",
"stderr",
".",
"strip",
"(",
")",
")",
"else",
":",
"return",
"stdout",
".",
"decode",
"(",
"'utf-8'",
",",
"'replace'",
")",
"return",
"''"
] | Run a command with ip route and return the response.
Args:
args: list, the string ip route command args to execute.
options: dict, the string parameters to append to the ip route command.
Returns:
string, the standard output from the ip route command execution. | [
"Run",
"a",
"command",
"with",
"ip",
"route",
"and",
"return",
"the",
"response",
"."
] | 53ea8cd069fb4d9a1984d1c167e54c133033f8da | https://github.com/GoogleCloudPlatform/compute-image-packages/blob/53ea8cd069fb4d9a1984d1c167e54c133033f8da/packages/python-google-compute-engine/google_compute_engine/distro_lib/ip_forwarding_utils.py#L113-L141 |
248,315 | GoogleCloudPlatform/compute-image-packages | packages/python-google-compute-engine/google_compute_engine/distro_lib/ip_forwarding_utils.py | IpForwardingUtilsIfconfig.RemoveForwardedIp | def RemoveForwardedIp(self, address, interface):
"""Delete an IP address on the network interface.
Args:
address: string, the IP address to configure.
interface: string, the output device to use.
"""
ip = netaddr.IPNetwork(address)
self._RunIfconfig(args=[interface, '-alias', str(ip.ip)]) | python | def RemoveForwardedIp(self, address, interface):
ip = netaddr.IPNetwork(address)
self._RunIfconfig(args=[interface, '-alias', str(ip.ip)]) | [
"def",
"RemoveForwardedIp",
"(",
"self",
",",
"address",
",",
"interface",
")",
":",
"ip",
"=",
"netaddr",
".",
"IPNetwork",
"(",
"address",
")",
"self",
".",
"_RunIfconfig",
"(",
"args",
"=",
"[",
"interface",
",",
"'-alias'",
",",
"str",
"(",
"ip",
".",
"ip",
")",
"]",
")"
] | Delete an IP address on the network interface.
Args:
address: string, the IP address to configure.
interface: string, the output device to use. | [
"Delete",
"an",
"IP",
"address",
"on",
"the",
"network",
"interface",
"."
] | 53ea8cd069fb4d9a1984d1c167e54c133033f8da | https://github.com/GoogleCloudPlatform/compute-image-packages/blob/53ea8cd069fb4d9a1984d1c167e54c133033f8da/packages/python-google-compute-engine/google_compute_engine/distro_lib/ip_forwarding_utils.py#L294-L302 |
248,316 | GoogleCloudPlatform/compute-image-packages | packages/python-google-compute-engine/google_compute_engine/boto/compute_auth.py | ComputeAuth._GetGsScopes | def _GetGsScopes(self):
"""Return all Google Storage scopes available on this VM."""
service_accounts = self.watcher.GetMetadata(metadata_key=self.metadata_key)
try:
scopes = service_accounts[self.service_account]['scopes']
return list(GS_SCOPES.intersection(set(scopes))) if scopes else None
except KeyError:
return None | python | def _GetGsScopes(self):
service_accounts = self.watcher.GetMetadata(metadata_key=self.metadata_key)
try:
scopes = service_accounts[self.service_account]['scopes']
return list(GS_SCOPES.intersection(set(scopes))) if scopes else None
except KeyError:
return None | [
"def",
"_GetGsScopes",
"(",
"self",
")",
":",
"service_accounts",
"=",
"self",
".",
"watcher",
".",
"GetMetadata",
"(",
"metadata_key",
"=",
"self",
".",
"metadata_key",
")",
"try",
":",
"scopes",
"=",
"service_accounts",
"[",
"self",
".",
"service_account",
"]",
"[",
"'scopes'",
"]",
"return",
"list",
"(",
"GS_SCOPES",
".",
"intersection",
"(",
"set",
"(",
"scopes",
")",
")",
")",
"if",
"scopes",
"else",
"None",
"except",
"KeyError",
":",
"return",
"None"
] | Return all Google Storage scopes available on this VM. | [
"Return",
"all",
"Google",
"Storage",
"scopes",
"available",
"on",
"this",
"VM",
"."
] | 53ea8cd069fb4d9a1984d1c167e54c133033f8da | https://github.com/GoogleCloudPlatform/compute-image-packages/blob/53ea8cd069fb4d9a1984d1c167e54c133033f8da/packages/python-google-compute-engine/google_compute_engine/boto/compute_auth.py#L50-L57 |
248,317 | GoogleCloudPlatform/compute-image-packages | packages/python-google-compute-engine/google_compute_engine/boto/compute_auth.py | ComputeAuth._GetAccessToken | def _GetAccessToken(self):
"""Return an OAuth 2.0 access token for Google Storage."""
service_accounts = self.watcher.GetMetadata(metadata_key=self.metadata_key)
try:
return service_accounts[self.service_account]['token']['access_token']
except KeyError:
return None | python | def _GetAccessToken(self):
service_accounts = self.watcher.GetMetadata(metadata_key=self.metadata_key)
try:
return service_accounts[self.service_account]['token']['access_token']
except KeyError:
return None | [
"def",
"_GetAccessToken",
"(",
"self",
")",
":",
"service_accounts",
"=",
"self",
".",
"watcher",
".",
"GetMetadata",
"(",
"metadata_key",
"=",
"self",
".",
"metadata_key",
")",
"try",
":",
"return",
"service_accounts",
"[",
"self",
".",
"service_account",
"]",
"[",
"'token'",
"]",
"[",
"'access_token'",
"]",
"except",
"KeyError",
":",
"return",
"None"
] | Return an OAuth 2.0 access token for Google Storage. | [
"Return",
"an",
"OAuth",
"2",
".",
"0",
"access",
"token",
"for",
"Google",
"Storage",
"."
] | 53ea8cd069fb4d9a1984d1c167e54c133033f8da | https://github.com/GoogleCloudPlatform/compute-image-packages/blob/53ea8cd069fb4d9a1984d1c167e54c133033f8da/packages/python-google-compute-engine/google_compute_engine/boto/compute_auth.py#L59-L65 |
248,318 | GoogleCloudPlatform/compute-image-packages | packages/python-google-compute-engine/google_compute_engine/clock_skew/clock_skew_daemon.py | ClockSkewDaemon.HandleClockSync | def HandleClockSync(self, response):
"""Called when clock drift token changes.
Args:
response: string, the metadata response with the new drift token value.
"""
self.logger.info('Clock drift token has changed: %s.', response)
self.distro_utils.HandleClockSync(self.logger) | python | def HandleClockSync(self, response):
self.logger.info('Clock drift token has changed: %s.', response)
self.distro_utils.HandleClockSync(self.logger) | [
"def",
"HandleClockSync",
"(",
"self",
",",
"response",
")",
":",
"self",
".",
"logger",
".",
"info",
"(",
"'Clock drift token has changed: %s.'",
",",
"response",
")",
"self",
".",
"distro_utils",
".",
"HandleClockSync",
"(",
"self",
".",
"logger",
")"
] | Called when clock drift token changes.
Args:
response: string, the metadata response with the new drift token value. | [
"Called",
"when",
"clock",
"drift",
"token",
"changes",
"."
] | 53ea8cd069fb4d9a1984d1c167e54c133033f8da | https://github.com/GoogleCloudPlatform/compute-image-packages/blob/53ea8cd069fb4d9a1984d1c167e54c133033f8da/packages/python-google-compute-engine/google_compute_engine/clock_skew/clock_skew_daemon.py#L56-L63 |
248,319 | GoogleCloudPlatform/compute-image-packages | packages/python-google-compute-engine/google_compute_engine/distro_lib/el_7/utils.py | Utils._DisableNetworkManager | def _DisableNetworkManager(self, interfaces, logger):
"""Disable network manager management on a list of network interfaces.
Args:
interfaces: list of string, the output device names enable.
logger: logger object, used to write to SysLog and serial port.
"""
for interface in interfaces:
interface_config = os.path.join(
self.network_path, 'ifcfg-%s' % interface)
if os.path.exists(interface_config):
self._ModifyInterface(
interface_config, 'DEVICE', interface, replace=False)
self._ModifyInterface(
interface_config, 'NM_CONTROLLED', 'no', replace=True)
else:
with open(interface_config, 'w') as interface_file:
interface_content = [
'# Added by Google.',
'BOOTPROTO=none',
'DEFROUTE=no',
'DEVICE=%s' % interface,
'IPV6INIT=no',
'NM_CONTROLLED=no',
'NOZEROCONF=yes',
'',
]
interface_file.write('\n'.join(interface_content))
logger.info('Created config file for interface %s.', interface) | python | def _DisableNetworkManager(self, interfaces, logger):
for interface in interfaces:
interface_config = os.path.join(
self.network_path, 'ifcfg-%s' % interface)
if os.path.exists(interface_config):
self._ModifyInterface(
interface_config, 'DEVICE', interface, replace=False)
self._ModifyInterface(
interface_config, 'NM_CONTROLLED', 'no', replace=True)
else:
with open(interface_config, 'w') as interface_file:
interface_content = [
'# Added by Google.',
'BOOTPROTO=none',
'DEFROUTE=no',
'DEVICE=%s' % interface,
'IPV6INIT=no',
'NM_CONTROLLED=no',
'NOZEROCONF=yes',
'',
]
interface_file.write('\n'.join(interface_content))
logger.info('Created config file for interface %s.', interface) | [
"def",
"_DisableNetworkManager",
"(",
"self",
",",
"interfaces",
",",
"logger",
")",
":",
"for",
"interface",
"in",
"interfaces",
":",
"interface_config",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"network_path",
",",
"'ifcfg-%s'",
"%",
"interface",
")",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"interface_config",
")",
":",
"self",
".",
"_ModifyInterface",
"(",
"interface_config",
",",
"'DEVICE'",
",",
"interface",
",",
"replace",
"=",
"False",
")",
"self",
".",
"_ModifyInterface",
"(",
"interface_config",
",",
"'NM_CONTROLLED'",
",",
"'no'",
",",
"replace",
"=",
"True",
")",
"else",
":",
"with",
"open",
"(",
"interface_config",
",",
"'w'",
")",
"as",
"interface_file",
":",
"interface_content",
"=",
"[",
"'# Added by Google.'",
",",
"'BOOTPROTO=none'",
",",
"'DEFROUTE=no'",
",",
"'DEVICE=%s'",
"%",
"interface",
",",
"'IPV6INIT=no'",
",",
"'NM_CONTROLLED=no'",
",",
"'NOZEROCONF=yes'",
",",
"''",
",",
"]",
"interface_file",
".",
"write",
"(",
"'\\n'",
".",
"join",
"(",
"interface_content",
")",
")",
"logger",
".",
"info",
"(",
"'Created config file for interface %s.'",
",",
"interface",
")"
] | Disable network manager management on a list of network interfaces.
Args:
interfaces: list of string, the output device names enable.
logger: logger object, used to write to SysLog and serial port. | [
"Disable",
"network",
"manager",
"management",
"on",
"a",
"list",
"of",
"network",
"interfaces",
"."
] | 53ea8cd069fb4d9a1984d1c167e54c133033f8da | https://github.com/GoogleCloudPlatform/compute-image-packages/blob/53ea8cd069fb4d9a1984d1c167e54c133033f8da/packages/python-google-compute-engine/google_compute_engine/distro_lib/el_7/utils.py#L47-L75 |
248,320 | GoogleCloudPlatform/compute-image-packages | packages/python-google-compute-engine/google_compute_engine/distro_lib/el_7/utils.py | Utils._ModifyInterface | def _ModifyInterface(
self, interface_config, config_key, config_value, replace=False):
"""Write a value to a config file if not already present.
Args:
interface_config: string, the path to a config file.
config_key: string, the configuration key to set.
config_value: string, the value to set for the configuration key.
replace: bool, replace the configuration option if already present.
"""
config_entry = '%s=%s' % (config_key, config_value)
if not open(interface_config).read().count(config_key):
with open(interface_config, 'a') as config:
config.write('%s\n' % config_entry)
elif replace:
for line in fileinput.input(interface_config, inplace=True):
print(re.sub(r'%s=.*' % config_key, config_entry, line.rstrip())) | python | def _ModifyInterface(
self, interface_config, config_key, config_value, replace=False):
config_entry = '%s=%s' % (config_key, config_value)
if not open(interface_config).read().count(config_key):
with open(interface_config, 'a') as config:
config.write('%s\n' % config_entry)
elif replace:
for line in fileinput.input(interface_config, inplace=True):
print(re.sub(r'%s=.*' % config_key, config_entry, line.rstrip())) | [
"def",
"_ModifyInterface",
"(",
"self",
",",
"interface_config",
",",
"config_key",
",",
"config_value",
",",
"replace",
"=",
"False",
")",
":",
"config_entry",
"=",
"'%s=%s'",
"%",
"(",
"config_key",
",",
"config_value",
")",
"if",
"not",
"open",
"(",
"interface_config",
")",
".",
"read",
"(",
")",
".",
"count",
"(",
"config_key",
")",
":",
"with",
"open",
"(",
"interface_config",
",",
"'a'",
")",
"as",
"config",
":",
"config",
".",
"write",
"(",
"'%s\\n'",
"%",
"config_entry",
")",
"elif",
"replace",
":",
"for",
"line",
"in",
"fileinput",
".",
"input",
"(",
"interface_config",
",",
"inplace",
"=",
"True",
")",
":",
"print",
"(",
"re",
".",
"sub",
"(",
"r'%s=.*'",
"%",
"config_key",
",",
"config_entry",
",",
"line",
".",
"rstrip",
"(",
")",
")",
")"
] | Write a value to a config file if not already present.
Args:
interface_config: string, the path to a config file.
config_key: string, the configuration key to set.
config_value: string, the value to set for the configuration key.
replace: bool, replace the configuration option if already present. | [
"Write",
"a",
"value",
"to",
"a",
"config",
"file",
"if",
"not",
"already",
"present",
"."
] | 53ea8cd069fb4d9a1984d1c167e54c133033f8da | https://github.com/GoogleCloudPlatform/compute-image-packages/blob/53ea8cd069fb4d9a1984d1c167e54c133033f8da/packages/python-google-compute-engine/google_compute_engine/distro_lib/el_7/utils.py#L77-L93 |
248,321 | GoogleCloudPlatform/compute-image-packages | packages/python-google-compute-engine/google_compute_engine/accounts/accounts_daemon.py | AccountsDaemon._HasExpired | def _HasExpired(self, key):
"""Check whether an SSH key has expired.
Uses Google-specific semantics of the OpenSSH public key format's comment
field to determine if an SSH key is past its expiration timestamp, and
therefore no longer to be trusted. This format is still subject to change.
Reliance on it in any way is at your own risk.
Args:
key: string, a single public key entry in OpenSSH public key file format.
This will be checked for Google-specific comment semantics, and if
present, those will be analysed.
Returns:
bool, True if the key has Google-specific comment semantics and has an
expiration timestamp in the past, or False otherwise.
"""
self.logger.debug('Processing key: %s.', key)
try:
schema, json_str = key.split(None, 3)[2:]
except (ValueError, AttributeError):
self.logger.debug('No schema identifier. Not expiring key.')
return False
if schema != 'google-ssh':
self.logger.debug('Invalid schema %s. Not expiring key.', schema)
return False
try:
json_obj = json.loads(json_str)
except ValueError:
self.logger.debug('Invalid JSON %s. Not expiring key.', json_str)
return False
if 'expireOn' not in json_obj:
self.logger.debug('No expiration timestamp. Not expiring key.')
return False
expire_str = json_obj['expireOn']
format_str = '%Y-%m-%dT%H:%M:%S+0000'
try:
expire_time = datetime.datetime.strptime(expire_str, format_str)
except ValueError:
self.logger.warning(
'Expiration timestamp "%s" not in format %s. Not expiring key.',
expire_str, format_str)
return False
# Expire the key if and only if we have exceeded the expiration timestamp.
return datetime.datetime.utcnow() > expire_time | python | def _HasExpired(self, key):
self.logger.debug('Processing key: %s.', key)
try:
schema, json_str = key.split(None, 3)[2:]
except (ValueError, AttributeError):
self.logger.debug('No schema identifier. Not expiring key.')
return False
if schema != 'google-ssh':
self.logger.debug('Invalid schema %s. Not expiring key.', schema)
return False
try:
json_obj = json.loads(json_str)
except ValueError:
self.logger.debug('Invalid JSON %s. Not expiring key.', json_str)
return False
if 'expireOn' not in json_obj:
self.logger.debug('No expiration timestamp. Not expiring key.')
return False
expire_str = json_obj['expireOn']
format_str = '%Y-%m-%dT%H:%M:%S+0000'
try:
expire_time = datetime.datetime.strptime(expire_str, format_str)
except ValueError:
self.logger.warning(
'Expiration timestamp "%s" not in format %s. Not expiring key.',
expire_str, format_str)
return False
# Expire the key if and only if we have exceeded the expiration timestamp.
return datetime.datetime.utcnow() > expire_time | [
"def",
"_HasExpired",
"(",
"self",
",",
"key",
")",
":",
"self",
".",
"logger",
".",
"debug",
"(",
"'Processing key: %s.'",
",",
"key",
")",
"try",
":",
"schema",
",",
"json_str",
"=",
"key",
".",
"split",
"(",
"None",
",",
"3",
")",
"[",
"2",
":",
"]",
"except",
"(",
"ValueError",
",",
"AttributeError",
")",
":",
"self",
".",
"logger",
".",
"debug",
"(",
"'No schema identifier. Not expiring key.'",
")",
"return",
"False",
"if",
"schema",
"!=",
"'google-ssh'",
":",
"self",
".",
"logger",
".",
"debug",
"(",
"'Invalid schema %s. Not expiring key.'",
",",
"schema",
")",
"return",
"False",
"try",
":",
"json_obj",
"=",
"json",
".",
"loads",
"(",
"json_str",
")",
"except",
"ValueError",
":",
"self",
".",
"logger",
".",
"debug",
"(",
"'Invalid JSON %s. Not expiring key.'",
",",
"json_str",
")",
"return",
"False",
"if",
"'expireOn'",
"not",
"in",
"json_obj",
":",
"self",
".",
"logger",
".",
"debug",
"(",
"'No expiration timestamp. Not expiring key.'",
")",
"return",
"False",
"expire_str",
"=",
"json_obj",
"[",
"'expireOn'",
"]",
"format_str",
"=",
"'%Y-%m-%dT%H:%M:%S+0000'",
"try",
":",
"expire_time",
"=",
"datetime",
".",
"datetime",
".",
"strptime",
"(",
"expire_str",
",",
"format_str",
")",
"except",
"ValueError",
":",
"self",
".",
"logger",
".",
"warning",
"(",
"'Expiration timestamp \"%s\" not in format %s. Not expiring key.'",
",",
"expire_str",
",",
"format_str",
")",
"return",
"False",
"# Expire the key if and only if we have exceeded the expiration timestamp.",
"return",
"datetime",
".",
"datetime",
".",
"utcnow",
"(",
")",
">",
"expire_time"
] | Check whether an SSH key has expired.
Uses Google-specific semantics of the OpenSSH public key format's comment
field to determine if an SSH key is past its expiration timestamp, and
therefore no longer to be trusted. This format is still subject to change.
Reliance on it in any way is at your own risk.
Args:
key: string, a single public key entry in OpenSSH public key file format.
This will be checked for Google-specific comment semantics, and if
present, those will be analysed.
Returns:
bool, True if the key has Google-specific comment semantics and has an
expiration timestamp in the past, or False otherwise. | [
"Check",
"whether",
"an",
"SSH",
"key",
"has",
"expired",
"."
] | 53ea8cd069fb4d9a1984d1c167e54c133033f8da | https://github.com/GoogleCloudPlatform/compute-image-packages/blob/53ea8cd069fb4d9a1984d1c167e54c133033f8da/packages/python-google-compute-engine/google_compute_engine/accounts/accounts_daemon.py#L78-L128 |
248,322 | GoogleCloudPlatform/compute-image-packages | packages/python-google-compute-engine/google_compute_engine/accounts/accounts_daemon.py | AccountsDaemon._ParseAccountsData | def _ParseAccountsData(self, account_data):
"""Parse the SSH key data into a user map.
Args:
account_data: string, the metadata server SSH key attributes data.
Returns:
dict, a mapping of the form: {'username': ['sshkey1, 'sshkey2', ...]}.
"""
if not account_data:
return {}
lines = [line for line in account_data.splitlines() if line]
user_map = {}
for line in lines:
if not all(ord(c) < 128 for c in line):
self.logger.info('SSH key contains non-ascii character: %s.', line)
continue
split_line = line.split(':', 1)
if len(split_line) != 2:
self.logger.info('SSH key is not a complete entry: %s.', split_line)
continue
user, key = split_line
if self._HasExpired(key):
self.logger.debug('Expired SSH key for user %s: %s.', user, key)
continue
if user not in user_map:
user_map[user] = []
user_map[user].append(key)
logging.debug('User accounts: %s.', user_map)
return user_map | python | def _ParseAccountsData(self, account_data):
if not account_data:
return {}
lines = [line for line in account_data.splitlines() if line]
user_map = {}
for line in lines:
if not all(ord(c) < 128 for c in line):
self.logger.info('SSH key contains non-ascii character: %s.', line)
continue
split_line = line.split(':', 1)
if len(split_line) != 2:
self.logger.info('SSH key is not a complete entry: %s.', split_line)
continue
user, key = split_line
if self._HasExpired(key):
self.logger.debug('Expired SSH key for user %s: %s.', user, key)
continue
if user not in user_map:
user_map[user] = []
user_map[user].append(key)
logging.debug('User accounts: %s.', user_map)
return user_map | [
"def",
"_ParseAccountsData",
"(",
"self",
",",
"account_data",
")",
":",
"if",
"not",
"account_data",
":",
"return",
"{",
"}",
"lines",
"=",
"[",
"line",
"for",
"line",
"in",
"account_data",
".",
"splitlines",
"(",
")",
"if",
"line",
"]",
"user_map",
"=",
"{",
"}",
"for",
"line",
"in",
"lines",
":",
"if",
"not",
"all",
"(",
"ord",
"(",
"c",
")",
"<",
"128",
"for",
"c",
"in",
"line",
")",
":",
"self",
".",
"logger",
".",
"info",
"(",
"'SSH key contains non-ascii character: %s.'",
",",
"line",
")",
"continue",
"split_line",
"=",
"line",
".",
"split",
"(",
"':'",
",",
"1",
")",
"if",
"len",
"(",
"split_line",
")",
"!=",
"2",
":",
"self",
".",
"logger",
".",
"info",
"(",
"'SSH key is not a complete entry: %s.'",
",",
"split_line",
")",
"continue",
"user",
",",
"key",
"=",
"split_line",
"if",
"self",
".",
"_HasExpired",
"(",
"key",
")",
":",
"self",
".",
"logger",
".",
"debug",
"(",
"'Expired SSH key for user %s: %s.'",
",",
"user",
",",
"key",
")",
"continue",
"if",
"user",
"not",
"in",
"user_map",
":",
"user_map",
"[",
"user",
"]",
"=",
"[",
"]",
"user_map",
"[",
"user",
"]",
".",
"append",
"(",
"key",
")",
"logging",
".",
"debug",
"(",
"'User accounts: %s.'",
",",
"user_map",
")",
"return",
"user_map"
] | Parse the SSH key data into a user map.
Args:
account_data: string, the metadata server SSH key attributes data.
Returns:
dict, a mapping of the form: {'username': ['sshkey1, 'sshkey2', ...]}. | [
"Parse",
"the",
"SSH",
"key",
"data",
"into",
"a",
"user",
"map",
"."
] | 53ea8cd069fb4d9a1984d1c167e54c133033f8da | https://github.com/GoogleCloudPlatform/compute-image-packages/blob/53ea8cd069fb4d9a1984d1c167e54c133033f8da/packages/python-google-compute-engine/google_compute_engine/accounts/accounts_daemon.py#L130-L159 |
248,323 | GoogleCloudPlatform/compute-image-packages | packages/python-google-compute-engine/google_compute_engine/accounts/accounts_daemon.py | AccountsDaemon._GetInstanceAndProjectAttributes | def _GetInstanceAndProjectAttributes(self, metadata_dict):
"""Get dictionaries for instance and project attributes.
Args:
metadata_dict: json, the deserialized contents of the metadata server.
Returns:
tuple, two dictionaries for instance and project attributes.
"""
metadata_dict = metadata_dict or {}
try:
instance_data = metadata_dict['instance']['attributes']
except KeyError:
instance_data = {}
self.logger.warning('Instance attributes were not found.')
try:
project_data = metadata_dict['project']['attributes']
except KeyError:
project_data = {}
self.logger.warning('Project attributes were not found.')
return instance_data, project_data | python | def _GetInstanceAndProjectAttributes(self, metadata_dict):
metadata_dict = metadata_dict or {}
try:
instance_data = metadata_dict['instance']['attributes']
except KeyError:
instance_data = {}
self.logger.warning('Instance attributes were not found.')
try:
project_data = metadata_dict['project']['attributes']
except KeyError:
project_data = {}
self.logger.warning('Project attributes were not found.')
return instance_data, project_data | [
"def",
"_GetInstanceAndProjectAttributes",
"(",
"self",
",",
"metadata_dict",
")",
":",
"metadata_dict",
"=",
"metadata_dict",
"or",
"{",
"}",
"try",
":",
"instance_data",
"=",
"metadata_dict",
"[",
"'instance'",
"]",
"[",
"'attributes'",
"]",
"except",
"KeyError",
":",
"instance_data",
"=",
"{",
"}",
"self",
".",
"logger",
".",
"warning",
"(",
"'Instance attributes were not found.'",
")",
"try",
":",
"project_data",
"=",
"metadata_dict",
"[",
"'project'",
"]",
"[",
"'attributes'",
"]",
"except",
"KeyError",
":",
"project_data",
"=",
"{",
"}",
"self",
".",
"logger",
".",
"warning",
"(",
"'Project attributes were not found.'",
")",
"return",
"instance_data",
",",
"project_data"
] | Get dictionaries for instance and project attributes.
Args:
metadata_dict: json, the deserialized contents of the metadata server.
Returns:
tuple, two dictionaries for instance and project attributes. | [
"Get",
"dictionaries",
"for",
"instance",
"and",
"project",
"attributes",
"."
] | 53ea8cd069fb4d9a1984d1c167e54c133033f8da | https://github.com/GoogleCloudPlatform/compute-image-packages/blob/53ea8cd069fb4d9a1984d1c167e54c133033f8da/packages/python-google-compute-engine/google_compute_engine/accounts/accounts_daemon.py#L161-L184 |
248,324 | GoogleCloudPlatform/compute-image-packages | packages/python-google-compute-engine/google_compute_engine/accounts/accounts_daemon.py | AccountsDaemon._GetAccountsData | def _GetAccountsData(self, metadata_dict):
"""Get the user accounts specified in metadata server contents.
Args:
metadata_dict: json, the deserialized contents of the metadata server.
Returns:
dict, a mapping of the form: {'username': ['sshkey1, 'sshkey2', ...]}.
"""
instance_data, project_data = self._GetInstanceAndProjectAttributes(
metadata_dict)
valid_keys = [instance_data.get('sshKeys'), instance_data.get('ssh-keys')]
block_project = instance_data.get('block-project-ssh-keys', '').lower()
if block_project != 'true' and not instance_data.get('sshKeys'):
valid_keys.append(project_data.get('ssh-keys'))
valid_keys.append(project_data.get('sshKeys'))
accounts_data = '\n'.join([key for key in valid_keys if key])
return self._ParseAccountsData(accounts_data) | python | def _GetAccountsData(self, metadata_dict):
instance_data, project_data = self._GetInstanceAndProjectAttributes(
metadata_dict)
valid_keys = [instance_data.get('sshKeys'), instance_data.get('ssh-keys')]
block_project = instance_data.get('block-project-ssh-keys', '').lower()
if block_project != 'true' and not instance_data.get('sshKeys'):
valid_keys.append(project_data.get('ssh-keys'))
valid_keys.append(project_data.get('sshKeys'))
accounts_data = '\n'.join([key for key in valid_keys if key])
return self._ParseAccountsData(accounts_data) | [
"def",
"_GetAccountsData",
"(",
"self",
",",
"metadata_dict",
")",
":",
"instance_data",
",",
"project_data",
"=",
"self",
".",
"_GetInstanceAndProjectAttributes",
"(",
"metadata_dict",
")",
"valid_keys",
"=",
"[",
"instance_data",
".",
"get",
"(",
"'sshKeys'",
")",
",",
"instance_data",
".",
"get",
"(",
"'ssh-keys'",
")",
"]",
"block_project",
"=",
"instance_data",
".",
"get",
"(",
"'block-project-ssh-keys'",
",",
"''",
")",
".",
"lower",
"(",
")",
"if",
"block_project",
"!=",
"'true'",
"and",
"not",
"instance_data",
".",
"get",
"(",
"'sshKeys'",
")",
":",
"valid_keys",
".",
"append",
"(",
"project_data",
".",
"get",
"(",
"'ssh-keys'",
")",
")",
"valid_keys",
".",
"append",
"(",
"project_data",
".",
"get",
"(",
"'sshKeys'",
")",
")",
"accounts_data",
"=",
"'\\n'",
".",
"join",
"(",
"[",
"key",
"for",
"key",
"in",
"valid_keys",
"if",
"key",
"]",
")",
"return",
"self",
".",
"_ParseAccountsData",
"(",
"accounts_data",
")"
] | Get the user accounts specified in metadata server contents.
Args:
metadata_dict: json, the deserialized contents of the metadata server.
Returns:
dict, a mapping of the form: {'username': ['sshkey1, 'sshkey2', ...]}. | [
"Get",
"the",
"user",
"accounts",
"specified",
"in",
"metadata",
"server",
"contents",
"."
] | 53ea8cd069fb4d9a1984d1c167e54c133033f8da | https://github.com/GoogleCloudPlatform/compute-image-packages/blob/53ea8cd069fb4d9a1984d1c167e54c133033f8da/packages/python-google-compute-engine/google_compute_engine/accounts/accounts_daemon.py#L186-L203 |
248,325 | GoogleCloudPlatform/compute-image-packages | packages/python-google-compute-engine/google_compute_engine/accounts/accounts_daemon.py | AccountsDaemon._UpdateUsers | def _UpdateUsers(self, update_users):
"""Provision and update Linux user accounts based on account metadata.
Args:
update_users: dict, authorized users mapped to their public SSH keys.
"""
for user, ssh_keys in update_users.items():
if not user or user in self.invalid_users:
continue
configured_keys = self.user_ssh_keys.get(user, [])
if set(ssh_keys) != set(configured_keys):
if not self.utils.UpdateUser(user, ssh_keys):
self.invalid_users.add(user)
else:
self.user_ssh_keys[user] = ssh_keys[:] | python | def _UpdateUsers(self, update_users):
for user, ssh_keys in update_users.items():
if not user or user in self.invalid_users:
continue
configured_keys = self.user_ssh_keys.get(user, [])
if set(ssh_keys) != set(configured_keys):
if not self.utils.UpdateUser(user, ssh_keys):
self.invalid_users.add(user)
else:
self.user_ssh_keys[user] = ssh_keys[:] | [
"def",
"_UpdateUsers",
"(",
"self",
",",
"update_users",
")",
":",
"for",
"user",
",",
"ssh_keys",
"in",
"update_users",
".",
"items",
"(",
")",
":",
"if",
"not",
"user",
"or",
"user",
"in",
"self",
".",
"invalid_users",
":",
"continue",
"configured_keys",
"=",
"self",
".",
"user_ssh_keys",
".",
"get",
"(",
"user",
",",
"[",
"]",
")",
"if",
"set",
"(",
"ssh_keys",
")",
"!=",
"set",
"(",
"configured_keys",
")",
":",
"if",
"not",
"self",
".",
"utils",
".",
"UpdateUser",
"(",
"user",
",",
"ssh_keys",
")",
":",
"self",
".",
"invalid_users",
".",
"add",
"(",
"user",
")",
"else",
":",
"self",
".",
"user_ssh_keys",
"[",
"user",
"]",
"=",
"ssh_keys",
"[",
":",
"]"
] | Provision and update Linux user accounts based on account metadata.
Args:
update_users: dict, authorized users mapped to their public SSH keys. | [
"Provision",
"and",
"update",
"Linux",
"user",
"accounts",
"based",
"on",
"account",
"metadata",
"."
] | 53ea8cd069fb4d9a1984d1c167e54c133033f8da | https://github.com/GoogleCloudPlatform/compute-image-packages/blob/53ea8cd069fb4d9a1984d1c167e54c133033f8da/packages/python-google-compute-engine/google_compute_engine/accounts/accounts_daemon.py#L205-L219 |
248,326 | GoogleCloudPlatform/compute-image-packages | packages/python-google-compute-engine/google_compute_engine/accounts/accounts_daemon.py | AccountsDaemon._RemoveUsers | def _RemoveUsers(self, remove_users):
"""Deprovision Linux user accounts that do not appear in account metadata.
Args:
remove_users: list, the username strings of the Linux accounts to remove.
"""
for username in remove_users:
self.utils.RemoveUser(username)
self.user_ssh_keys.pop(username, None)
self.invalid_users -= set(remove_users) | python | def _RemoveUsers(self, remove_users):
for username in remove_users:
self.utils.RemoveUser(username)
self.user_ssh_keys.pop(username, None)
self.invalid_users -= set(remove_users) | [
"def",
"_RemoveUsers",
"(",
"self",
",",
"remove_users",
")",
":",
"for",
"username",
"in",
"remove_users",
":",
"self",
".",
"utils",
".",
"RemoveUser",
"(",
"username",
")",
"self",
".",
"user_ssh_keys",
".",
"pop",
"(",
"username",
",",
"None",
")",
"self",
".",
"invalid_users",
"-=",
"set",
"(",
"remove_users",
")"
] | Deprovision Linux user accounts that do not appear in account metadata.
Args:
remove_users: list, the username strings of the Linux accounts to remove. | [
"Deprovision",
"Linux",
"user",
"accounts",
"that",
"do",
"not",
"appear",
"in",
"account",
"metadata",
"."
] | 53ea8cd069fb4d9a1984d1c167e54c133033f8da | https://github.com/GoogleCloudPlatform/compute-image-packages/blob/53ea8cd069fb4d9a1984d1c167e54c133033f8da/packages/python-google-compute-engine/google_compute_engine/accounts/accounts_daemon.py#L221-L230 |
248,327 | GoogleCloudPlatform/compute-image-packages | packages/python-google-compute-engine/google_compute_engine/accounts/accounts_daemon.py | AccountsDaemon._GetEnableOsLoginValue | def _GetEnableOsLoginValue(self, metadata_dict):
"""Get the value of the enable-oslogin metadata key.
Args:
metadata_dict: json, the deserialized contents of the metadata server.
Returns:
bool, True if OS Login is enabled for VM access.
"""
instance_data, project_data = self._GetInstanceAndProjectAttributes(
metadata_dict)
instance_value = instance_data.get('enable-oslogin')
project_value = project_data.get('enable-oslogin')
value = instance_value or project_value or ''
return value.lower() == 'true' | python | def _GetEnableOsLoginValue(self, metadata_dict):
instance_data, project_data = self._GetInstanceAndProjectAttributes(
metadata_dict)
instance_value = instance_data.get('enable-oslogin')
project_value = project_data.get('enable-oslogin')
value = instance_value or project_value or ''
return value.lower() == 'true' | [
"def",
"_GetEnableOsLoginValue",
"(",
"self",
",",
"metadata_dict",
")",
":",
"instance_data",
",",
"project_data",
"=",
"self",
".",
"_GetInstanceAndProjectAttributes",
"(",
"metadata_dict",
")",
"instance_value",
"=",
"instance_data",
".",
"get",
"(",
"'enable-oslogin'",
")",
"project_value",
"=",
"project_data",
".",
"get",
"(",
"'enable-oslogin'",
")",
"value",
"=",
"instance_value",
"or",
"project_value",
"or",
"''",
"return",
"value",
".",
"lower",
"(",
")",
"==",
"'true'"
] | Get the value of the enable-oslogin metadata key.
Args:
metadata_dict: json, the deserialized contents of the metadata server.
Returns:
bool, True if OS Login is enabled for VM access. | [
"Get",
"the",
"value",
"of",
"the",
"enable",
"-",
"oslogin",
"metadata",
"key",
"."
] | 53ea8cd069fb4d9a1984d1c167e54c133033f8da | https://github.com/GoogleCloudPlatform/compute-image-packages/blob/53ea8cd069fb4d9a1984d1c167e54c133033f8da/packages/python-google-compute-engine/google_compute_engine/accounts/accounts_daemon.py#L232-L247 |
248,328 | GoogleCloudPlatform/compute-image-packages | packages/python-google-compute-engine/google_compute_engine/accounts/accounts_daemon.py | AccountsDaemon.HandleAccounts | def HandleAccounts(self, result):
"""Called when there are changes to the contents of the metadata server.
Args:
result: json, the deserialized contents of the metadata server.
"""
self.logger.debug('Checking for changes to user accounts.')
configured_users = self.utils.GetConfiguredUsers()
enable_oslogin = self._GetEnableOsLoginValue(result)
enable_two_factor = self._GetEnableTwoFactorValue(result)
if enable_oslogin:
desired_users = {}
self.oslogin.UpdateOsLogin(True, two_factor_desired=enable_two_factor)
else:
desired_users = self._GetAccountsData(result)
self.oslogin.UpdateOsLogin(False)
remove_users = sorted(set(configured_users) - set(desired_users.keys()))
self._UpdateUsers(desired_users)
self._RemoveUsers(remove_users)
self.utils.SetConfiguredUsers(desired_users.keys()) | python | def HandleAccounts(self, result):
self.logger.debug('Checking for changes to user accounts.')
configured_users = self.utils.GetConfiguredUsers()
enable_oslogin = self._GetEnableOsLoginValue(result)
enable_two_factor = self._GetEnableTwoFactorValue(result)
if enable_oslogin:
desired_users = {}
self.oslogin.UpdateOsLogin(True, two_factor_desired=enable_two_factor)
else:
desired_users = self._GetAccountsData(result)
self.oslogin.UpdateOsLogin(False)
remove_users = sorted(set(configured_users) - set(desired_users.keys()))
self._UpdateUsers(desired_users)
self._RemoveUsers(remove_users)
self.utils.SetConfiguredUsers(desired_users.keys()) | [
"def",
"HandleAccounts",
"(",
"self",
",",
"result",
")",
":",
"self",
".",
"logger",
".",
"debug",
"(",
"'Checking for changes to user accounts.'",
")",
"configured_users",
"=",
"self",
".",
"utils",
".",
"GetConfiguredUsers",
"(",
")",
"enable_oslogin",
"=",
"self",
".",
"_GetEnableOsLoginValue",
"(",
"result",
")",
"enable_two_factor",
"=",
"self",
".",
"_GetEnableTwoFactorValue",
"(",
"result",
")",
"if",
"enable_oslogin",
":",
"desired_users",
"=",
"{",
"}",
"self",
".",
"oslogin",
".",
"UpdateOsLogin",
"(",
"True",
",",
"two_factor_desired",
"=",
"enable_two_factor",
")",
"else",
":",
"desired_users",
"=",
"self",
".",
"_GetAccountsData",
"(",
"result",
")",
"self",
".",
"oslogin",
".",
"UpdateOsLogin",
"(",
"False",
")",
"remove_users",
"=",
"sorted",
"(",
"set",
"(",
"configured_users",
")",
"-",
"set",
"(",
"desired_users",
".",
"keys",
"(",
")",
")",
")",
"self",
".",
"_UpdateUsers",
"(",
"desired_users",
")",
"self",
".",
"_RemoveUsers",
"(",
"remove_users",
")",
"self",
".",
"utils",
".",
"SetConfiguredUsers",
"(",
"desired_users",
".",
"keys",
"(",
")",
")"
] | Called when there are changes to the contents of the metadata server.
Args:
result: json, the deserialized contents of the metadata server. | [
"Called",
"when",
"there",
"are",
"changes",
"to",
"the",
"contents",
"of",
"the",
"metadata",
"server",
"."
] | 53ea8cd069fb4d9a1984d1c167e54c133033f8da | https://github.com/GoogleCloudPlatform/compute-image-packages/blob/53ea8cd069fb4d9a1984d1c167e54c133033f8da/packages/python-google-compute-engine/google_compute_engine/accounts/accounts_daemon.py#L266-L285 |
248,329 | GoogleCloudPlatform/compute-image-packages | packages/python-google-compute-engine/google_compute_engine/file_utils.py | _SetSELinuxContext | def _SetSELinuxContext(path):
"""Set the appropriate SELinux context, if SELinux tools are installed.
Calls /sbin/restorecon on the provided path to set the SELinux context as
specified by policy. This call does not operate recursively.
Only some OS configurations use SELinux. It is therefore acceptable for
restorecon to be missing, in which case we do nothing.
Args:
path: string, the path on which to fix the SELinux context.
"""
restorecon = '/sbin/restorecon'
if os.path.isfile(restorecon) and os.access(restorecon, os.X_OK):
subprocess.call([restorecon, path]) | python | def _SetSELinuxContext(path):
restorecon = '/sbin/restorecon'
if os.path.isfile(restorecon) and os.access(restorecon, os.X_OK):
subprocess.call([restorecon, path]) | [
"def",
"_SetSELinuxContext",
"(",
"path",
")",
":",
"restorecon",
"=",
"'/sbin/restorecon'",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"restorecon",
")",
"and",
"os",
".",
"access",
"(",
"restorecon",
",",
"os",
".",
"X_OK",
")",
":",
"subprocess",
".",
"call",
"(",
"[",
"restorecon",
",",
"path",
"]",
")"
] | Set the appropriate SELinux context, if SELinux tools are installed.
Calls /sbin/restorecon on the provided path to set the SELinux context as
specified by policy. This call does not operate recursively.
Only some OS configurations use SELinux. It is therefore acceptable for
restorecon to be missing, in which case we do nothing.
Args:
path: string, the path on which to fix the SELinux context. | [
"Set",
"the",
"appropriate",
"SELinux",
"context",
"if",
"SELinux",
"tools",
"are",
"installed",
"."
] | 53ea8cd069fb4d9a1984d1c167e54c133033f8da | https://github.com/GoogleCloudPlatform/compute-image-packages/blob/53ea8cd069fb4d9a1984d1c167e54c133033f8da/packages/python-google-compute-engine/google_compute_engine/file_utils.py#L25-L39 |
248,330 | GoogleCloudPlatform/compute-image-packages | packages/python-google-compute-engine/google_compute_engine/file_utils.py | SetPermissions | def SetPermissions(path, mode=None, uid=None, gid=None, mkdir=False):
"""Set the permissions and ownership of a path.
Args:
path: string, the path for which owner ID and group ID needs to be setup.
mode: octal string, the permissions to set on the path.
uid: int, the owner ID to be set for the path.
gid: int, the group ID to be set for the path.
mkdir: bool, True if the directory needs to be created.
"""
if mkdir and not os.path.exists(path):
os.mkdir(path, mode or 0o777)
elif mode:
os.chmod(path, mode)
if uid and gid:
os.chown(path, uid, gid)
_SetSELinuxContext(path) | python | def SetPermissions(path, mode=None, uid=None, gid=None, mkdir=False):
if mkdir and not os.path.exists(path):
os.mkdir(path, mode or 0o777)
elif mode:
os.chmod(path, mode)
if uid and gid:
os.chown(path, uid, gid)
_SetSELinuxContext(path) | [
"def",
"SetPermissions",
"(",
"path",
",",
"mode",
"=",
"None",
",",
"uid",
"=",
"None",
",",
"gid",
"=",
"None",
",",
"mkdir",
"=",
"False",
")",
":",
"if",
"mkdir",
"and",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"path",
")",
":",
"os",
".",
"mkdir",
"(",
"path",
",",
"mode",
"or",
"0o777",
")",
"elif",
"mode",
":",
"os",
".",
"chmod",
"(",
"path",
",",
"mode",
")",
"if",
"uid",
"and",
"gid",
":",
"os",
".",
"chown",
"(",
"path",
",",
"uid",
",",
"gid",
")",
"_SetSELinuxContext",
"(",
"path",
")"
] | Set the permissions and ownership of a path.
Args:
path: string, the path for which owner ID and group ID needs to be setup.
mode: octal string, the permissions to set on the path.
uid: int, the owner ID to be set for the path.
gid: int, the group ID to be set for the path.
mkdir: bool, True if the directory needs to be created. | [
"Set",
"the",
"permissions",
"and",
"ownership",
"of",
"a",
"path",
"."
] | 53ea8cd069fb4d9a1984d1c167e54c133033f8da | https://github.com/GoogleCloudPlatform/compute-image-packages/blob/53ea8cd069fb4d9a1984d1c167e54c133033f8da/packages/python-google-compute-engine/google_compute_engine/file_utils.py#L42-L58 |
248,331 | GoogleCloudPlatform/compute-image-packages | packages/python-google-compute-engine/google_compute_engine/file_utils.py | Lock | def Lock(fd, path, blocking):
"""Lock the provided file descriptor.
Args:
fd: int, the file descriptor of the file to lock.
path: string, the name of the file to lock.
blocking: bool, whether the function should return immediately.
Raises:
IOError, raised from flock while attempting to lock a file.
"""
operation = fcntl.LOCK_EX if blocking else fcntl.LOCK_EX | fcntl.LOCK_NB
try:
fcntl.flock(fd, operation)
except IOError as e:
if e.errno == errno.EWOULDBLOCK:
raise IOError('Exception locking %s. File already locked.' % path)
else:
raise IOError('Exception locking %s. %s.' % (path, str(e))) | python | def Lock(fd, path, blocking):
operation = fcntl.LOCK_EX if blocking else fcntl.LOCK_EX | fcntl.LOCK_NB
try:
fcntl.flock(fd, operation)
except IOError as e:
if e.errno == errno.EWOULDBLOCK:
raise IOError('Exception locking %s. File already locked.' % path)
else:
raise IOError('Exception locking %s. %s.' % (path, str(e))) | [
"def",
"Lock",
"(",
"fd",
",",
"path",
",",
"blocking",
")",
":",
"operation",
"=",
"fcntl",
".",
"LOCK_EX",
"if",
"blocking",
"else",
"fcntl",
".",
"LOCK_EX",
"|",
"fcntl",
".",
"LOCK_NB",
"try",
":",
"fcntl",
".",
"flock",
"(",
"fd",
",",
"operation",
")",
"except",
"IOError",
"as",
"e",
":",
"if",
"e",
".",
"errno",
"==",
"errno",
".",
"EWOULDBLOCK",
":",
"raise",
"IOError",
"(",
"'Exception locking %s. File already locked.'",
"%",
"path",
")",
"else",
":",
"raise",
"IOError",
"(",
"'Exception locking %s. %s.'",
"%",
"(",
"path",
",",
"str",
"(",
"e",
")",
")",
")"
] | Lock the provided file descriptor.
Args:
fd: int, the file descriptor of the file to lock.
path: string, the name of the file to lock.
blocking: bool, whether the function should return immediately.
Raises:
IOError, raised from flock while attempting to lock a file. | [
"Lock",
"the",
"provided",
"file",
"descriptor",
"."
] | 53ea8cd069fb4d9a1984d1c167e54c133033f8da | https://github.com/GoogleCloudPlatform/compute-image-packages/blob/53ea8cd069fb4d9a1984d1c167e54c133033f8da/packages/python-google-compute-engine/google_compute_engine/file_utils.py#L61-L79 |
248,332 | GoogleCloudPlatform/compute-image-packages | packages/python-google-compute-engine/google_compute_engine/file_utils.py | Unlock | def Unlock(fd, path):
"""Release the lock on the file.
Args:
fd: int, the file descriptor of the file to unlock.
path: string, the name of the file to lock.
Raises:
IOError, raised from flock while attempting to release a file lock.
"""
try:
fcntl.flock(fd, fcntl.LOCK_UN | fcntl.LOCK_NB)
except IOError as e:
if e.errno == errno.EWOULDBLOCK:
raise IOError('Exception unlocking %s. Locked by another process.' % path)
else:
raise IOError('Exception unlocking %s. %s.' % (path, str(e))) | python | def Unlock(fd, path):
try:
fcntl.flock(fd, fcntl.LOCK_UN | fcntl.LOCK_NB)
except IOError as e:
if e.errno == errno.EWOULDBLOCK:
raise IOError('Exception unlocking %s. Locked by another process.' % path)
else:
raise IOError('Exception unlocking %s. %s.' % (path, str(e))) | [
"def",
"Unlock",
"(",
"fd",
",",
"path",
")",
":",
"try",
":",
"fcntl",
".",
"flock",
"(",
"fd",
",",
"fcntl",
".",
"LOCK_UN",
"|",
"fcntl",
".",
"LOCK_NB",
")",
"except",
"IOError",
"as",
"e",
":",
"if",
"e",
".",
"errno",
"==",
"errno",
".",
"EWOULDBLOCK",
":",
"raise",
"IOError",
"(",
"'Exception unlocking %s. Locked by another process.'",
"%",
"path",
")",
"else",
":",
"raise",
"IOError",
"(",
"'Exception unlocking %s. %s.'",
"%",
"(",
"path",
",",
"str",
"(",
"e",
")",
")",
")"
] | Release the lock on the file.
Args:
fd: int, the file descriptor of the file to unlock.
path: string, the name of the file to lock.
Raises:
IOError, raised from flock while attempting to release a file lock. | [
"Release",
"the",
"lock",
"on",
"the",
"file",
"."
] | 53ea8cd069fb4d9a1984d1c167e54c133033f8da | https://github.com/GoogleCloudPlatform/compute-image-packages/blob/53ea8cd069fb4d9a1984d1c167e54c133033f8da/packages/python-google-compute-engine/google_compute_engine/file_utils.py#L82-L98 |
248,333 | GoogleCloudPlatform/compute-image-packages | packages/python-google-compute-engine/google_compute_engine/file_utils.py | LockFile | def LockFile(path, blocking=False):
"""Interface to flock-based file locking to prevent concurrent executions.
Args:
path: string, the name of the file to lock.
blocking: bool, whether the function should return immediately.
Yields:
None, yields when a lock on the file is obtained.
Raises:
IOError, raised from flock locking operations on a file.
OSError, raised from file operations.
"""
fd = os.open(path, os.O_CREAT)
try:
Lock(fd, path, blocking)
yield
finally:
try:
Unlock(fd, path)
finally:
os.close(fd) | python | def LockFile(path, blocking=False):
fd = os.open(path, os.O_CREAT)
try:
Lock(fd, path, blocking)
yield
finally:
try:
Unlock(fd, path)
finally:
os.close(fd) | [
"def",
"LockFile",
"(",
"path",
",",
"blocking",
"=",
"False",
")",
":",
"fd",
"=",
"os",
".",
"open",
"(",
"path",
",",
"os",
".",
"O_CREAT",
")",
"try",
":",
"Lock",
"(",
"fd",
",",
"path",
",",
"blocking",
")",
"yield",
"finally",
":",
"try",
":",
"Unlock",
"(",
"fd",
",",
"path",
")",
"finally",
":",
"os",
".",
"close",
"(",
"fd",
")"
] | Interface to flock-based file locking to prevent concurrent executions.
Args:
path: string, the name of the file to lock.
blocking: bool, whether the function should return immediately.
Yields:
None, yields when a lock on the file is obtained.
Raises:
IOError, raised from flock locking operations on a file.
OSError, raised from file operations. | [
"Interface",
"to",
"flock",
"-",
"based",
"file",
"locking",
"to",
"prevent",
"concurrent",
"executions",
"."
] | 53ea8cd069fb4d9a1984d1c167e54c133033f8da | https://github.com/GoogleCloudPlatform/compute-image-packages/blob/53ea8cd069fb4d9a1984d1c167e54c133033f8da/packages/python-google-compute-engine/google_compute_engine/file_utils.py#L102-L124 |
248,334 | GoogleCloudPlatform/compute-image-packages | packages/python-google-compute-engine/google_compute_engine/metadata_watcher.py | RetryOnUnavailable | def RetryOnUnavailable(func):
"""Function decorator to retry on a service unavailable exception."""
@functools.wraps(func)
def Wrapper(*args, **kwargs):
while True:
try:
response = func(*args, **kwargs)
except (httpclient.HTTPException, socket.error, urlerror.URLError) as e:
time.sleep(5)
if (isinstance(e, urlerror.HTTPError)
and e.getcode() == httpclient.SERVICE_UNAVAILABLE):
continue
elif isinstance(e, socket.timeout):
continue
raise
else:
if response.getcode() == httpclient.OK:
return response
else:
raise StatusException(response)
return Wrapper | python | def RetryOnUnavailable(func):
@functools.wraps(func)
def Wrapper(*args, **kwargs):
while True:
try:
response = func(*args, **kwargs)
except (httpclient.HTTPException, socket.error, urlerror.URLError) as e:
time.sleep(5)
if (isinstance(e, urlerror.HTTPError)
and e.getcode() == httpclient.SERVICE_UNAVAILABLE):
continue
elif isinstance(e, socket.timeout):
continue
raise
else:
if response.getcode() == httpclient.OK:
return response
else:
raise StatusException(response)
return Wrapper | [
"def",
"RetryOnUnavailable",
"(",
"func",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"func",
")",
"def",
"Wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"while",
"True",
":",
"try",
":",
"response",
"=",
"func",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"except",
"(",
"httpclient",
".",
"HTTPException",
",",
"socket",
".",
"error",
",",
"urlerror",
".",
"URLError",
")",
"as",
"e",
":",
"time",
".",
"sleep",
"(",
"5",
")",
"if",
"(",
"isinstance",
"(",
"e",
",",
"urlerror",
".",
"HTTPError",
")",
"and",
"e",
".",
"getcode",
"(",
")",
"==",
"httpclient",
".",
"SERVICE_UNAVAILABLE",
")",
":",
"continue",
"elif",
"isinstance",
"(",
"e",
",",
"socket",
".",
"timeout",
")",
":",
"continue",
"raise",
"else",
":",
"if",
"response",
".",
"getcode",
"(",
")",
"==",
"httpclient",
".",
"OK",
":",
"return",
"response",
"else",
":",
"raise",
"StatusException",
"(",
"response",
")",
"return",
"Wrapper"
] | Function decorator to retry on a service unavailable exception. | [
"Function",
"decorator",
"to",
"retry",
"on",
"a",
"service",
"unavailable",
"exception",
"."
] | 53ea8cd069fb4d9a1984d1c167e54c133033f8da | https://github.com/GoogleCloudPlatform/compute-image-packages/blob/53ea8cd069fb4d9a1984d1c167e54c133033f8da/packages/python-google-compute-engine/google_compute_engine/metadata_watcher.py#L43-L64 |
248,335 | GoogleCloudPlatform/compute-image-packages | packages/python-google-compute-engine/google_compute_engine/metadata_watcher.py | MetadataWatcher._GetMetadataRequest | def _GetMetadataRequest(self, metadata_url, params=None, timeout=None):
"""Performs a GET request with the metadata headers.
Args:
metadata_url: string, the URL to perform a GET request on.
params: dictionary, the query parameters in the GET request.
timeout: int, timeout in seconds for metadata requests.
Returns:
HTTP response from the GET request.
Raises:
urlerror.HTTPError: raises when the GET request fails.
"""
headers = {'Metadata-Flavor': 'Google'}
params = urlparse.urlencode(params or {})
url = '%s?%s' % (metadata_url, params)
request = urlrequest.Request(url, headers=headers)
request_opener = urlrequest.build_opener(urlrequest.ProxyHandler({}))
timeout = timeout or self.timeout
return request_opener.open(request, timeout=timeout*1.1) | python | def _GetMetadataRequest(self, metadata_url, params=None, timeout=None):
headers = {'Metadata-Flavor': 'Google'}
params = urlparse.urlencode(params or {})
url = '%s?%s' % (metadata_url, params)
request = urlrequest.Request(url, headers=headers)
request_opener = urlrequest.build_opener(urlrequest.ProxyHandler({}))
timeout = timeout or self.timeout
return request_opener.open(request, timeout=timeout*1.1) | [
"def",
"_GetMetadataRequest",
"(",
"self",
",",
"metadata_url",
",",
"params",
"=",
"None",
",",
"timeout",
"=",
"None",
")",
":",
"headers",
"=",
"{",
"'Metadata-Flavor'",
":",
"'Google'",
"}",
"params",
"=",
"urlparse",
".",
"urlencode",
"(",
"params",
"or",
"{",
"}",
")",
"url",
"=",
"'%s?%s'",
"%",
"(",
"metadata_url",
",",
"params",
")",
"request",
"=",
"urlrequest",
".",
"Request",
"(",
"url",
",",
"headers",
"=",
"headers",
")",
"request_opener",
"=",
"urlrequest",
".",
"build_opener",
"(",
"urlrequest",
".",
"ProxyHandler",
"(",
"{",
"}",
")",
")",
"timeout",
"=",
"timeout",
"or",
"self",
".",
"timeout",
"return",
"request_opener",
".",
"open",
"(",
"request",
",",
"timeout",
"=",
"timeout",
"*",
"1.1",
")"
] | Performs a GET request with the metadata headers.
Args:
metadata_url: string, the URL to perform a GET request on.
params: dictionary, the query parameters in the GET request.
timeout: int, timeout in seconds for metadata requests.
Returns:
HTTP response from the GET request.
Raises:
urlerror.HTTPError: raises when the GET request fails. | [
"Performs",
"a",
"GET",
"request",
"with",
"the",
"metadata",
"headers",
"."
] | 53ea8cd069fb4d9a1984d1c167e54c133033f8da | https://github.com/GoogleCloudPlatform/compute-image-packages/blob/53ea8cd069fb4d9a1984d1c167e54c133033f8da/packages/python-google-compute-engine/google_compute_engine/metadata_watcher.py#L82-L102 |
248,336 | GoogleCloudPlatform/compute-image-packages | packages/python-google-compute-engine/google_compute_engine/metadata_watcher.py | MetadataWatcher._UpdateEtag | def _UpdateEtag(self, response):
"""Update the etag from an API response.
Args:
response: HTTP response with a header field.
Returns:
bool, True if the etag in the response header updated.
"""
etag = response.headers.get('etag', self.etag)
etag_updated = self.etag != etag
self.etag = etag
return etag_updated | python | def _UpdateEtag(self, response):
etag = response.headers.get('etag', self.etag)
etag_updated = self.etag != etag
self.etag = etag
return etag_updated | [
"def",
"_UpdateEtag",
"(",
"self",
",",
"response",
")",
":",
"etag",
"=",
"response",
".",
"headers",
".",
"get",
"(",
"'etag'",
",",
"self",
".",
"etag",
")",
"etag_updated",
"=",
"self",
".",
"etag",
"!=",
"etag",
"self",
".",
"etag",
"=",
"etag",
"return",
"etag_updated"
] | Update the etag from an API response.
Args:
response: HTTP response with a header field.
Returns:
bool, True if the etag in the response header updated. | [
"Update",
"the",
"etag",
"from",
"an",
"API",
"response",
"."
] | 53ea8cd069fb4d9a1984d1c167e54c133033f8da | https://github.com/GoogleCloudPlatform/compute-image-packages/blob/53ea8cd069fb4d9a1984d1c167e54c133033f8da/packages/python-google-compute-engine/google_compute_engine/metadata_watcher.py#L104-L116 |
248,337 | GoogleCloudPlatform/compute-image-packages | packages/python-google-compute-engine/google_compute_engine/metadata_watcher.py | MetadataWatcher._GetMetadataUpdate | def _GetMetadataUpdate(
self, metadata_key='', recursive=True, wait=True, timeout=None):
"""Request the contents of metadata server and deserialize the response.
Args:
metadata_key: string, the metadata key to watch for changes.
recursive: bool, True if we should recursively watch for metadata changes.
wait: bool, True if we should wait for a metadata change.
timeout: int, timeout in seconds for returning metadata output.
Returns:
json, the deserialized contents of the metadata server.
"""
metadata_key = os.path.join(metadata_key, '') if recursive else metadata_key
metadata_url = os.path.join(METADATA_SERVER, metadata_key)
params = {
'alt': 'json',
'last_etag': self.etag,
'recursive': recursive,
'timeout_sec': timeout or self.timeout,
'wait_for_change': wait,
}
while True:
response = self._GetMetadataRequest(
metadata_url, params=params, timeout=timeout)
etag_updated = self._UpdateEtag(response)
if wait and not etag_updated and not timeout:
# Retry until the etag is updated.
continue
else:
# One of the following are true:
# - Waiting for change is not required.
# - The etag is updated.
# - The user specified a request timeout.
break
return json.loads(response.read().decode('utf-8')) | python | def _GetMetadataUpdate(
self, metadata_key='', recursive=True, wait=True, timeout=None):
metadata_key = os.path.join(metadata_key, '') if recursive else metadata_key
metadata_url = os.path.join(METADATA_SERVER, metadata_key)
params = {
'alt': 'json',
'last_etag': self.etag,
'recursive': recursive,
'timeout_sec': timeout or self.timeout,
'wait_for_change': wait,
}
while True:
response = self._GetMetadataRequest(
metadata_url, params=params, timeout=timeout)
etag_updated = self._UpdateEtag(response)
if wait and not etag_updated and not timeout:
# Retry until the etag is updated.
continue
else:
# One of the following are true:
# - Waiting for change is not required.
# - The etag is updated.
# - The user specified a request timeout.
break
return json.loads(response.read().decode('utf-8')) | [
"def",
"_GetMetadataUpdate",
"(",
"self",
",",
"metadata_key",
"=",
"''",
",",
"recursive",
"=",
"True",
",",
"wait",
"=",
"True",
",",
"timeout",
"=",
"None",
")",
":",
"metadata_key",
"=",
"os",
".",
"path",
".",
"join",
"(",
"metadata_key",
",",
"''",
")",
"if",
"recursive",
"else",
"metadata_key",
"metadata_url",
"=",
"os",
".",
"path",
".",
"join",
"(",
"METADATA_SERVER",
",",
"metadata_key",
")",
"params",
"=",
"{",
"'alt'",
":",
"'json'",
",",
"'last_etag'",
":",
"self",
".",
"etag",
",",
"'recursive'",
":",
"recursive",
",",
"'timeout_sec'",
":",
"timeout",
"or",
"self",
".",
"timeout",
",",
"'wait_for_change'",
":",
"wait",
",",
"}",
"while",
"True",
":",
"response",
"=",
"self",
".",
"_GetMetadataRequest",
"(",
"metadata_url",
",",
"params",
"=",
"params",
",",
"timeout",
"=",
"timeout",
")",
"etag_updated",
"=",
"self",
".",
"_UpdateEtag",
"(",
"response",
")",
"if",
"wait",
"and",
"not",
"etag_updated",
"and",
"not",
"timeout",
":",
"# Retry until the etag is updated.",
"continue",
"else",
":",
"# One of the following are true:",
"# - Waiting for change is not required.",
"# - The etag is updated.",
"# - The user specified a request timeout.",
"break",
"return",
"json",
".",
"loads",
"(",
"response",
".",
"read",
"(",
")",
".",
"decode",
"(",
"'utf-8'",
")",
")"
] | Request the contents of metadata server and deserialize the response.
Args:
metadata_key: string, the metadata key to watch for changes.
recursive: bool, True if we should recursively watch for metadata changes.
wait: bool, True if we should wait for a metadata change.
timeout: int, timeout in seconds for returning metadata output.
Returns:
json, the deserialized contents of the metadata server. | [
"Request",
"the",
"contents",
"of",
"metadata",
"server",
"and",
"deserialize",
"the",
"response",
"."
] | 53ea8cd069fb4d9a1984d1c167e54c133033f8da | https://github.com/GoogleCloudPlatform/compute-image-packages/blob/53ea8cd069fb4d9a1984d1c167e54c133033f8da/packages/python-google-compute-engine/google_compute_engine/metadata_watcher.py#L118-L153 |
248,338 | GoogleCloudPlatform/compute-image-packages | packages/python-google-compute-engine/google_compute_engine/metadata_watcher.py | MetadataWatcher._HandleMetadataUpdate | def _HandleMetadataUpdate(
self, metadata_key='', recursive=True, wait=True, timeout=None,
retry=True):
"""Wait for a successful metadata response.
Args:
metadata_key: string, the metadata key to watch for changes.
recursive: bool, True if we should recursively watch for metadata changes.
wait: bool, True if we should wait for a metadata change.
timeout: int, timeout in seconds for returning metadata output.
retry: bool, True if we should retry on failure.
Returns:
json, the deserialized contents of the metadata server.
"""
exception = None
while True:
try:
return self._GetMetadataUpdate(
metadata_key=metadata_key, recursive=recursive, wait=wait,
timeout=timeout)
except (httpclient.HTTPException, socket.error, urlerror.URLError) as e:
if not isinstance(e, type(exception)):
exception = e
self.logger.error('GET request error retrieving metadata. %s.', e)
if retry:
continue
else:
break | python | def _HandleMetadataUpdate(
self, metadata_key='', recursive=True, wait=True, timeout=None,
retry=True):
exception = None
while True:
try:
return self._GetMetadataUpdate(
metadata_key=metadata_key, recursive=recursive, wait=wait,
timeout=timeout)
except (httpclient.HTTPException, socket.error, urlerror.URLError) as e:
if not isinstance(e, type(exception)):
exception = e
self.logger.error('GET request error retrieving metadata. %s.', e)
if retry:
continue
else:
break | [
"def",
"_HandleMetadataUpdate",
"(",
"self",
",",
"metadata_key",
"=",
"''",
",",
"recursive",
"=",
"True",
",",
"wait",
"=",
"True",
",",
"timeout",
"=",
"None",
",",
"retry",
"=",
"True",
")",
":",
"exception",
"=",
"None",
"while",
"True",
":",
"try",
":",
"return",
"self",
".",
"_GetMetadataUpdate",
"(",
"metadata_key",
"=",
"metadata_key",
",",
"recursive",
"=",
"recursive",
",",
"wait",
"=",
"wait",
",",
"timeout",
"=",
"timeout",
")",
"except",
"(",
"httpclient",
".",
"HTTPException",
",",
"socket",
".",
"error",
",",
"urlerror",
".",
"URLError",
")",
"as",
"e",
":",
"if",
"not",
"isinstance",
"(",
"e",
",",
"type",
"(",
"exception",
")",
")",
":",
"exception",
"=",
"e",
"self",
".",
"logger",
".",
"error",
"(",
"'GET request error retrieving metadata. %s.'",
",",
"e",
")",
"if",
"retry",
":",
"continue",
"else",
":",
"break"
] | Wait for a successful metadata response.
Args:
metadata_key: string, the metadata key to watch for changes.
recursive: bool, True if we should recursively watch for metadata changes.
wait: bool, True if we should wait for a metadata change.
timeout: int, timeout in seconds for returning metadata output.
retry: bool, True if we should retry on failure.
Returns:
json, the deserialized contents of the metadata server. | [
"Wait",
"for",
"a",
"successful",
"metadata",
"response",
"."
] | 53ea8cd069fb4d9a1984d1c167e54c133033f8da | https://github.com/GoogleCloudPlatform/compute-image-packages/blob/53ea8cd069fb4d9a1984d1c167e54c133033f8da/packages/python-google-compute-engine/google_compute_engine/metadata_watcher.py#L155-L183 |
248,339 | GoogleCloudPlatform/compute-image-packages | packages/python-google-compute-engine/google_compute_engine/metadata_watcher.py | MetadataWatcher.WatchMetadata | def WatchMetadata(
self, handler, metadata_key='', recursive=True, timeout=None):
"""Watch for changes to the contents of the metadata server.
Args:
handler: callable, a function to call with the updated metadata contents.
metadata_key: string, the metadata key to watch for changes.
recursive: bool, True if we should recursively watch for metadata changes.
timeout: int, timeout in seconds for returning metadata output.
"""
while True:
response = self._HandleMetadataUpdate(
metadata_key=metadata_key, recursive=recursive, wait=True,
timeout=timeout)
try:
handler(response)
except Exception as e:
self.logger.exception('Exception calling the response handler. %s.', e) | python | def WatchMetadata(
self, handler, metadata_key='', recursive=True, timeout=None):
while True:
response = self._HandleMetadataUpdate(
metadata_key=metadata_key, recursive=recursive, wait=True,
timeout=timeout)
try:
handler(response)
except Exception as e:
self.logger.exception('Exception calling the response handler. %s.', e) | [
"def",
"WatchMetadata",
"(",
"self",
",",
"handler",
",",
"metadata_key",
"=",
"''",
",",
"recursive",
"=",
"True",
",",
"timeout",
"=",
"None",
")",
":",
"while",
"True",
":",
"response",
"=",
"self",
".",
"_HandleMetadataUpdate",
"(",
"metadata_key",
"=",
"metadata_key",
",",
"recursive",
"=",
"recursive",
",",
"wait",
"=",
"True",
",",
"timeout",
"=",
"timeout",
")",
"try",
":",
"handler",
"(",
"response",
")",
"except",
"Exception",
"as",
"e",
":",
"self",
".",
"logger",
".",
"exception",
"(",
"'Exception calling the response handler. %s.'",
",",
"e",
")"
] | Watch for changes to the contents of the metadata server.
Args:
handler: callable, a function to call with the updated metadata contents.
metadata_key: string, the metadata key to watch for changes.
recursive: bool, True if we should recursively watch for metadata changes.
timeout: int, timeout in seconds for returning metadata output. | [
"Watch",
"for",
"changes",
"to",
"the",
"contents",
"of",
"the",
"metadata",
"server",
"."
] | 53ea8cd069fb4d9a1984d1c167e54c133033f8da | https://github.com/GoogleCloudPlatform/compute-image-packages/blob/53ea8cd069fb4d9a1984d1c167e54c133033f8da/packages/python-google-compute-engine/google_compute_engine/metadata_watcher.py#L185-L202 |
248,340 | GoogleCloudPlatform/compute-image-packages | packages/python-google-compute-engine/google_compute_engine/metadata_watcher.py | MetadataWatcher.GetMetadata | def GetMetadata(
self, metadata_key='', recursive=True, timeout=None, retry=True):
"""Retrieve the contents of metadata server for a metadata key.
Args:
metadata_key: string, the metadata key to watch for changes.
recursive: bool, True if we should recursively watch for metadata changes.
timeout: int, timeout in seconds for returning metadata output.
retry: bool, True if we should retry on failure.
Returns:
json, the deserialized contents of the metadata server or None if error.
"""
return self._HandleMetadataUpdate(
metadata_key=metadata_key, recursive=recursive, wait=False,
timeout=timeout, retry=retry) | python | def GetMetadata(
self, metadata_key='', recursive=True, timeout=None, retry=True):
return self._HandleMetadataUpdate(
metadata_key=metadata_key, recursive=recursive, wait=False,
timeout=timeout, retry=retry) | [
"def",
"GetMetadata",
"(",
"self",
",",
"metadata_key",
"=",
"''",
",",
"recursive",
"=",
"True",
",",
"timeout",
"=",
"None",
",",
"retry",
"=",
"True",
")",
":",
"return",
"self",
".",
"_HandleMetadataUpdate",
"(",
"metadata_key",
"=",
"metadata_key",
",",
"recursive",
"=",
"recursive",
",",
"wait",
"=",
"False",
",",
"timeout",
"=",
"timeout",
",",
"retry",
"=",
"retry",
")"
] | Retrieve the contents of metadata server for a metadata key.
Args:
metadata_key: string, the metadata key to watch for changes.
recursive: bool, True if we should recursively watch for metadata changes.
timeout: int, timeout in seconds for returning metadata output.
retry: bool, True if we should retry on failure.
Returns:
json, the deserialized contents of the metadata server or None if error. | [
"Retrieve",
"the",
"contents",
"of",
"metadata",
"server",
"for",
"a",
"metadata",
"key",
"."
] | 53ea8cd069fb4d9a1984d1c167e54c133033f8da | https://github.com/GoogleCloudPlatform/compute-image-packages/blob/53ea8cd069fb4d9a1984d1c167e54c133033f8da/packages/python-google-compute-engine/google_compute_engine/metadata_watcher.py#L204-L219 |
248,341 | GoogleCloudPlatform/compute-image-packages | packages/python-google-compute-engine/google_compute_engine/networking/ip_forwarding/ip_forwarding.py | IpForwarding._LogForwardedIpChanges | def _LogForwardedIpChanges(
self, configured, desired, to_add, to_remove, interface):
"""Log the planned IP address changes.
Args:
configured: list, the IP address strings already configured.
desired: list, the IP address strings that will be configured.
to_add: list, the forwarded IP address strings to configure.
to_remove: list, the forwarded IP address strings to delete.
interface: string, the output device to modify.
"""
if not to_add and not to_remove:
return
self.logger.info(
'Changing %s IPs from %s to %s by adding %s and removing %s.',
interface, configured or None, desired or None, to_add or None,
to_remove or None) | python | def _LogForwardedIpChanges(
self, configured, desired, to_add, to_remove, interface):
if not to_add and not to_remove:
return
self.logger.info(
'Changing %s IPs from %s to %s by adding %s and removing %s.',
interface, configured or None, desired or None, to_add or None,
to_remove or None) | [
"def",
"_LogForwardedIpChanges",
"(",
"self",
",",
"configured",
",",
"desired",
",",
"to_add",
",",
"to_remove",
",",
"interface",
")",
":",
"if",
"not",
"to_add",
"and",
"not",
"to_remove",
":",
"return",
"self",
".",
"logger",
".",
"info",
"(",
"'Changing %s IPs from %s to %s by adding %s and removing %s.'",
",",
"interface",
",",
"configured",
"or",
"None",
",",
"desired",
"or",
"None",
",",
"to_add",
"or",
"None",
",",
"to_remove",
"or",
"None",
")"
] | Log the planned IP address changes.
Args:
configured: list, the IP address strings already configured.
desired: list, the IP address strings that will be configured.
to_add: list, the forwarded IP address strings to configure.
to_remove: list, the forwarded IP address strings to delete.
interface: string, the output device to modify. | [
"Log",
"the",
"planned",
"IP",
"address",
"changes",
"."
] | 53ea8cd069fb4d9a1984d1c167e54c133033f8da | https://github.com/GoogleCloudPlatform/compute-image-packages/blob/53ea8cd069fb4d9a1984d1c167e54c133033f8da/packages/python-google-compute-engine/google_compute_engine/networking/ip_forwarding/ip_forwarding.py#L45-L61 |
248,342 | GoogleCloudPlatform/compute-image-packages | packages/python-google-compute-engine/google_compute_engine/networking/ip_forwarding/ip_forwarding.py | IpForwarding._AddForwardedIps | def _AddForwardedIps(self, forwarded_ips, interface):
"""Configure the forwarded IP address on the network interface.
Args:
forwarded_ips: list, the forwarded IP address strings to configure.
interface: string, the output device to use.
"""
for address in forwarded_ips:
self.ip_forwarding_utils.AddForwardedIp(address, interface) | python | def _AddForwardedIps(self, forwarded_ips, interface):
for address in forwarded_ips:
self.ip_forwarding_utils.AddForwardedIp(address, interface) | [
"def",
"_AddForwardedIps",
"(",
"self",
",",
"forwarded_ips",
",",
"interface",
")",
":",
"for",
"address",
"in",
"forwarded_ips",
":",
"self",
".",
"ip_forwarding_utils",
".",
"AddForwardedIp",
"(",
"address",
",",
"interface",
")"
] | Configure the forwarded IP address on the network interface.
Args:
forwarded_ips: list, the forwarded IP address strings to configure.
interface: string, the output device to use. | [
"Configure",
"the",
"forwarded",
"IP",
"address",
"on",
"the",
"network",
"interface",
"."
] | 53ea8cd069fb4d9a1984d1c167e54c133033f8da | https://github.com/GoogleCloudPlatform/compute-image-packages/blob/53ea8cd069fb4d9a1984d1c167e54c133033f8da/packages/python-google-compute-engine/google_compute_engine/networking/ip_forwarding/ip_forwarding.py#L63-L71 |
248,343 | GoogleCloudPlatform/compute-image-packages | packages/python-google-compute-engine/google_compute_engine/networking/ip_forwarding/ip_forwarding.py | IpForwarding._RemoveForwardedIps | def _RemoveForwardedIps(self, forwarded_ips, interface):
"""Remove the forwarded IP addresses from the network interface.
Args:
forwarded_ips: list, the forwarded IP address strings to delete.
interface: string, the output device to use.
"""
for address in forwarded_ips:
self.ip_forwarding_utils.RemoveForwardedIp(address, interface) | python | def _RemoveForwardedIps(self, forwarded_ips, interface):
for address in forwarded_ips:
self.ip_forwarding_utils.RemoveForwardedIp(address, interface) | [
"def",
"_RemoveForwardedIps",
"(",
"self",
",",
"forwarded_ips",
",",
"interface",
")",
":",
"for",
"address",
"in",
"forwarded_ips",
":",
"self",
".",
"ip_forwarding_utils",
".",
"RemoveForwardedIp",
"(",
"address",
",",
"interface",
")"
] | Remove the forwarded IP addresses from the network interface.
Args:
forwarded_ips: list, the forwarded IP address strings to delete.
interface: string, the output device to use. | [
"Remove",
"the",
"forwarded",
"IP",
"addresses",
"from",
"the",
"network",
"interface",
"."
] | 53ea8cd069fb4d9a1984d1c167e54c133033f8da | https://github.com/GoogleCloudPlatform/compute-image-packages/blob/53ea8cd069fb4d9a1984d1c167e54c133033f8da/packages/python-google-compute-engine/google_compute_engine/networking/ip_forwarding/ip_forwarding.py#L73-L81 |
248,344 | GoogleCloudPlatform/compute-image-packages | packages/python-google-compute-engine/google_compute_engine/networking/ip_forwarding/ip_forwarding.py | IpForwarding.HandleForwardedIps | def HandleForwardedIps(self, interface, forwarded_ips, interface_ip=None):
"""Handle changes to the forwarded IPs on a network interface.
Args:
interface: string, the output device to configure.
forwarded_ips: list, the forwarded IP address strings desired.
interface_ip: string, current interface ip address.
"""
desired = self.ip_forwarding_utils.ParseForwardedIps(forwarded_ips)
configured = self.ip_forwarding_utils.GetForwardedIps(
interface, interface_ip)
to_add = sorted(set(desired) - set(configured))
to_remove = sorted(set(configured) - set(desired))
self._LogForwardedIpChanges(
configured, desired, to_add, to_remove, interface)
self._AddForwardedIps(to_add, interface)
self._RemoveForwardedIps(to_remove, interface) | python | def HandleForwardedIps(self, interface, forwarded_ips, interface_ip=None):
desired = self.ip_forwarding_utils.ParseForwardedIps(forwarded_ips)
configured = self.ip_forwarding_utils.GetForwardedIps(
interface, interface_ip)
to_add = sorted(set(desired) - set(configured))
to_remove = sorted(set(configured) - set(desired))
self._LogForwardedIpChanges(
configured, desired, to_add, to_remove, interface)
self._AddForwardedIps(to_add, interface)
self._RemoveForwardedIps(to_remove, interface) | [
"def",
"HandleForwardedIps",
"(",
"self",
",",
"interface",
",",
"forwarded_ips",
",",
"interface_ip",
"=",
"None",
")",
":",
"desired",
"=",
"self",
".",
"ip_forwarding_utils",
".",
"ParseForwardedIps",
"(",
"forwarded_ips",
")",
"configured",
"=",
"self",
".",
"ip_forwarding_utils",
".",
"GetForwardedIps",
"(",
"interface",
",",
"interface_ip",
")",
"to_add",
"=",
"sorted",
"(",
"set",
"(",
"desired",
")",
"-",
"set",
"(",
"configured",
")",
")",
"to_remove",
"=",
"sorted",
"(",
"set",
"(",
"configured",
")",
"-",
"set",
"(",
"desired",
")",
")",
"self",
".",
"_LogForwardedIpChanges",
"(",
"configured",
",",
"desired",
",",
"to_add",
",",
"to_remove",
",",
"interface",
")",
"self",
".",
"_AddForwardedIps",
"(",
"to_add",
",",
"interface",
")",
"self",
".",
"_RemoveForwardedIps",
"(",
"to_remove",
",",
"interface",
")"
] | Handle changes to the forwarded IPs on a network interface.
Args:
interface: string, the output device to configure.
forwarded_ips: list, the forwarded IP address strings desired.
interface_ip: string, current interface ip address. | [
"Handle",
"changes",
"to",
"the",
"forwarded",
"IPs",
"on",
"a",
"network",
"interface",
"."
] | 53ea8cd069fb4d9a1984d1c167e54c133033f8da | https://github.com/GoogleCloudPlatform/compute-image-packages/blob/53ea8cd069fb4d9a1984d1c167e54c133033f8da/packages/python-google-compute-engine/google_compute_engine/networking/ip_forwarding/ip_forwarding.py#L83-L99 |
248,345 | GoogleCloudPlatform/compute-image-packages | packages/python-google-compute-engine/google_compute_engine/distro_lib/sles_12/utils.py | Utils._WriteIfcfg | def _WriteIfcfg(self, interfaces, logger):
"""Write ifcfg files for multi-NIC support.
Overwrites the files. This allows us to update ifcfg-* in the future.
Disable the network setup to override this behavior and customize the
configurations.
Args:
interfaces: list of string, the output device names to enable.
logger: logger object, used to write to SysLog and serial port.
"""
for interface in interfaces:
interface_config = os.path.join(
self.network_path, 'ifcfg-%s' % interface)
interface_content = [
'# Added by Google.',
'STARTMODE=hotplug',
'BOOTPROTO=dhcp',
'DHCLIENT_SET_DEFAULT_ROUTE=yes',
'DHCLIENT_ROUTE_PRIORITY=10%s00' % interface,
'',
]
with open(interface_config, 'w') as interface_file:
interface_file.write('\n'.join(interface_content))
logger.info('Created ifcfg file for interface %s.', interface) | python | def _WriteIfcfg(self, interfaces, logger):
for interface in interfaces:
interface_config = os.path.join(
self.network_path, 'ifcfg-%s' % interface)
interface_content = [
'# Added by Google.',
'STARTMODE=hotplug',
'BOOTPROTO=dhcp',
'DHCLIENT_SET_DEFAULT_ROUTE=yes',
'DHCLIENT_ROUTE_PRIORITY=10%s00' % interface,
'',
]
with open(interface_config, 'w') as interface_file:
interface_file.write('\n'.join(interface_content))
logger.info('Created ifcfg file for interface %s.', interface) | [
"def",
"_WriteIfcfg",
"(",
"self",
",",
"interfaces",
",",
"logger",
")",
":",
"for",
"interface",
"in",
"interfaces",
":",
"interface_config",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"network_path",
",",
"'ifcfg-%s'",
"%",
"interface",
")",
"interface_content",
"=",
"[",
"'# Added by Google.'",
",",
"'STARTMODE=hotplug'",
",",
"'BOOTPROTO=dhcp'",
",",
"'DHCLIENT_SET_DEFAULT_ROUTE=yes'",
",",
"'DHCLIENT_ROUTE_PRIORITY=10%s00'",
"%",
"interface",
",",
"''",
",",
"]",
"with",
"open",
"(",
"interface_config",
",",
"'w'",
")",
"as",
"interface_file",
":",
"interface_file",
".",
"write",
"(",
"'\\n'",
".",
"join",
"(",
"interface_content",
")",
")",
"logger",
".",
"info",
"(",
"'Created ifcfg file for interface %s.'",
",",
"interface",
")"
] | Write ifcfg files for multi-NIC support.
Overwrites the files. This allows us to update ifcfg-* in the future.
Disable the network setup to override this behavior and customize the
configurations.
Args:
interfaces: list of string, the output device names to enable.
logger: logger object, used to write to SysLog and serial port. | [
"Write",
"ifcfg",
"files",
"for",
"multi",
"-",
"NIC",
"support",
"."
] | 53ea8cd069fb4d9a1984d1c167e54c133033f8da | https://github.com/GoogleCloudPlatform/compute-image-packages/blob/53ea8cd069fb4d9a1984d1c167e54c133033f8da/packages/python-google-compute-engine/google_compute_engine/distro_lib/sles_12/utils.py#L47-L71 |
248,346 | GoogleCloudPlatform/compute-image-packages | packages/python-google-compute-engine/google_compute_engine/distro_lib/sles_12/utils.py | Utils._Ifup | def _Ifup(self, interfaces, logger):
"""Activate network interfaces.
Args:
interfaces: list of string, the output device names to enable.
logger: logger object, used to write to SysLog and serial port.
"""
ifup = ['/usr/sbin/wicked', 'ifup', '--timeout', '1']
try:
subprocess.check_call(ifup + interfaces)
except subprocess.CalledProcessError:
logger.warning('Could not activate interfaces %s.', interfaces) | python | def _Ifup(self, interfaces, logger):
ifup = ['/usr/sbin/wicked', 'ifup', '--timeout', '1']
try:
subprocess.check_call(ifup + interfaces)
except subprocess.CalledProcessError:
logger.warning('Could not activate interfaces %s.', interfaces) | [
"def",
"_Ifup",
"(",
"self",
",",
"interfaces",
",",
"logger",
")",
":",
"ifup",
"=",
"[",
"'/usr/sbin/wicked'",
",",
"'ifup'",
",",
"'--timeout'",
",",
"'1'",
"]",
"try",
":",
"subprocess",
".",
"check_call",
"(",
"ifup",
"+",
"interfaces",
")",
"except",
"subprocess",
".",
"CalledProcessError",
":",
"logger",
".",
"warning",
"(",
"'Could not activate interfaces %s.'",
",",
"interfaces",
")"
] | Activate network interfaces.
Args:
interfaces: list of string, the output device names to enable.
logger: logger object, used to write to SysLog and serial port. | [
"Activate",
"network",
"interfaces",
"."
] | 53ea8cd069fb4d9a1984d1c167e54c133033f8da | https://github.com/GoogleCloudPlatform/compute-image-packages/blob/53ea8cd069fb4d9a1984d1c167e54c133033f8da/packages/python-google-compute-engine/google_compute_engine/distro_lib/sles_12/utils.py#L73-L84 |
248,347 | GoogleCloudPlatform/compute-image-packages | packages/python-google-compute-engine/google_compute_engine/networking/network_daemon.py | NetworkDaemon.HandleNetworkInterfaces | def HandleNetworkInterfaces(self, result):
"""Called when network interface metadata changes.
Args:
result: dict, the metadata response with the network interfaces.
"""
network_interfaces = self._ExtractInterfaceMetadata(result)
if self.network_setup_enabled:
self.network_setup.EnableNetworkInterfaces(
[interface.name for interface in network_interfaces[1:]])
for interface in network_interfaces:
if self.ip_forwarding_enabled:
self.ip_forwarding.HandleForwardedIps(
interface.name, interface.forwarded_ips, interface.ip) | python | def HandleNetworkInterfaces(self, result):
network_interfaces = self._ExtractInterfaceMetadata(result)
if self.network_setup_enabled:
self.network_setup.EnableNetworkInterfaces(
[interface.name for interface in network_interfaces[1:]])
for interface in network_interfaces:
if self.ip_forwarding_enabled:
self.ip_forwarding.HandleForwardedIps(
interface.name, interface.forwarded_ips, interface.ip) | [
"def",
"HandleNetworkInterfaces",
"(",
"self",
",",
"result",
")",
":",
"network_interfaces",
"=",
"self",
".",
"_ExtractInterfaceMetadata",
"(",
"result",
")",
"if",
"self",
".",
"network_setup_enabled",
":",
"self",
".",
"network_setup",
".",
"EnableNetworkInterfaces",
"(",
"[",
"interface",
".",
"name",
"for",
"interface",
"in",
"network_interfaces",
"[",
"1",
":",
"]",
"]",
")",
"for",
"interface",
"in",
"network_interfaces",
":",
"if",
"self",
".",
"ip_forwarding_enabled",
":",
"self",
".",
"ip_forwarding",
".",
"HandleForwardedIps",
"(",
"interface",
".",
"name",
",",
"interface",
".",
"forwarded_ips",
",",
"interface",
".",
"ip",
")"
] | Called when network interface metadata changes.
Args:
result: dict, the metadata response with the network interfaces. | [
"Called",
"when",
"network",
"interface",
"metadata",
"changes",
"."
] | 53ea8cd069fb4d9a1984d1c167e54c133033f8da | https://github.com/GoogleCloudPlatform/compute-image-packages/blob/53ea8cd069fb4d9a1984d1c167e54c133033f8da/packages/python-google-compute-engine/google_compute_engine/networking/network_daemon.py#L84-L99 |
248,348 | GoogleCloudPlatform/compute-image-packages | packages/python-google-compute-engine/google_compute_engine/networking/network_daemon.py | NetworkDaemon._ExtractInterfaceMetadata | def _ExtractInterfaceMetadata(self, metadata):
"""Extracts network interface metadata.
Args:
metadata: dict, the metadata response with the new network interfaces.
Returns:
list, a list of NetworkInterface objects.
"""
interfaces = []
for network_interface in metadata:
mac_address = network_interface.get('mac')
interface = self.network_utils.GetNetworkInterface(mac_address)
ip_addresses = []
if interface:
ip_addresses.extend(network_interface.get('forwardedIps', []))
if self.ip_aliases:
ip_addresses.extend(network_interface.get('ipAliases', []))
if self.target_instance_ips:
ip_addresses.extend(network_interface.get('targetInstanceIps', []))
interfaces.append(NetworkDaemon.NetworkInterface(
interface, ip_addresses, network_interface.get('ip', [])))
else:
message = 'Network interface not found for MAC address: %s.'
self.logger.warning(message, mac_address)
return interfaces | python | def _ExtractInterfaceMetadata(self, metadata):
interfaces = []
for network_interface in metadata:
mac_address = network_interface.get('mac')
interface = self.network_utils.GetNetworkInterface(mac_address)
ip_addresses = []
if interface:
ip_addresses.extend(network_interface.get('forwardedIps', []))
if self.ip_aliases:
ip_addresses.extend(network_interface.get('ipAliases', []))
if self.target_instance_ips:
ip_addresses.extend(network_interface.get('targetInstanceIps', []))
interfaces.append(NetworkDaemon.NetworkInterface(
interface, ip_addresses, network_interface.get('ip', [])))
else:
message = 'Network interface not found for MAC address: %s.'
self.logger.warning(message, mac_address)
return interfaces | [
"def",
"_ExtractInterfaceMetadata",
"(",
"self",
",",
"metadata",
")",
":",
"interfaces",
"=",
"[",
"]",
"for",
"network_interface",
"in",
"metadata",
":",
"mac_address",
"=",
"network_interface",
".",
"get",
"(",
"'mac'",
")",
"interface",
"=",
"self",
".",
"network_utils",
".",
"GetNetworkInterface",
"(",
"mac_address",
")",
"ip_addresses",
"=",
"[",
"]",
"if",
"interface",
":",
"ip_addresses",
".",
"extend",
"(",
"network_interface",
".",
"get",
"(",
"'forwardedIps'",
",",
"[",
"]",
")",
")",
"if",
"self",
".",
"ip_aliases",
":",
"ip_addresses",
".",
"extend",
"(",
"network_interface",
".",
"get",
"(",
"'ipAliases'",
",",
"[",
"]",
")",
")",
"if",
"self",
".",
"target_instance_ips",
":",
"ip_addresses",
".",
"extend",
"(",
"network_interface",
".",
"get",
"(",
"'targetInstanceIps'",
",",
"[",
"]",
")",
")",
"interfaces",
".",
"append",
"(",
"NetworkDaemon",
".",
"NetworkInterface",
"(",
"interface",
",",
"ip_addresses",
",",
"network_interface",
".",
"get",
"(",
"'ip'",
",",
"[",
"]",
")",
")",
")",
"else",
":",
"message",
"=",
"'Network interface not found for MAC address: %s.'",
"self",
".",
"logger",
".",
"warning",
"(",
"message",
",",
"mac_address",
")",
"return",
"interfaces"
] | Extracts network interface metadata.
Args:
metadata: dict, the metadata response with the new network interfaces.
Returns:
list, a list of NetworkInterface objects. | [
"Extracts",
"network",
"interface",
"metadata",
"."
] | 53ea8cd069fb4d9a1984d1c167e54c133033f8da | https://github.com/GoogleCloudPlatform/compute-image-packages/blob/53ea8cd069fb4d9a1984d1c167e54c133033f8da/packages/python-google-compute-engine/google_compute_engine/networking/network_daemon.py#L101-L126 |
248,349 | sendgrid/python-http-client | python_http_client/client.py | Client._build_url | def _build_url(self, query_params):
"""Build the final URL to be passed to urllib
:param query_params: A dictionary of all the query parameters
:type query_params: dictionary
:return: string
"""
url = ''
count = 0
while count < len(self._url_path):
url += '/{}'.format(self._url_path[count])
count += 1
# add slash
if self.append_slash:
url += '/'
if query_params:
url_values = urlencode(sorted(query_params.items()), True)
url = '{}?{}'.format(url, url_values)
if self._version:
url = self._build_versioned_url(url)
else:
url = '{}{}'.format(self.host, url)
return url | python | def _build_url(self, query_params):
url = ''
count = 0
while count < len(self._url_path):
url += '/{}'.format(self._url_path[count])
count += 1
# add slash
if self.append_slash:
url += '/'
if query_params:
url_values = urlencode(sorted(query_params.items()), True)
url = '{}?{}'.format(url, url_values)
if self._version:
url = self._build_versioned_url(url)
else:
url = '{}{}'.format(self.host, url)
return url | [
"def",
"_build_url",
"(",
"self",
",",
"query_params",
")",
":",
"url",
"=",
"''",
"count",
"=",
"0",
"while",
"count",
"<",
"len",
"(",
"self",
".",
"_url_path",
")",
":",
"url",
"+=",
"'/{}'",
".",
"format",
"(",
"self",
".",
"_url_path",
"[",
"count",
"]",
")",
"count",
"+=",
"1",
"# add slash",
"if",
"self",
".",
"append_slash",
":",
"url",
"+=",
"'/'",
"if",
"query_params",
":",
"url_values",
"=",
"urlencode",
"(",
"sorted",
"(",
"query_params",
".",
"items",
"(",
")",
")",
",",
"True",
")",
"url",
"=",
"'{}?{}'",
".",
"format",
"(",
"url",
",",
"url_values",
")",
"if",
"self",
".",
"_version",
":",
"url",
"=",
"self",
".",
"_build_versioned_url",
"(",
"url",
")",
"else",
":",
"url",
"=",
"'{}{}'",
".",
"format",
"(",
"self",
".",
"host",
",",
"url",
")",
"return",
"url"
] | Build the final URL to be passed to urllib
:param query_params: A dictionary of all the query parameters
:type query_params: dictionary
:return: string | [
"Build",
"the",
"final",
"URL",
"to",
"be",
"passed",
"to",
"urllib"
] | fa72b743fbf1aa499cc4e34d6a690af3e16a7a4d | https://github.com/sendgrid/python-http-client/blob/fa72b743fbf1aa499cc4e34d6a690af3e16a7a4d/python_http_client/client.py#L107-L132 |
248,350 | sendgrid/python-http-client | python_http_client/client.py | Client._build_client | def _build_client(self, name=None):
"""Make a new Client object
:param name: Name of the url segment
:type name: string
:return: A Client object
"""
url_path = self._url_path + [name] if name else self._url_path
return Client(host=self.host,
version=self._version,
request_headers=self.request_headers,
url_path=url_path,
append_slash=self.append_slash,
timeout=self.timeout) | python | def _build_client(self, name=None):
url_path = self._url_path + [name] if name else self._url_path
return Client(host=self.host,
version=self._version,
request_headers=self.request_headers,
url_path=url_path,
append_slash=self.append_slash,
timeout=self.timeout) | [
"def",
"_build_client",
"(",
"self",
",",
"name",
"=",
"None",
")",
":",
"url_path",
"=",
"self",
".",
"_url_path",
"+",
"[",
"name",
"]",
"if",
"name",
"else",
"self",
".",
"_url_path",
"return",
"Client",
"(",
"host",
"=",
"self",
".",
"host",
",",
"version",
"=",
"self",
".",
"_version",
",",
"request_headers",
"=",
"self",
".",
"request_headers",
",",
"url_path",
"=",
"url_path",
",",
"append_slash",
"=",
"self",
".",
"append_slash",
",",
"timeout",
"=",
"self",
".",
"timeout",
")"
] | Make a new Client object
:param name: Name of the url segment
:type name: string
:return: A Client object | [
"Make",
"a",
"new",
"Client",
"object"
] | fa72b743fbf1aa499cc4e34d6a690af3e16a7a4d | https://github.com/sendgrid/python-http-client/blob/fa72b743fbf1aa499cc4e34d6a690af3e16a7a4d/python_http_client/client.py#L143-L156 |
248,351 | sendgrid/python-http-client | python_http_client/client.py | Client._make_request | def _make_request(self, opener, request, timeout=None):
"""Make the API call and return the response. This is separated into
it's own function, so we can mock it easily for testing.
:param opener:
:type opener:
:param request: url payload to request
:type request: urllib.Request object
:param timeout: timeout value or None
:type timeout: float
:return: urllib response
"""
timeout = timeout or self.timeout
try:
return opener.open(request, timeout=timeout)
except HTTPError as err:
exc = handle_error(err)
exc.__cause__ = None
raise exc | python | def _make_request(self, opener, request, timeout=None):
timeout = timeout or self.timeout
try:
return opener.open(request, timeout=timeout)
except HTTPError as err:
exc = handle_error(err)
exc.__cause__ = None
raise exc | [
"def",
"_make_request",
"(",
"self",
",",
"opener",
",",
"request",
",",
"timeout",
"=",
"None",
")",
":",
"timeout",
"=",
"timeout",
"or",
"self",
".",
"timeout",
"try",
":",
"return",
"opener",
".",
"open",
"(",
"request",
",",
"timeout",
"=",
"timeout",
")",
"except",
"HTTPError",
"as",
"err",
":",
"exc",
"=",
"handle_error",
"(",
"err",
")",
"exc",
".",
"__cause__",
"=",
"None",
"raise",
"exc"
] | Make the API call and return the response. This is separated into
it's own function, so we can mock it easily for testing.
:param opener:
:type opener:
:param request: url payload to request
:type request: urllib.Request object
:param timeout: timeout value or None
:type timeout: float
:return: urllib response | [
"Make",
"the",
"API",
"call",
"and",
"return",
"the",
"response",
".",
"This",
"is",
"separated",
"into",
"it",
"s",
"own",
"function",
"so",
"we",
"can",
"mock",
"it",
"easily",
"for",
"testing",
"."
] | fa72b743fbf1aa499cc4e34d6a690af3e16a7a4d | https://github.com/sendgrid/python-http-client/blob/fa72b743fbf1aa499cc4e34d6a690af3e16a7a4d/python_http_client/client.py#L158-L176 |
248,352 | junzis/pyModeS | pyModeS/decoder/bds/bds08.py | category | def category(msg):
"""Aircraft category number
Args:
msg (string): 28 bytes hexadecimal message string
Returns:
int: category number
"""
if common.typecode(msg) < 1 or common.typecode(msg) > 4:
raise RuntimeError("%s: Not a identification message" % msg)
msgbin = common.hex2bin(msg)
return common.bin2int(msgbin[5:8]) | python | def category(msg):
if common.typecode(msg) < 1 or common.typecode(msg) > 4:
raise RuntimeError("%s: Not a identification message" % msg)
msgbin = common.hex2bin(msg)
return common.bin2int(msgbin[5:8]) | [
"def",
"category",
"(",
"msg",
")",
":",
"if",
"common",
".",
"typecode",
"(",
"msg",
")",
"<",
"1",
"or",
"common",
".",
"typecode",
"(",
"msg",
")",
">",
"4",
":",
"raise",
"RuntimeError",
"(",
"\"%s: Not a identification message\"",
"%",
"msg",
")",
"msgbin",
"=",
"common",
".",
"hex2bin",
"(",
"msg",
")",
"return",
"common",
".",
"bin2int",
"(",
"msgbin",
"[",
"5",
":",
"8",
"]",
")"
] | Aircraft category number
Args:
msg (string): 28 bytes hexadecimal message string
Returns:
int: category number | [
"Aircraft",
"category",
"number"
] | 8cd5655a04b08171a9ad5f1ffd232b7e0178ea53 | https://github.com/junzis/pyModeS/blob/8cd5655a04b08171a9ad5f1ffd232b7e0178ea53/pyModeS/decoder/bds/bds08.py#L26-L40 |
248,353 | junzis/pyModeS | pyModeS/decoder/bds/bds05.py | airborne_position | def airborne_position(msg0, msg1, t0, t1):
"""Decode airborn position from a pair of even and odd position message
Args:
msg0 (string): even message (28 bytes hexadecimal string)
msg1 (string): odd message (28 bytes hexadecimal string)
t0 (int): timestamps for the even message
t1 (int): timestamps for the odd message
Returns:
(float, float): (latitude, longitude) of the aircraft
"""
mb0 = common.hex2bin(msg0)[32:]
mb1 = common.hex2bin(msg1)[32:]
# 131072 is 2^17, since CPR lat and lon are 17 bits each.
cprlat_even = common.bin2int(mb0[22:39]) / 131072.0
cprlon_even = common.bin2int(mb0[39:56]) / 131072.0
cprlat_odd = common.bin2int(mb1[22:39]) / 131072.0
cprlon_odd = common.bin2int(mb1[39:56]) / 131072.0
air_d_lat_even = 360.0 / 60
air_d_lat_odd = 360.0 / 59
# compute latitude index 'j'
j = common.floor(59 * cprlat_even - 60 * cprlat_odd + 0.5)
lat_even = float(air_d_lat_even * (j % 60 + cprlat_even))
lat_odd = float(air_d_lat_odd * (j % 59 + cprlat_odd))
if lat_even >= 270:
lat_even = lat_even - 360
if lat_odd >= 270:
lat_odd = lat_odd - 360
# check if both are in the same latidude zone, exit if not
if common.cprNL(lat_even) != common.cprNL(lat_odd):
return None
# compute ni, longitude index m, and longitude
if (t0 > t1):
lat = lat_even
nl = common.cprNL(lat)
ni = max(common.cprNL(lat)- 0, 1)
m = common.floor(cprlon_even * (nl-1) - cprlon_odd * nl + 0.5)
lon = (360.0 / ni) * (m % ni + cprlon_even)
else:
lat = lat_odd
nl = common.cprNL(lat)
ni = max(common.cprNL(lat) - 1, 1)
m = common.floor(cprlon_even * (nl-1) - cprlon_odd * nl + 0.5)
lon = (360.0 / ni) * (m % ni + cprlon_odd)
if lon > 180:
lon = lon - 360
return round(lat, 5), round(lon, 5) | python | def airborne_position(msg0, msg1, t0, t1):
mb0 = common.hex2bin(msg0)[32:]
mb1 = common.hex2bin(msg1)[32:]
# 131072 is 2^17, since CPR lat and lon are 17 bits each.
cprlat_even = common.bin2int(mb0[22:39]) / 131072.0
cprlon_even = common.bin2int(mb0[39:56]) / 131072.0
cprlat_odd = common.bin2int(mb1[22:39]) / 131072.0
cprlon_odd = common.bin2int(mb1[39:56]) / 131072.0
air_d_lat_even = 360.0 / 60
air_d_lat_odd = 360.0 / 59
# compute latitude index 'j'
j = common.floor(59 * cprlat_even - 60 * cprlat_odd + 0.5)
lat_even = float(air_d_lat_even * (j % 60 + cprlat_even))
lat_odd = float(air_d_lat_odd * (j % 59 + cprlat_odd))
if lat_even >= 270:
lat_even = lat_even - 360
if lat_odd >= 270:
lat_odd = lat_odd - 360
# check if both are in the same latidude zone, exit if not
if common.cprNL(lat_even) != common.cprNL(lat_odd):
return None
# compute ni, longitude index m, and longitude
if (t0 > t1):
lat = lat_even
nl = common.cprNL(lat)
ni = max(common.cprNL(lat)- 0, 1)
m = common.floor(cprlon_even * (nl-1) - cprlon_odd * nl + 0.5)
lon = (360.0 / ni) * (m % ni + cprlon_even)
else:
lat = lat_odd
nl = common.cprNL(lat)
ni = max(common.cprNL(lat) - 1, 1)
m = common.floor(cprlon_even * (nl-1) - cprlon_odd * nl + 0.5)
lon = (360.0 / ni) * (m % ni + cprlon_odd)
if lon > 180:
lon = lon - 360
return round(lat, 5), round(lon, 5) | [
"def",
"airborne_position",
"(",
"msg0",
",",
"msg1",
",",
"t0",
",",
"t1",
")",
":",
"mb0",
"=",
"common",
".",
"hex2bin",
"(",
"msg0",
")",
"[",
"32",
":",
"]",
"mb1",
"=",
"common",
".",
"hex2bin",
"(",
"msg1",
")",
"[",
"32",
":",
"]",
"# 131072 is 2^17, since CPR lat and lon are 17 bits each.",
"cprlat_even",
"=",
"common",
".",
"bin2int",
"(",
"mb0",
"[",
"22",
":",
"39",
"]",
")",
"/",
"131072.0",
"cprlon_even",
"=",
"common",
".",
"bin2int",
"(",
"mb0",
"[",
"39",
":",
"56",
"]",
")",
"/",
"131072.0",
"cprlat_odd",
"=",
"common",
".",
"bin2int",
"(",
"mb1",
"[",
"22",
":",
"39",
"]",
")",
"/",
"131072.0",
"cprlon_odd",
"=",
"common",
".",
"bin2int",
"(",
"mb1",
"[",
"39",
":",
"56",
"]",
")",
"/",
"131072.0",
"air_d_lat_even",
"=",
"360.0",
"/",
"60",
"air_d_lat_odd",
"=",
"360.0",
"/",
"59",
"# compute latitude index 'j'",
"j",
"=",
"common",
".",
"floor",
"(",
"59",
"*",
"cprlat_even",
"-",
"60",
"*",
"cprlat_odd",
"+",
"0.5",
")",
"lat_even",
"=",
"float",
"(",
"air_d_lat_even",
"*",
"(",
"j",
"%",
"60",
"+",
"cprlat_even",
")",
")",
"lat_odd",
"=",
"float",
"(",
"air_d_lat_odd",
"*",
"(",
"j",
"%",
"59",
"+",
"cprlat_odd",
")",
")",
"if",
"lat_even",
">=",
"270",
":",
"lat_even",
"=",
"lat_even",
"-",
"360",
"if",
"lat_odd",
">=",
"270",
":",
"lat_odd",
"=",
"lat_odd",
"-",
"360",
"# check if both are in the same latidude zone, exit if not",
"if",
"common",
".",
"cprNL",
"(",
"lat_even",
")",
"!=",
"common",
".",
"cprNL",
"(",
"lat_odd",
")",
":",
"return",
"None",
"# compute ni, longitude index m, and longitude",
"if",
"(",
"t0",
">",
"t1",
")",
":",
"lat",
"=",
"lat_even",
"nl",
"=",
"common",
".",
"cprNL",
"(",
"lat",
")",
"ni",
"=",
"max",
"(",
"common",
".",
"cprNL",
"(",
"lat",
")",
"-",
"0",
",",
"1",
")",
"m",
"=",
"common",
".",
"floor",
"(",
"cprlon_even",
"*",
"(",
"nl",
"-",
"1",
")",
"-",
"cprlon_odd",
"*",
"nl",
"+",
"0.5",
")",
"lon",
"=",
"(",
"360.0",
"/",
"ni",
")",
"*",
"(",
"m",
"%",
"ni",
"+",
"cprlon_even",
")",
"else",
":",
"lat",
"=",
"lat_odd",
"nl",
"=",
"common",
".",
"cprNL",
"(",
"lat",
")",
"ni",
"=",
"max",
"(",
"common",
".",
"cprNL",
"(",
"lat",
")",
"-",
"1",
",",
"1",
")",
"m",
"=",
"common",
".",
"floor",
"(",
"cprlon_even",
"*",
"(",
"nl",
"-",
"1",
")",
"-",
"cprlon_odd",
"*",
"nl",
"+",
"0.5",
")",
"lon",
"=",
"(",
"360.0",
"/",
"ni",
")",
"*",
"(",
"m",
"%",
"ni",
"+",
"cprlon_odd",
")",
"if",
"lon",
">",
"180",
":",
"lon",
"=",
"lon",
"-",
"360",
"return",
"round",
"(",
"lat",
",",
"5",
")",
",",
"round",
"(",
"lon",
",",
"5",
")"
] | Decode airborn position from a pair of even and odd position message
Args:
msg0 (string): even message (28 bytes hexadecimal string)
msg1 (string): odd message (28 bytes hexadecimal string)
t0 (int): timestamps for the even message
t1 (int): timestamps for the odd message
Returns:
(float, float): (latitude, longitude) of the aircraft | [
"Decode",
"airborn",
"position",
"from",
"a",
"pair",
"of",
"even",
"and",
"odd",
"position",
"message"
] | 8cd5655a04b08171a9ad5f1ffd232b7e0178ea53 | https://github.com/junzis/pyModeS/blob/8cd5655a04b08171a9ad5f1ffd232b7e0178ea53/pyModeS/decoder/bds/bds05.py#L27-L85 |
248,354 | junzis/pyModeS | pyModeS/decoder/bds/bds05.py | airborne_position_with_ref | def airborne_position_with_ref(msg, lat_ref, lon_ref):
"""Decode airborne position with only one message,
knowing reference nearby location, such as previously calculated location,
ground station, or airport location, etc. The reference position shall
be with in 180NM of the true position.
Args:
msg (string): even message (28 bytes hexadecimal string)
lat_ref: previous known latitude
lon_ref: previous known longitude
Returns:
(float, float): (latitude, longitude) of the aircraft
"""
mb = common.hex2bin(msg)[32:]
cprlat = common.bin2int(mb[22:39]) / 131072.0
cprlon = common.bin2int(mb[39:56]) / 131072.0
i = int(mb[21])
d_lat = 360.0/59 if i else 360.0/60
j = common.floor(lat_ref / d_lat) \
+ common.floor(0.5 + ((lat_ref % d_lat) / d_lat) - cprlat)
lat = d_lat * (j + cprlat)
ni = common.cprNL(lat) - i
if ni > 0:
d_lon = 360.0 / ni
else:
d_lon = 360.0
m = common.floor(lon_ref / d_lon) \
+ common.floor(0.5 + ((lon_ref % d_lon) / d_lon) - cprlon)
lon = d_lon * (m + cprlon)
return round(lat, 5), round(lon, 5) | python | def airborne_position_with_ref(msg, lat_ref, lon_ref):
mb = common.hex2bin(msg)[32:]
cprlat = common.bin2int(mb[22:39]) / 131072.0
cprlon = common.bin2int(mb[39:56]) / 131072.0
i = int(mb[21])
d_lat = 360.0/59 if i else 360.0/60
j = common.floor(lat_ref / d_lat) \
+ common.floor(0.5 + ((lat_ref % d_lat) / d_lat) - cprlat)
lat = d_lat * (j + cprlat)
ni = common.cprNL(lat) - i
if ni > 0:
d_lon = 360.0 / ni
else:
d_lon = 360.0
m = common.floor(lon_ref / d_lon) \
+ common.floor(0.5 + ((lon_ref % d_lon) / d_lon) - cprlon)
lon = d_lon * (m + cprlon)
return round(lat, 5), round(lon, 5) | [
"def",
"airborne_position_with_ref",
"(",
"msg",
",",
"lat_ref",
",",
"lon_ref",
")",
":",
"mb",
"=",
"common",
".",
"hex2bin",
"(",
"msg",
")",
"[",
"32",
":",
"]",
"cprlat",
"=",
"common",
".",
"bin2int",
"(",
"mb",
"[",
"22",
":",
"39",
"]",
")",
"/",
"131072.0",
"cprlon",
"=",
"common",
".",
"bin2int",
"(",
"mb",
"[",
"39",
":",
"56",
"]",
")",
"/",
"131072.0",
"i",
"=",
"int",
"(",
"mb",
"[",
"21",
"]",
")",
"d_lat",
"=",
"360.0",
"/",
"59",
"if",
"i",
"else",
"360.0",
"/",
"60",
"j",
"=",
"common",
".",
"floor",
"(",
"lat_ref",
"/",
"d_lat",
")",
"+",
"common",
".",
"floor",
"(",
"0.5",
"+",
"(",
"(",
"lat_ref",
"%",
"d_lat",
")",
"/",
"d_lat",
")",
"-",
"cprlat",
")",
"lat",
"=",
"d_lat",
"*",
"(",
"j",
"+",
"cprlat",
")",
"ni",
"=",
"common",
".",
"cprNL",
"(",
"lat",
")",
"-",
"i",
"if",
"ni",
">",
"0",
":",
"d_lon",
"=",
"360.0",
"/",
"ni",
"else",
":",
"d_lon",
"=",
"360.0",
"m",
"=",
"common",
".",
"floor",
"(",
"lon_ref",
"/",
"d_lon",
")",
"+",
"common",
".",
"floor",
"(",
"0.5",
"+",
"(",
"(",
"lon_ref",
"%",
"d_lon",
")",
"/",
"d_lon",
")",
"-",
"cprlon",
")",
"lon",
"=",
"d_lon",
"*",
"(",
"m",
"+",
"cprlon",
")",
"return",
"round",
"(",
"lat",
",",
"5",
")",
",",
"round",
"(",
"lon",
",",
"5",
")"
] | Decode airborne position with only one message,
knowing reference nearby location, such as previously calculated location,
ground station, or airport location, etc. The reference position shall
be with in 180NM of the true position.
Args:
msg (string): even message (28 bytes hexadecimal string)
lat_ref: previous known latitude
lon_ref: previous known longitude
Returns:
(float, float): (latitude, longitude) of the aircraft | [
"Decode",
"airborne",
"position",
"with",
"only",
"one",
"message",
"knowing",
"reference",
"nearby",
"location",
"such",
"as",
"previously",
"calculated",
"location",
"ground",
"station",
"or",
"airport",
"location",
"etc",
".",
"The",
"reference",
"position",
"shall",
"be",
"with",
"in",
"180NM",
"of",
"the",
"true",
"position",
"."
] | 8cd5655a04b08171a9ad5f1ffd232b7e0178ea53 | https://github.com/junzis/pyModeS/blob/8cd5655a04b08171a9ad5f1ffd232b7e0178ea53/pyModeS/decoder/bds/bds05.py#L88-L129 |
248,355 | junzis/pyModeS | pyModeS/decoder/common.py | hex2bin | def hex2bin(hexstr):
"""Convert a hexdecimal string to binary string, with zero fillings. """
num_of_bits = len(hexstr) * 4
binstr = bin(int(hexstr, 16))[2:].zfill(int(num_of_bits))
return binstr | python | def hex2bin(hexstr):
num_of_bits = len(hexstr) * 4
binstr = bin(int(hexstr, 16))[2:].zfill(int(num_of_bits))
return binstr | [
"def",
"hex2bin",
"(",
"hexstr",
")",
":",
"num_of_bits",
"=",
"len",
"(",
"hexstr",
")",
"*",
"4",
"binstr",
"=",
"bin",
"(",
"int",
"(",
"hexstr",
",",
"16",
")",
")",
"[",
"2",
":",
"]",
".",
"zfill",
"(",
"int",
"(",
"num_of_bits",
")",
")",
"return",
"binstr"
] | Convert a hexdecimal string to binary string, with zero fillings. | [
"Convert",
"a",
"hexdecimal",
"string",
"to",
"binary",
"string",
"with",
"zero",
"fillings",
"."
] | 8cd5655a04b08171a9ad5f1ffd232b7e0178ea53 | https://github.com/junzis/pyModeS/blob/8cd5655a04b08171a9ad5f1ffd232b7e0178ea53/pyModeS/decoder/common.py#L4-L8 |
248,356 | junzis/pyModeS | pyModeS/decoder/common.py | icao | def icao(msg):
"""Calculate the ICAO address from an Mode-S message
with DF4, DF5, DF20, DF21
Args:
msg (String): 28 bytes hexadecimal message string
Returns:
String: ICAO address in 6 bytes hexadecimal string
"""
DF = df(msg)
if DF in (11, 17, 18):
addr = msg[2:8]
elif DF in (0, 4, 5, 16, 20, 21):
c0 = bin2int(crc(msg, encode=True))
c1 = hex2int(msg[-6:])
addr = '%06X' % (c0 ^ c1)
else:
addr = None
return addr | python | def icao(msg):
DF = df(msg)
if DF in (11, 17, 18):
addr = msg[2:8]
elif DF in (0, 4, 5, 16, 20, 21):
c0 = bin2int(crc(msg, encode=True))
c1 = hex2int(msg[-6:])
addr = '%06X' % (c0 ^ c1)
else:
addr = None
return addr | [
"def",
"icao",
"(",
"msg",
")",
":",
"DF",
"=",
"df",
"(",
"msg",
")",
"if",
"DF",
"in",
"(",
"11",
",",
"17",
",",
"18",
")",
":",
"addr",
"=",
"msg",
"[",
"2",
":",
"8",
"]",
"elif",
"DF",
"in",
"(",
"0",
",",
"4",
",",
"5",
",",
"16",
",",
"20",
",",
"21",
")",
":",
"c0",
"=",
"bin2int",
"(",
"crc",
"(",
"msg",
",",
"encode",
"=",
"True",
")",
")",
"c1",
"=",
"hex2int",
"(",
"msg",
"[",
"-",
"6",
":",
"]",
")",
"addr",
"=",
"'%06X'",
"%",
"(",
"c0",
"^",
"c1",
")",
"else",
":",
"addr",
"=",
"None",
"return",
"addr"
] | Calculate the ICAO address from an Mode-S message
with DF4, DF5, DF20, DF21
Args:
msg (String): 28 bytes hexadecimal message string
Returns:
String: ICAO address in 6 bytes hexadecimal string | [
"Calculate",
"the",
"ICAO",
"address",
"from",
"an",
"Mode",
"-",
"S",
"message",
"with",
"DF4",
"DF5",
"DF20",
"DF21"
] | 8cd5655a04b08171a9ad5f1ffd232b7e0178ea53 | https://github.com/junzis/pyModeS/blob/8cd5655a04b08171a9ad5f1ffd232b7e0178ea53/pyModeS/decoder/common.py#L79-L101 |
248,357 | junzis/pyModeS | pyModeS/decoder/common.py | gray2int | def gray2int(graystr):
"""Convert greycode to binary"""
num = bin2int(graystr)
num ^= (num >> 8)
num ^= (num >> 4)
num ^= (num >> 2)
num ^= (num >> 1)
return num | python | def gray2int(graystr):
num = bin2int(graystr)
num ^= (num >> 8)
num ^= (num >> 4)
num ^= (num >> 2)
num ^= (num >> 1)
return num | [
"def",
"gray2int",
"(",
"graystr",
")",
":",
"num",
"=",
"bin2int",
"(",
"graystr",
")",
"num",
"^=",
"(",
"num",
">>",
"8",
")",
"num",
"^=",
"(",
"num",
">>",
"4",
")",
"num",
"^=",
"(",
"num",
">>",
"2",
")",
"num",
"^=",
"(",
"num",
">>",
"1",
")",
"return",
"num"
] | Convert greycode to binary | [
"Convert",
"greycode",
"to",
"binary"
] | 8cd5655a04b08171a9ad5f1ffd232b7e0178ea53 | https://github.com/junzis/pyModeS/blob/8cd5655a04b08171a9ad5f1ffd232b7e0178ea53/pyModeS/decoder/common.py#L268-L275 |
248,358 | junzis/pyModeS | pyModeS/decoder/common.py | allzeros | def allzeros(msg):
"""check if the data bits are all zeros
Args:
msg (String): 28 bytes hexadecimal message string
Returns:
bool: True or False
"""
d = hex2bin(data(msg))
if bin2int(d) > 0:
return False
else:
return True | python | def allzeros(msg):
d = hex2bin(data(msg))
if bin2int(d) > 0:
return False
else:
return True | [
"def",
"allzeros",
"(",
"msg",
")",
":",
"d",
"=",
"hex2bin",
"(",
"data",
"(",
"msg",
")",
")",
"if",
"bin2int",
"(",
"d",
")",
">",
"0",
":",
"return",
"False",
"else",
":",
"return",
"True"
] | check if the data bits are all zeros
Args:
msg (String): 28 bytes hexadecimal message string
Returns:
bool: True or False | [
"check",
"if",
"the",
"data",
"bits",
"are",
"all",
"zeros"
] | 8cd5655a04b08171a9ad5f1ffd232b7e0178ea53 | https://github.com/junzis/pyModeS/blob/8cd5655a04b08171a9ad5f1ffd232b7e0178ea53/pyModeS/decoder/common.py#L283-L297 |
248,359 | junzis/pyModeS | pyModeS/decoder/common.py | wrongstatus | def wrongstatus(data, sb, msb, lsb):
"""Check if the status bit and field bits are consistency. This Function
is used for checking BDS code versions.
"""
# status bit, most significant bit, least significant bit
status = int(data[sb-1])
value = bin2int(data[msb-1:lsb])
if not status:
if value != 0:
return True
return False | python | def wrongstatus(data, sb, msb, lsb):
# status bit, most significant bit, least significant bit
status = int(data[sb-1])
value = bin2int(data[msb-1:lsb])
if not status:
if value != 0:
return True
return False | [
"def",
"wrongstatus",
"(",
"data",
",",
"sb",
",",
"msb",
",",
"lsb",
")",
":",
"# status bit, most significant bit, least significant bit",
"status",
"=",
"int",
"(",
"data",
"[",
"sb",
"-",
"1",
"]",
")",
"value",
"=",
"bin2int",
"(",
"data",
"[",
"msb",
"-",
"1",
":",
"lsb",
"]",
")",
"if",
"not",
"status",
":",
"if",
"value",
"!=",
"0",
":",
"return",
"True",
"return",
"False"
] | Check if the status bit and field bits are consistency. This Function
is used for checking BDS code versions. | [
"Check",
"if",
"the",
"status",
"bit",
"and",
"field",
"bits",
"are",
"consistency",
".",
"This",
"Function",
"is",
"used",
"for",
"checking",
"BDS",
"code",
"versions",
"."
] | 8cd5655a04b08171a9ad5f1ffd232b7e0178ea53 | https://github.com/junzis/pyModeS/blob/8cd5655a04b08171a9ad5f1ffd232b7e0178ea53/pyModeS/decoder/common.py#L300-L313 |
248,360 | junzis/pyModeS | pyModeS/decoder/adsb.py | version | def version(msg):
"""ADS-B Version
Args:
msg (string): 28 bytes hexadecimal message string, TC = 31
Returns:
int: version number
"""
tc = typecode(msg)
if tc != 31:
raise RuntimeError("%s: Not a status operation message, expecting TC = 31" % msg)
msgbin = common.hex2bin(msg)
version = common.bin2int(msgbin[72:75])
return version | python | def version(msg):
tc = typecode(msg)
if tc != 31:
raise RuntimeError("%s: Not a status operation message, expecting TC = 31" % msg)
msgbin = common.hex2bin(msg)
version = common.bin2int(msgbin[72:75])
return version | [
"def",
"version",
"(",
"msg",
")",
":",
"tc",
"=",
"typecode",
"(",
"msg",
")",
"if",
"tc",
"!=",
"31",
":",
"raise",
"RuntimeError",
"(",
"\"%s: Not a status operation message, expecting TC = 31\"",
"%",
"msg",
")",
"msgbin",
"=",
"common",
".",
"hex2bin",
"(",
"msg",
")",
"version",
"=",
"common",
".",
"bin2int",
"(",
"msgbin",
"[",
"72",
":",
"75",
"]",
")",
"return",
"version"
] | ADS-B Version
Args:
msg (string): 28 bytes hexadecimal message string, TC = 31
Returns:
int: version number | [
"ADS",
"-",
"B",
"Version"
] | 8cd5655a04b08171a9ad5f1ffd232b7e0178ea53 | https://github.com/junzis/pyModeS/blob/8cd5655a04b08171a9ad5f1ffd232b7e0178ea53/pyModeS/decoder/adsb.py#L194-L211 |
248,361 | junzis/pyModeS | pyModeS/decoder/adsb.py | nic_v1 | def nic_v1(msg, NICs):
"""Calculate NIC, navigation integrity category, for ADS-B version 1
Args:
msg (string): 28 bytes hexadecimal message string
NICs (int or string): NIC supplement
Returns:
int or string: Horizontal Radius of Containment
int or string: Vertical Protection Limit
"""
if typecode(msg) < 5 or typecode(msg) > 22:
raise RuntimeError(
"%s: Not a surface position message (5<TC<8), \
airborne position message (8<TC<19), \
or airborne position with GNSS height (20<TC<22)" % msg
)
tc = typecode(msg)
NIC = uncertainty.TC_NICv1_lookup[tc]
if isinstance(NIC, dict):
NIC = NIC[NICs]
try:
Rc = uncertainty.NICv1[NIC][NICs]['Rc']
VPL = uncertainty.NICv1[NIC][NICs]['VPL']
except KeyError:
Rc, VPL = uncertainty.NA, uncertainty.NA
return Rc, VPL | python | def nic_v1(msg, NICs):
if typecode(msg) < 5 or typecode(msg) > 22:
raise RuntimeError(
"%s: Not a surface position message (5<TC<8), \
airborne position message (8<TC<19), \
or airborne position with GNSS height (20<TC<22)" % msg
)
tc = typecode(msg)
NIC = uncertainty.TC_NICv1_lookup[tc]
if isinstance(NIC, dict):
NIC = NIC[NICs]
try:
Rc = uncertainty.NICv1[NIC][NICs]['Rc']
VPL = uncertainty.NICv1[NIC][NICs]['VPL']
except KeyError:
Rc, VPL = uncertainty.NA, uncertainty.NA
return Rc, VPL | [
"def",
"nic_v1",
"(",
"msg",
",",
"NICs",
")",
":",
"if",
"typecode",
"(",
"msg",
")",
"<",
"5",
"or",
"typecode",
"(",
"msg",
")",
">",
"22",
":",
"raise",
"RuntimeError",
"(",
"\"%s: Not a surface position message (5<TC<8), \\\n airborne position message (8<TC<19), \\\n or airborne position with GNSS height (20<TC<22)\"",
"%",
"msg",
")",
"tc",
"=",
"typecode",
"(",
"msg",
")",
"NIC",
"=",
"uncertainty",
".",
"TC_NICv1_lookup",
"[",
"tc",
"]",
"if",
"isinstance",
"(",
"NIC",
",",
"dict",
")",
":",
"NIC",
"=",
"NIC",
"[",
"NICs",
"]",
"try",
":",
"Rc",
"=",
"uncertainty",
".",
"NICv1",
"[",
"NIC",
"]",
"[",
"NICs",
"]",
"[",
"'Rc'",
"]",
"VPL",
"=",
"uncertainty",
".",
"NICv1",
"[",
"NIC",
"]",
"[",
"NICs",
"]",
"[",
"'VPL'",
"]",
"except",
"KeyError",
":",
"Rc",
",",
"VPL",
"=",
"uncertainty",
".",
"NA",
",",
"uncertainty",
".",
"NA",
"return",
"Rc",
",",
"VPL"
] | Calculate NIC, navigation integrity category, for ADS-B version 1
Args:
msg (string): 28 bytes hexadecimal message string
NICs (int or string): NIC supplement
Returns:
int or string: Horizontal Radius of Containment
int or string: Vertical Protection Limit | [
"Calculate",
"NIC",
"navigation",
"integrity",
"category",
"for",
"ADS",
"-",
"B",
"version",
"1"
] | 8cd5655a04b08171a9ad5f1ffd232b7e0178ea53 | https://github.com/junzis/pyModeS/blob/8cd5655a04b08171a9ad5f1ffd232b7e0178ea53/pyModeS/decoder/adsb.py#L278-L308 |
248,362 | junzis/pyModeS | pyModeS/decoder/adsb.py | nic_v2 | def nic_v2(msg, NICa, NICbc):
"""Calculate NIC, navigation integrity category, for ADS-B version 2
Args:
msg (string): 28 bytes hexadecimal message string
NICa (int or string): NIC supplement - A
NICbc (int or srting): NIC supplement - B or C
Returns:
int or string: Horizontal Radius of Containment
"""
if typecode(msg) < 5 or typecode(msg) > 22:
raise RuntimeError(
"%s: Not a surface position message (5<TC<8), \
airborne position message (8<TC<19), \
or airborne position with GNSS height (20<TC<22)" % msg
)
tc = typecode(msg)
NIC = uncertainty.TC_NICv2_lookup[tc]
if 20<=tc<=22:
NICs = 0
else:
NICs = NICa*2 + NICbc
try:
if isinstance(NIC, dict):
NIC = NIC[NICs]
Rc = uncertainty.NICv2[NIC][NICs]['Rc']
except KeyError:
Rc = uncertainty.NA
return Rc | python | def nic_v2(msg, NICa, NICbc):
if typecode(msg) < 5 or typecode(msg) > 22:
raise RuntimeError(
"%s: Not a surface position message (5<TC<8), \
airborne position message (8<TC<19), \
or airborne position with GNSS height (20<TC<22)" % msg
)
tc = typecode(msg)
NIC = uncertainty.TC_NICv2_lookup[tc]
if 20<=tc<=22:
NICs = 0
else:
NICs = NICa*2 + NICbc
try:
if isinstance(NIC, dict):
NIC = NIC[NICs]
Rc = uncertainty.NICv2[NIC][NICs]['Rc']
except KeyError:
Rc = uncertainty.NA
return Rc | [
"def",
"nic_v2",
"(",
"msg",
",",
"NICa",
",",
"NICbc",
")",
":",
"if",
"typecode",
"(",
"msg",
")",
"<",
"5",
"or",
"typecode",
"(",
"msg",
")",
">",
"22",
":",
"raise",
"RuntimeError",
"(",
"\"%s: Not a surface position message (5<TC<8), \\\n airborne position message (8<TC<19), \\\n or airborne position with GNSS height (20<TC<22)\"",
"%",
"msg",
")",
"tc",
"=",
"typecode",
"(",
"msg",
")",
"NIC",
"=",
"uncertainty",
".",
"TC_NICv2_lookup",
"[",
"tc",
"]",
"if",
"20",
"<=",
"tc",
"<=",
"22",
":",
"NICs",
"=",
"0",
"else",
":",
"NICs",
"=",
"NICa",
"*",
"2",
"+",
"NICbc",
"try",
":",
"if",
"isinstance",
"(",
"NIC",
",",
"dict",
")",
":",
"NIC",
"=",
"NIC",
"[",
"NICs",
"]",
"Rc",
"=",
"uncertainty",
".",
"NICv2",
"[",
"NIC",
"]",
"[",
"NICs",
"]",
"[",
"'Rc'",
"]",
"except",
"KeyError",
":",
"Rc",
"=",
"uncertainty",
".",
"NA",
"return",
"Rc"
] | Calculate NIC, navigation integrity category, for ADS-B version 2
Args:
msg (string): 28 bytes hexadecimal message string
NICa (int or string): NIC supplement - A
NICbc (int or srting): NIC supplement - B or C
Returns:
int or string: Horizontal Radius of Containment | [
"Calculate",
"NIC",
"navigation",
"integrity",
"category",
"for",
"ADS",
"-",
"B",
"version",
"2"
] | 8cd5655a04b08171a9ad5f1ffd232b7e0178ea53 | https://github.com/junzis/pyModeS/blob/8cd5655a04b08171a9ad5f1ffd232b7e0178ea53/pyModeS/decoder/adsb.py#L311-L345 |
248,363 | junzis/pyModeS | pyModeS/decoder/adsb.py | nic_s | def nic_s(msg):
"""Obtain NIC supplement bit, TC=31 message
Args:
msg (string): 28 bytes hexadecimal message string
Returns:
int: NICs number (0 or 1)
"""
tc = typecode(msg)
if tc != 31:
raise RuntimeError("%s: Not a status operation message, expecting TC = 31" % msg)
msgbin = common.hex2bin(msg)
nic_s = int(msgbin[75])
return nic_s | python | def nic_s(msg):
tc = typecode(msg)
if tc != 31:
raise RuntimeError("%s: Not a status operation message, expecting TC = 31" % msg)
msgbin = common.hex2bin(msg)
nic_s = int(msgbin[75])
return nic_s | [
"def",
"nic_s",
"(",
"msg",
")",
":",
"tc",
"=",
"typecode",
"(",
"msg",
")",
"if",
"tc",
"!=",
"31",
":",
"raise",
"RuntimeError",
"(",
"\"%s: Not a status operation message, expecting TC = 31\"",
"%",
"msg",
")",
"msgbin",
"=",
"common",
".",
"hex2bin",
"(",
"msg",
")",
"nic_s",
"=",
"int",
"(",
"msgbin",
"[",
"75",
"]",
")",
"return",
"nic_s"
] | Obtain NIC supplement bit, TC=31 message
Args:
msg (string): 28 bytes hexadecimal message string
Returns:
int: NICs number (0 or 1) | [
"Obtain",
"NIC",
"supplement",
"bit",
"TC",
"=",
"31",
"message"
] | 8cd5655a04b08171a9ad5f1ffd232b7e0178ea53 | https://github.com/junzis/pyModeS/blob/8cd5655a04b08171a9ad5f1ffd232b7e0178ea53/pyModeS/decoder/adsb.py#L348-L365 |
248,364 | junzis/pyModeS | pyModeS/decoder/adsb.py | nic_b | def nic_b(msg):
"""Obtain NICb, navigation integrity category supplement-b
Args:
msg (string): 28 bytes hexadecimal message string
Returns:
int: NICb number (0 or 1)
"""
tc = typecode(msg)
if tc < 9 or tc > 18:
raise RuntimeError("%s: Not a airborne position message, expecting 8<TC<19" % msg)
msgbin = common.hex2bin(msg)
nic_b = int(msgbin[39])
return nic_b | python | def nic_b(msg):
tc = typecode(msg)
if tc < 9 or tc > 18:
raise RuntimeError("%s: Not a airborne position message, expecting 8<TC<19" % msg)
msgbin = common.hex2bin(msg)
nic_b = int(msgbin[39])
return nic_b | [
"def",
"nic_b",
"(",
"msg",
")",
":",
"tc",
"=",
"typecode",
"(",
"msg",
")",
"if",
"tc",
"<",
"9",
"or",
"tc",
">",
"18",
":",
"raise",
"RuntimeError",
"(",
"\"%s: Not a airborne position message, expecting 8<TC<19\"",
"%",
"msg",
")",
"msgbin",
"=",
"common",
".",
"hex2bin",
"(",
"msg",
")",
"nic_b",
"=",
"int",
"(",
"msgbin",
"[",
"39",
"]",
")",
"return",
"nic_b"
] | Obtain NICb, navigation integrity category supplement-b
Args:
msg (string): 28 bytes hexadecimal message string
Returns:
int: NICb number (0 or 1) | [
"Obtain",
"NICb",
"navigation",
"integrity",
"category",
"supplement",
"-",
"b"
] | 8cd5655a04b08171a9ad5f1ffd232b7e0178ea53 | https://github.com/junzis/pyModeS/blob/8cd5655a04b08171a9ad5f1ffd232b7e0178ea53/pyModeS/decoder/adsb.py#L389-L406 |
248,365 | junzis/pyModeS | pyModeS/decoder/adsb.py | nac_p | def nac_p(msg):
"""Calculate NACp, Navigation Accuracy Category - Position
Args:
msg (string): 28 bytes hexadecimal message string, TC = 29 or 31
Returns:
int or string: 95% horizontal accuracy bounds, Estimated Position Uncertainty
int or string: 95% vertical accuracy bounds, Vertical Estimated Position Uncertainty
"""
tc = typecode(msg)
if tc not in [29, 31]:
raise RuntimeError("%s: Not a target state and status message, \
or operation status message, expecting TC = 29 or 31" % msg)
msgbin = common.hex2bin(msg)
if tc == 29:
NACp = common.bin2int(msgbin[71:75])
elif tc == 31:
NACp = common.bin2int(msgbin[76:80])
try:
EPU = uncertainty.NACp[NACp]['EPU']
VEPU = uncertainty.NACp[NACp]['VEPU']
except KeyError:
EPU, VEPU = uncertainty.NA, uncertainty.NA
return EPU, VEPU | python | def nac_p(msg):
tc = typecode(msg)
if tc not in [29, 31]:
raise RuntimeError("%s: Not a target state and status message, \
or operation status message, expecting TC = 29 or 31" % msg)
msgbin = common.hex2bin(msg)
if tc == 29:
NACp = common.bin2int(msgbin[71:75])
elif tc == 31:
NACp = common.bin2int(msgbin[76:80])
try:
EPU = uncertainty.NACp[NACp]['EPU']
VEPU = uncertainty.NACp[NACp]['VEPU']
except KeyError:
EPU, VEPU = uncertainty.NA, uncertainty.NA
return EPU, VEPU | [
"def",
"nac_p",
"(",
"msg",
")",
":",
"tc",
"=",
"typecode",
"(",
"msg",
")",
"if",
"tc",
"not",
"in",
"[",
"29",
",",
"31",
"]",
":",
"raise",
"RuntimeError",
"(",
"\"%s: Not a target state and status message, \\\n or operation status message, expecting TC = 29 or 31\"",
"%",
"msg",
")",
"msgbin",
"=",
"common",
".",
"hex2bin",
"(",
"msg",
")",
"if",
"tc",
"==",
"29",
":",
"NACp",
"=",
"common",
".",
"bin2int",
"(",
"msgbin",
"[",
"71",
":",
"75",
"]",
")",
"elif",
"tc",
"==",
"31",
":",
"NACp",
"=",
"common",
".",
"bin2int",
"(",
"msgbin",
"[",
"76",
":",
"80",
"]",
")",
"try",
":",
"EPU",
"=",
"uncertainty",
".",
"NACp",
"[",
"NACp",
"]",
"[",
"'EPU'",
"]",
"VEPU",
"=",
"uncertainty",
".",
"NACp",
"[",
"NACp",
"]",
"[",
"'VEPU'",
"]",
"except",
"KeyError",
":",
"EPU",
",",
"VEPU",
"=",
"uncertainty",
".",
"NA",
",",
"uncertainty",
".",
"NA",
"return",
"EPU",
",",
"VEPU"
] | Calculate NACp, Navigation Accuracy Category - Position
Args:
msg (string): 28 bytes hexadecimal message string, TC = 29 or 31
Returns:
int or string: 95% horizontal accuracy bounds, Estimated Position Uncertainty
int or string: 95% vertical accuracy bounds, Vertical Estimated Position Uncertainty | [
"Calculate",
"NACp",
"Navigation",
"Accuracy",
"Category",
"-",
"Position"
] | 8cd5655a04b08171a9ad5f1ffd232b7e0178ea53 | https://github.com/junzis/pyModeS/blob/8cd5655a04b08171a9ad5f1ffd232b7e0178ea53/pyModeS/decoder/adsb.py#L409-L438 |
248,366 | junzis/pyModeS | pyModeS/decoder/adsb.py | nac_v | def nac_v(msg):
"""Calculate NACv, Navigation Accuracy Category - Velocity
Args:
msg (string): 28 bytes hexadecimal message string, TC = 19
Returns:
int or string: 95% horizontal accuracy bounds for velocity, Horizontal Figure of Merit
int or string: 95% vertical accuracy bounds for velocity, Vertical Figure of Merit
"""
tc = typecode(msg)
if tc != 19:
raise RuntimeError("%s: Not an airborne velocity message, expecting TC = 19" % msg)
msgbin = common.hex2bin(msg)
NACv = common.bin2int(msgbin[42:45])
try:
HFOMr = uncertainty.NACv[NACv]['HFOMr']
VFOMr = uncertainty.NACv[NACv]['VFOMr']
except KeyError:
HFOMr, VFOMr = uncertainty.NA, uncertainty.NA
return HFOMr, VFOMr | python | def nac_v(msg):
tc = typecode(msg)
if tc != 19:
raise RuntimeError("%s: Not an airborne velocity message, expecting TC = 19" % msg)
msgbin = common.hex2bin(msg)
NACv = common.bin2int(msgbin[42:45])
try:
HFOMr = uncertainty.NACv[NACv]['HFOMr']
VFOMr = uncertainty.NACv[NACv]['VFOMr']
except KeyError:
HFOMr, VFOMr = uncertainty.NA, uncertainty.NA
return HFOMr, VFOMr | [
"def",
"nac_v",
"(",
"msg",
")",
":",
"tc",
"=",
"typecode",
"(",
"msg",
")",
"if",
"tc",
"!=",
"19",
":",
"raise",
"RuntimeError",
"(",
"\"%s: Not an airborne velocity message, expecting TC = 19\"",
"%",
"msg",
")",
"msgbin",
"=",
"common",
".",
"hex2bin",
"(",
"msg",
")",
"NACv",
"=",
"common",
".",
"bin2int",
"(",
"msgbin",
"[",
"42",
":",
"45",
"]",
")",
"try",
":",
"HFOMr",
"=",
"uncertainty",
".",
"NACv",
"[",
"NACv",
"]",
"[",
"'HFOMr'",
"]",
"VFOMr",
"=",
"uncertainty",
".",
"NACv",
"[",
"NACv",
"]",
"[",
"'VFOMr'",
"]",
"except",
"KeyError",
":",
"HFOMr",
",",
"VFOMr",
"=",
"uncertainty",
".",
"NA",
",",
"uncertainty",
".",
"NA",
"return",
"HFOMr",
",",
"VFOMr"
] | Calculate NACv, Navigation Accuracy Category - Velocity
Args:
msg (string): 28 bytes hexadecimal message string, TC = 19
Returns:
int or string: 95% horizontal accuracy bounds for velocity, Horizontal Figure of Merit
int or string: 95% vertical accuracy bounds for velocity, Vertical Figure of Merit | [
"Calculate",
"NACv",
"Navigation",
"Accuracy",
"Category",
"-",
"Velocity"
] | 8cd5655a04b08171a9ad5f1ffd232b7e0178ea53 | https://github.com/junzis/pyModeS/blob/8cd5655a04b08171a9ad5f1ffd232b7e0178ea53/pyModeS/decoder/adsb.py#L441-L465 |
248,367 | junzis/pyModeS | pyModeS/decoder/adsb.py | sil | def sil(msg, version):
"""Calculate SIL, Surveillance Integrity Level
Args:
msg (string): 28 bytes hexadecimal message string with TC = 29, 31
Returns:
int or string: Probability of exceeding Horizontal Radius of Containment RCu
int or string: Probability of exceeding Vertical Integrity Containment Region VPL
string: SIL supplement based on per "hour" or "sample", or 'unknown'
"""
tc = typecode(msg)
if tc not in [29, 31]:
raise RuntimeError("%s: Not a target state and status messag, \
or operation status message, expecting TC = 29 or 31" % msg)
msgbin = common.hex2bin(msg)
if tc == 29:
SIL = common.bin2int(msgbin[76:78])
elif tc == 31:
SIL = common.bin2int(msgbin[82:84])
try:
PE_RCu = uncertainty.SIL[SIL]['PE_RCu']
PE_VPL = uncertainty.SIL[SIL]['PE_VPL']
except KeyError:
PE_RCu, PE_VPL = uncertainty.NA, uncertainty.NA
base = 'unknown'
if version == 2:
if tc == 29:
SIL_SUP = common.bin2int(msgbin[39])
elif tc == 31:
SIL_SUP = common.bin2int(msgbin[86])
if SIL_SUP == 0:
base = "hour"
elif SIL_SUP == 1:
base = "sample"
return PE_RCu, PE_VPL, base | python | def sil(msg, version):
tc = typecode(msg)
if tc not in [29, 31]:
raise RuntimeError("%s: Not a target state and status messag, \
or operation status message, expecting TC = 29 or 31" % msg)
msgbin = common.hex2bin(msg)
if tc == 29:
SIL = common.bin2int(msgbin[76:78])
elif tc == 31:
SIL = common.bin2int(msgbin[82:84])
try:
PE_RCu = uncertainty.SIL[SIL]['PE_RCu']
PE_VPL = uncertainty.SIL[SIL]['PE_VPL']
except KeyError:
PE_RCu, PE_VPL = uncertainty.NA, uncertainty.NA
base = 'unknown'
if version == 2:
if tc == 29:
SIL_SUP = common.bin2int(msgbin[39])
elif tc == 31:
SIL_SUP = common.bin2int(msgbin[86])
if SIL_SUP == 0:
base = "hour"
elif SIL_SUP == 1:
base = "sample"
return PE_RCu, PE_VPL, base | [
"def",
"sil",
"(",
"msg",
",",
"version",
")",
":",
"tc",
"=",
"typecode",
"(",
"msg",
")",
"if",
"tc",
"not",
"in",
"[",
"29",
",",
"31",
"]",
":",
"raise",
"RuntimeError",
"(",
"\"%s: Not a target state and status messag, \\\n or operation status message, expecting TC = 29 or 31\"",
"%",
"msg",
")",
"msgbin",
"=",
"common",
".",
"hex2bin",
"(",
"msg",
")",
"if",
"tc",
"==",
"29",
":",
"SIL",
"=",
"common",
".",
"bin2int",
"(",
"msgbin",
"[",
"76",
":",
"78",
"]",
")",
"elif",
"tc",
"==",
"31",
":",
"SIL",
"=",
"common",
".",
"bin2int",
"(",
"msgbin",
"[",
"82",
":",
"84",
"]",
")",
"try",
":",
"PE_RCu",
"=",
"uncertainty",
".",
"SIL",
"[",
"SIL",
"]",
"[",
"'PE_RCu'",
"]",
"PE_VPL",
"=",
"uncertainty",
".",
"SIL",
"[",
"SIL",
"]",
"[",
"'PE_VPL'",
"]",
"except",
"KeyError",
":",
"PE_RCu",
",",
"PE_VPL",
"=",
"uncertainty",
".",
"NA",
",",
"uncertainty",
".",
"NA",
"base",
"=",
"'unknown'",
"if",
"version",
"==",
"2",
":",
"if",
"tc",
"==",
"29",
":",
"SIL_SUP",
"=",
"common",
".",
"bin2int",
"(",
"msgbin",
"[",
"39",
"]",
")",
"elif",
"tc",
"==",
"31",
":",
"SIL_SUP",
"=",
"common",
".",
"bin2int",
"(",
"msgbin",
"[",
"86",
"]",
")",
"if",
"SIL_SUP",
"==",
"0",
":",
"base",
"=",
"\"hour\"",
"elif",
"SIL_SUP",
"==",
"1",
":",
"base",
"=",
"\"sample\"",
"return",
"PE_RCu",
",",
"PE_VPL",
",",
"base"
] | Calculate SIL, Surveillance Integrity Level
Args:
msg (string): 28 bytes hexadecimal message string with TC = 29, 31
Returns:
int or string: Probability of exceeding Horizontal Radius of Containment RCu
int or string: Probability of exceeding Vertical Integrity Containment Region VPL
string: SIL supplement based on per "hour" or "sample", or 'unknown' | [
"Calculate",
"SIL",
"Surveillance",
"Integrity",
"Level"
] | 8cd5655a04b08171a9ad5f1ffd232b7e0178ea53 | https://github.com/junzis/pyModeS/blob/8cd5655a04b08171a9ad5f1ffd232b7e0178ea53/pyModeS/decoder/adsb.py#L468-L511 |
248,368 | junzis/pyModeS | pyModeS/decoder/bds/bds50.py | roll50 | def roll50(msg):
"""Roll angle, BDS 5,0 message
Args:
msg (String): 28 bytes hexadecimal message (BDS50) string
Returns:
float: angle in degrees,
negative->left wing down, positive->right wing down
"""
d = hex2bin(data(msg))
if d[0] == '0':
return None
sign = int(d[1]) # 1 -> left wing down
value = bin2int(d[2:11])
if sign:
value = value - 512
angle = value * 45.0 / 256.0 # degree
return round(angle, 1) | python | def roll50(msg):
d = hex2bin(data(msg))
if d[0] == '0':
return None
sign = int(d[1]) # 1 -> left wing down
value = bin2int(d[2:11])
if sign:
value = value - 512
angle = value * 45.0 / 256.0 # degree
return round(angle, 1) | [
"def",
"roll50",
"(",
"msg",
")",
":",
"d",
"=",
"hex2bin",
"(",
"data",
"(",
"msg",
")",
")",
"if",
"d",
"[",
"0",
"]",
"==",
"'0'",
":",
"return",
"None",
"sign",
"=",
"int",
"(",
"d",
"[",
"1",
"]",
")",
"# 1 -> left wing down",
"value",
"=",
"bin2int",
"(",
"d",
"[",
"2",
":",
"11",
"]",
")",
"if",
"sign",
":",
"value",
"=",
"value",
"-",
"512",
"angle",
"=",
"value",
"*",
"45.0",
"/",
"256.0",
"# degree",
"return",
"round",
"(",
"angle",
",",
"1",
")"
] | Roll angle, BDS 5,0 message
Args:
msg (String): 28 bytes hexadecimal message (BDS50) string
Returns:
float: angle in degrees,
negative->left wing down, positive->right wing down | [
"Roll",
"angle",
"BDS",
"5",
"0",
"message"
] | 8cd5655a04b08171a9ad5f1ffd232b7e0178ea53 | https://github.com/junzis/pyModeS/blob/8cd5655a04b08171a9ad5f1ffd232b7e0178ea53/pyModeS/decoder/bds/bds50.py#L76-L98 |
248,369 | junzis/pyModeS | pyModeS/decoder/bds/bds50.py | trk50 | def trk50(msg):
"""True track angle, BDS 5,0 message
Args:
msg (String): 28 bytes hexadecimal message (BDS50) string
Returns:
float: angle in degrees to true north (from 0 to 360)
"""
d = hex2bin(data(msg))
if d[11] == '0':
return None
sign = int(d[12]) # 1 -> west
value = bin2int(d[13:23])
if sign:
value = value - 1024
trk = value * 90.0 / 512.0
# convert from [-180, 180] to [0, 360]
if trk < 0:
trk = 360 + trk
return round(trk, 3) | python | def trk50(msg):
d = hex2bin(data(msg))
if d[11] == '0':
return None
sign = int(d[12]) # 1 -> west
value = bin2int(d[13:23])
if sign:
value = value - 1024
trk = value * 90.0 / 512.0
# convert from [-180, 180] to [0, 360]
if trk < 0:
trk = 360 + trk
return round(trk, 3) | [
"def",
"trk50",
"(",
"msg",
")",
":",
"d",
"=",
"hex2bin",
"(",
"data",
"(",
"msg",
")",
")",
"if",
"d",
"[",
"11",
"]",
"==",
"'0'",
":",
"return",
"None",
"sign",
"=",
"int",
"(",
"d",
"[",
"12",
"]",
")",
"# 1 -> west",
"value",
"=",
"bin2int",
"(",
"d",
"[",
"13",
":",
"23",
"]",
")",
"if",
"sign",
":",
"value",
"=",
"value",
"-",
"1024",
"trk",
"=",
"value",
"*",
"90.0",
"/",
"512.0",
"# convert from [-180, 180] to [0, 360]",
"if",
"trk",
"<",
"0",
":",
"trk",
"=",
"360",
"+",
"trk",
"return",
"round",
"(",
"trk",
",",
"3",
")"
] | True track angle, BDS 5,0 message
Args:
msg (String): 28 bytes hexadecimal message (BDS50) string
Returns:
float: angle in degrees to true north (from 0 to 360) | [
"True",
"track",
"angle",
"BDS",
"5",
"0",
"message"
] | 8cd5655a04b08171a9ad5f1ffd232b7e0178ea53 | https://github.com/junzis/pyModeS/blob/8cd5655a04b08171a9ad5f1ffd232b7e0178ea53/pyModeS/decoder/bds/bds50.py#L101-L127 |
248,370 | junzis/pyModeS | pyModeS/decoder/bds/bds50.py | gs50 | def gs50(msg):
"""Ground speed, BDS 5,0 message
Args:
msg (String): 28 bytes hexadecimal message (BDS50) string
Returns:
int: ground speed in knots
"""
d = hex2bin(data(msg))
if d[23] == '0':
return None
spd = bin2int(d[24:34]) * 2 # kts
return spd | python | def gs50(msg):
d = hex2bin(data(msg))
if d[23] == '0':
return None
spd = bin2int(d[24:34]) * 2 # kts
return spd | [
"def",
"gs50",
"(",
"msg",
")",
":",
"d",
"=",
"hex2bin",
"(",
"data",
"(",
"msg",
")",
")",
"if",
"d",
"[",
"23",
"]",
"==",
"'0'",
":",
"return",
"None",
"spd",
"=",
"bin2int",
"(",
"d",
"[",
"24",
":",
"34",
"]",
")",
"*",
"2",
"# kts",
"return",
"spd"
] | Ground speed, BDS 5,0 message
Args:
msg (String): 28 bytes hexadecimal message (BDS50) string
Returns:
int: ground speed in knots | [
"Ground",
"speed",
"BDS",
"5",
"0",
"message"
] | 8cd5655a04b08171a9ad5f1ffd232b7e0178ea53 | https://github.com/junzis/pyModeS/blob/8cd5655a04b08171a9ad5f1ffd232b7e0178ea53/pyModeS/decoder/bds/bds50.py#L130-L145 |
248,371 | junzis/pyModeS | pyModeS/decoder/bds/bds50.py | tas50 | def tas50(msg):
"""Aircraft true airspeed, BDS 5,0 message
Args:
msg (String): 28 bytes hexadecimal message (BDS50) string
Returns:
int: true airspeed in knots
"""
d = hex2bin(data(msg))
if d[45] == '0':
return None
tas = bin2int(d[46:56]) * 2 # kts
return tas | python | def tas50(msg):
d = hex2bin(data(msg))
if d[45] == '0':
return None
tas = bin2int(d[46:56]) * 2 # kts
return tas | [
"def",
"tas50",
"(",
"msg",
")",
":",
"d",
"=",
"hex2bin",
"(",
"data",
"(",
"msg",
")",
")",
"if",
"d",
"[",
"45",
"]",
"==",
"'0'",
":",
"return",
"None",
"tas",
"=",
"bin2int",
"(",
"d",
"[",
"46",
":",
"56",
"]",
")",
"*",
"2",
"# kts",
"return",
"tas"
] | Aircraft true airspeed, BDS 5,0 message
Args:
msg (String): 28 bytes hexadecimal message (BDS50) string
Returns:
int: true airspeed in knots | [
"Aircraft",
"true",
"airspeed",
"BDS",
"5",
"0",
"message"
] | 8cd5655a04b08171a9ad5f1ffd232b7e0178ea53 | https://github.com/junzis/pyModeS/blob/8cd5655a04b08171a9ad5f1ffd232b7e0178ea53/pyModeS/decoder/bds/bds50.py#L174-L189 |
248,372 | junzis/pyModeS | pyModeS/decoder/bds/bds53.py | ias53 | def ias53(msg):
"""Indicated airspeed, DBS 5,3 message
Args:
msg (String): 28 bytes hexadecimal message
Returns:
int: indicated arispeed in knots
"""
d = hex2bin(data(msg))
if d[12] == '0':
return None
ias = bin2int(d[13:23]) # knots
return ias | python | def ias53(msg):
d = hex2bin(data(msg))
if d[12] == '0':
return None
ias = bin2int(d[13:23]) # knots
return ias | [
"def",
"ias53",
"(",
"msg",
")",
":",
"d",
"=",
"hex2bin",
"(",
"data",
"(",
"msg",
")",
")",
"if",
"d",
"[",
"12",
"]",
"==",
"'0'",
":",
"return",
"None",
"ias",
"=",
"bin2int",
"(",
"d",
"[",
"13",
":",
"23",
"]",
")",
"# knots",
"return",
"ias"
] | Indicated airspeed, DBS 5,3 message
Args:
msg (String): 28 bytes hexadecimal message
Returns:
int: indicated arispeed in knots | [
"Indicated",
"airspeed",
"DBS",
"5",
"3",
"message"
] | 8cd5655a04b08171a9ad5f1ffd232b7e0178ea53 | https://github.com/junzis/pyModeS/blob/8cd5655a04b08171a9ad5f1ffd232b7e0178ea53/pyModeS/decoder/bds/bds53.py#L106-L121 |
248,373 | junzis/pyModeS | pyModeS/decoder/bds/bds53.py | mach53 | def mach53(msg):
"""MACH number, DBS 5,3 message
Args:
msg (String): 28 bytes hexadecimal message
Returns:
float: MACH number
"""
d = hex2bin(data(msg))
if d[23] == '0':
return None
mach = bin2int(d[24:33]) * 0.008
return round(mach, 3) | python | def mach53(msg):
d = hex2bin(data(msg))
if d[23] == '0':
return None
mach = bin2int(d[24:33]) * 0.008
return round(mach, 3) | [
"def",
"mach53",
"(",
"msg",
")",
":",
"d",
"=",
"hex2bin",
"(",
"data",
"(",
"msg",
")",
")",
"if",
"d",
"[",
"23",
"]",
"==",
"'0'",
":",
"return",
"None",
"mach",
"=",
"bin2int",
"(",
"d",
"[",
"24",
":",
"33",
"]",
")",
"*",
"0.008",
"return",
"round",
"(",
"mach",
",",
"3",
")"
] | MACH number, DBS 5,3 message
Args:
msg (String): 28 bytes hexadecimal message
Returns:
float: MACH number | [
"MACH",
"number",
"DBS",
"5",
"3",
"message"
] | 8cd5655a04b08171a9ad5f1ffd232b7e0178ea53 | https://github.com/junzis/pyModeS/blob/8cd5655a04b08171a9ad5f1ffd232b7e0178ea53/pyModeS/decoder/bds/bds53.py#L124-L139 |
248,374 | junzis/pyModeS | pyModeS/decoder/bds/bds53.py | tas53 | def tas53(msg):
"""Aircraft true airspeed, BDS 5,3 message
Args:
msg (String): 28 bytes hexadecimal message
Returns:
float: true airspeed in knots
"""
d = hex2bin(data(msg))
if d[33] == '0':
return None
tas = bin2int(d[34:46]) * 0.5 # kts
return round(tas, 1) | python | def tas53(msg):
d = hex2bin(data(msg))
if d[33] == '0':
return None
tas = bin2int(d[34:46]) * 0.5 # kts
return round(tas, 1) | [
"def",
"tas53",
"(",
"msg",
")",
":",
"d",
"=",
"hex2bin",
"(",
"data",
"(",
"msg",
")",
")",
"if",
"d",
"[",
"33",
"]",
"==",
"'0'",
":",
"return",
"None",
"tas",
"=",
"bin2int",
"(",
"d",
"[",
"34",
":",
"46",
"]",
")",
"*",
"0.5",
"# kts",
"return",
"round",
"(",
"tas",
",",
"1",
")"
] | Aircraft true airspeed, BDS 5,3 message
Args:
msg (String): 28 bytes hexadecimal message
Returns:
float: true airspeed in knots | [
"Aircraft",
"true",
"airspeed",
"BDS",
"5",
"3",
"message"
] | 8cd5655a04b08171a9ad5f1ffd232b7e0178ea53 | https://github.com/junzis/pyModeS/blob/8cd5655a04b08171a9ad5f1ffd232b7e0178ea53/pyModeS/decoder/bds/bds53.py#L142-L157 |
248,375 | junzis/pyModeS | pyModeS/extra/tcpclient.py | BaseClient.read_skysense_buffer | def read_skysense_buffer(self):
"""Skysense stream format.
::
----------------------------------------------------------------------------------
Field SS MS MS MS MS MS MS MS MS MS MS MS MS MS MS TS TS TS TS TS TS RS RS RS
----------------------------------------------------------------------------------
Position: 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
----------------------------------------------------------------------------------
SS field - Start character
Position 0:
1 byte = 8 bits
Start character '$'
MS field - Payload
Postion 1 through 14:
14 bytes = 112 bits
Mode-S payload
In case of DF types that only carry 7 bytes of information
position 8 through 14 are set to 0x00.
TS field - Time stamp
Position 15 through 20:
6 bytes = 48 bits
Time stamp with fields as:
Lock Status - Status of internal time keeping mechanism
Equal to 1 if operating normally
Bit 47 - 1 bit
Time of day in UTC seconds, between 0 and 86399
Bits 46 through 30 - 17 bits
Nanoseconds into current second, between 0 and 999999999
Bits 29 through 0 - 30 bits
RS field - Signal Level
Position 21 through 23:
3 bytes = 24 bits
RSSI (received signal strength indication) and relative
noise level with fields
RNL, Q12.4 unsigned fixed point binary with 4 fractional
bits and 8 integer bits.
This is and indication of the noise level of the message.
Roughly 40 counts per 10dBm.
Bits 23 through 12 - 12 bits
RSSI, Q12.4 unsigned fixed point binary with 4 fractional
bits and 8 integer bits.
This is an indication of the signal level of the received
message in ADC counts. Roughly 40 counts per 10dBm.
Bits 11 through 0 - 12 bits
"""
SS_MSGLENGTH = 24
SS_STARTCHAR = 0x24
if len(self.buffer) <= SS_MSGLENGTH:
return None
messages = []
while len(self.buffer) > SS_MSGLENGTH:
i = 0
if self.buffer[i] == SS_STARTCHAR and self.buffer[i+SS_MSGLENGTH] == SS_STARTCHAR:
i += 1
if (self.buffer[i]>>7):
#Long message
payload = self.buffer[i:i+14]
else:
#Short message
payload = self.buffer[i:i+7]
msg = ''.join('%02X' % j for j in payload)
i += 14 #Both message types use 14 bytes
tsbin = self.buffer[i:i+6]
sec = ( (tsbin[0] & 0x7f) << 10) | (tsbin[1] << 2 ) | (tsbin[2] >> 6)
nano = ( (tsbin[2] & 0x3f) << 24) | (tsbin[3] << 16) | (tsbin[4] << 8) | tsbin[5]
ts = sec + nano*1.0e-9
i += 6
#Signal and noise level - Don't care for now
i += 3
self.buffer = self.buffer[SS_MSGLENGTH:]
messages.append( [msg,ts] )
else:
self.buffer = self.buffer[1:]
return messages | python | def read_skysense_buffer(self):
SS_MSGLENGTH = 24
SS_STARTCHAR = 0x24
if len(self.buffer) <= SS_MSGLENGTH:
return None
messages = []
while len(self.buffer) > SS_MSGLENGTH:
i = 0
if self.buffer[i] == SS_STARTCHAR and self.buffer[i+SS_MSGLENGTH] == SS_STARTCHAR:
i += 1
if (self.buffer[i]>>7):
#Long message
payload = self.buffer[i:i+14]
else:
#Short message
payload = self.buffer[i:i+7]
msg = ''.join('%02X' % j for j in payload)
i += 14 #Both message types use 14 bytes
tsbin = self.buffer[i:i+6]
sec = ( (tsbin[0] & 0x7f) << 10) | (tsbin[1] << 2 ) | (tsbin[2] >> 6)
nano = ( (tsbin[2] & 0x3f) << 24) | (tsbin[3] << 16) | (tsbin[4] << 8) | tsbin[5]
ts = sec + nano*1.0e-9
i += 6
#Signal and noise level - Don't care for now
i += 3
self.buffer = self.buffer[SS_MSGLENGTH:]
messages.append( [msg,ts] )
else:
self.buffer = self.buffer[1:]
return messages | [
"def",
"read_skysense_buffer",
"(",
"self",
")",
":",
"SS_MSGLENGTH",
"=",
"24",
"SS_STARTCHAR",
"=",
"0x24",
"if",
"len",
"(",
"self",
".",
"buffer",
")",
"<=",
"SS_MSGLENGTH",
":",
"return",
"None",
"messages",
"=",
"[",
"]",
"while",
"len",
"(",
"self",
".",
"buffer",
")",
">",
"SS_MSGLENGTH",
":",
"i",
"=",
"0",
"if",
"self",
".",
"buffer",
"[",
"i",
"]",
"==",
"SS_STARTCHAR",
"and",
"self",
".",
"buffer",
"[",
"i",
"+",
"SS_MSGLENGTH",
"]",
"==",
"SS_STARTCHAR",
":",
"i",
"+=",
"1",
"if",
"(",
"self",
".",
"buffer",
"[",
"i",
"]",
">>",
"7",
")",
":",
"#Long message",
"payload",
"=",
"self",
".",
"buffer",
"[",
"i",
":",
"i",
"+",
"14",
"]",
"else",
":",
"#Short message",
"payload",
"=",
"self",
".",
"buffer",
"[",
"i",
":",
"i",
"+",
"7",
"]",
"msg",
"=",
"''",
".",
"join",
"(",
"'%02X'",
"%",
"j",
"for",
"j",
"in",
"payload",
")",
"i",
"+=",
"14",
"#Both message types use 14 bytes",
"tsbin",
"=",
"self",
".",
"buffer",
"[",
"i",
":",
"i",
"+",
"6",
"]",
"sec",
"=",
"(",
"(",
"tsbin",
"[",
"0",
"]",
"&",
"0x7f",
")",
"<<",
"10",
")",
"|",
"(",
"tsbin",
"[",
"1",
"]",
"<<",
"2",
")",
"|",
"(",
"tsbin",
"[",
"2",
"]",
">>",
"6",
")",
"nano",
"=",
"(",
"(",
"tsbin",
"[",
"2",
"]",
"&",
"0x3f",
")",
"<<",
"24",
")",
"|",
"(",
"tsbin",
"[",
"3",
"]",
"<<",
"16",
")",
"|",
"(",
"tsbin",
"[",
"4",
"]",
"<<",
"8",
")",
"|",
"tsbin",
"[",
"5",
"]",
"ts",
"=",
"sec",
"+",
"nano",
"*",
"1.0e-9",
"i",
"+=",
"6",
"#Signal and noise level - Don't care for now",
"i",
"+=",
"3",
"self",
".",
"buffer",
"=",
"self",
".",
"buffer",
"[",
"SS_MSGLENGTH",
":",
"]",
"messages",
".",
"append",
"(",
"[",
"msg",
",",
"ts",
"]",
")",
"else",
":",
"self",
".",
"buffer",
"=",
"self",
".",
"buffer",
"[",
"1",
":",
"]",
"return",
"messages"
] | Skysense stream format.
::
----------------------------------------------------------------------------------
Field SS MS MS MS MS MS MS MS MS MS MS MS MS MS MS TS TS TS TS TS TS RS RS RS
----------------------------------------------------------------------------------
Position: 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
----------------------------------------------------------------------------------
SS field - Start character
Position 0:
1 byte = 8 bits
Start character '$'
MS field - Payload
Postion 1 through 14:
14 bytes = 112 bits
Mode-S payload
In case of DF types that only carry 7 bytes of information
position 8 through 14 are set to 0x00.
TS field - Time stamp
Position 15 through 20:
6 bytes = 48 bits
Time stamp with fields as:
Lock Status - Status of internal time keeping mechanism
Equal to 1 if operating normally
Bit 47 - 1 bit
Time of day in UTC seconds, between 0 and 86399
Bits 46 through 30 - 17 bits
Nanoseconds into current second, between 0 and 999999999
Bits 29 through 0 - 30 bits
RS field - Signal Level
Position 21 through 23:
3 bytes = 24 bits
RSSI (received signal strength indication) and relative
noise level with fields
RNL, Q12.4 unsigned fixed point binary with 4 fractional
bits and 8 integer bits.
This is and indication of the noise level of the message.
Roughly 40 counts per 10dBm.
Bits 23 through 12 - 12 bits
RSSI, Q12.4 unsigned fixed point binary with 4 fractional
bits and 8 integer bits.
This is an indication of the signal level of the received
message in ADC counts. Roughly 40 counts per 10dBm.
Bits 11 through 0 - 12 bits | [
"Skysense",
"stream",
"format",
"."
] | 8cd5655a04b08171a9ad5f1ffd232b7e0178ea53 | https://github.com/junzis/pyModeS/blob/8cd5655a04b08171a9ad5f1ffd232b7e0178ea53/pyModeS/extra/tcpclient.py#L147-L233 |
248,376 | junzis/pyModeS | pyModeS/decoder/bds/bds10.py | is10 | def is10(msg):
"""Check if a message is likely to be BDS code 1,0
Args:
msg (String): 28 bytes hexadecimal message string
Returns:
bool: True or False
"""
if allzeros(msg):
return False
d = hex2bin(data(msg))
# first 8 bits must be 0x10
if d[0:8] != '00010000':
return False
# bit 10 to 14 are reserved
if bin2int(d[9:14]) != 0:
return False
# overlay capabilty conflict
if d[14] == '1' and bin2int(d[16:23]) < 5:
return False
if d[14] == '0' and bin2int(d[16:23]) > 4:
return False
return True | python | def is10(msg):
if allzeros(msg):
return False
d = hex2bin(data(msg))
# first 8 bits must be 0x10
if d[0:8] != '00010000':
return False
# bit 10 to 14 are reserved
if bin2int(d[9:14]) != 0:
return False
# overlay capabilty conflict
if d[14] == '1' and bin2int(d[16:23]) < 5:
return False
if d[14] == '0' and bin2int(d[16:23]) > 4:
return False
return True | [
"def",
"is10",
"(",
"msg",
")",
":",
"if",
"allzeros",
"(",
"msg",
")",
":",
"return",
"False",
"d",
"=",
"hex2bin",
"(",
"data",
"(",
"msg",
")",
")",
"# first 8 bits must be 0x10",
"if",
"d",
"[",
"0",
":",
"8",
"]",
"!=",
"'00010000'",
":",
"return",
"False",
"# bit 10 to 14 are reserved",
"if",
"bin2int",
"(",
"d",
"[",
"9",
":",
"14",
"]",
")",
"!=",
"0",
":",
"return",
"False",
"# overlay capabilty conflict",
"if",
"d",
"[",
"14",
"]",
"==",
"'1'",
"and",
"bin2int",
"(",
"d",
"[",
"16",
":",
"23",
"]",
")",
"<",
"5",
":",
"return",
"False",
"if",
"d",
"[",
"14",
"]",
"==",
"'0'",
"and",
"bin2int",
"(",
"d",
"[",
"16",
":",
"23",
"]",
")",
">",
"4",
":",
"return",
"False",
"return",
"True"
] | Check if a message is likely to be BDS code 1,0
Args:
msg (String): 28 bytes hexadecimal message string
Returns:
bool: True or False | [
"Check",
"if",
"a",
"message",
"is",
"likely",
"to",
"be",
"BDS",
"code",
"1",
"0"
] | 8cd5655a04b08171a9ad5f1ffd232b7e0178ea53 | https://github.com/junzis/pyModeS/blob/8cd5655a04b08171a9ad5f1ffd232b7e0178ea53/pyModeS/decoder/bds/bds10.py#L24-L53 |
248,377 | junzis/pyModeS | pyModeS/decoder/bds/bds17.py | is17 | def is17(msg):
"""Check if a message is likely to be BDS code 1,7
Args:
msg (String): 28 bytes hexadecimal message string
Returns:
bool: True or False
"""
if allzeros(msg):
return False
d = hex2bin(data(msg))
if bin2int(d[28:56]) != 0:
return False
caps = cap17(msg)
# basic BDS codes for ADS-B shall be supported
# assuming ADS-B out is installed (2017EU/2020US mandate)
# if not set(['BDS05', 'BDS06', 'BDS08', 'BDS09', 'BDS20']).issubset(caps):
# return False
# at least you can respond who you are
if 'BDS20' not in caps:
return False
return True | python | def is17(msg):
if allzeros(msg):
return False
d = hex2bin(data(msg))
if bin2int(d[28:56]) != 0:
return False
caps = cap17(msg)
# basic BDS codes for ADS-B shall be supported
# assuming ADS-B out is installed (2017EU/2020US mandate)
# if not set(['BDS05', 'BDS06', 'BDS08', 'BDS09', 'BDS20']).issubset(caps):
# return False
# at least you can respond who you are
if 'BDS20' not in caps:
return False
return True | [
"def",
"is17",
"(",
"msg",
")",
":",
"if",
"allzeros",
"(",
"msg",
")",
":",
"return",
"False",
"d",
"=",
"hex2bin",
"(",
"data",
"(",
"msg",
")",
")",
"if",
"bin2int",
"(",
"d",
"[",
"28",
":",
"56",
"]",
")",
"!=",
"0",
":",
"return",
"False",
"caps",
"=",
"cap17",
"(",
"msg",
")",
"# basic BDS codes for ADS-B shall be supported",
"# assuming ADS-B out is installed (2017EU/2020US mandate)",
"# if not set(['BDS05', 'BDS06', 'BDS08', 'BDS09', 'BDS20']).issubset(caps):",
"# return False",
"# at least you can respond who you are",
"if",
"'BDS20'",
"not",
"in",
"caps",
":",
"return",
"False",
"return",
"True"
] | Check if a message is likely to be BDS code 1,7
Args:
msg (String): 28 bytes hexadecimal message string
Returns:
bool: True or False | [
"Check",
"if",
"a",
"message",
"is",
"likely",
"to",
"be",
"BDS",
"code",
"1",
"7"
] | 8cd5655a04b08171a9ad5f1ffd232b7e0178ea53 | https://github.com/junzis/pyModeS/blob/8cd5655a04b08171a9ad5f1ffd232b7e0178ea53/pyModeS/decoder/bds/bds17.py#L27-L56 |
248,378 | junzis/pyModeS | pyModeS/decoder/bds/bds17.py | cap17 | def cap17(msg):
"""Extract capacities from BDS 1,7 message
Args:
msg (String): 28 bytes hexadecimal message string
Returns:
list: list of suport BDS codes
"""
allbds = ['05', '06', '07', '08', '09', '0A', '20', '21', '40', '41',
'42', '43', '44', '45', '48', '50', '51', '52', '53', '54',
'55', '56', '5F', '60', 'NA', 'NA', 'E1', 'E2']
d = hex2bin(data(msg))
idx = [i for i, v in enumerate(d[:28]) if v=='1']
capacity = ['BDS'+allbds[i] for i in idx if allbds[i] is not 'NA']
return capacity | python | def cap17(msg):
allbds = ['05', '06', '07', '08', '09', '0A', '20', '21', '40', '41',
'42', '43', '44', '45', '48', '50', '51', '52', '53', '54',
'55', '56', '5F', '60', 'NA', 'NA', 'E1', 'E2']
d = hex2bin(data(msg))
idx = [i for i, v in enumerate(d[:28]) if v=='1']
capacity = ['BDS'+allbds[i] for i in idx if allbds[i] is not 'NA']
return capacity | [
"def",
"cap17",
"(",
"msg",
")",
":",
"allbds",
"=",
"[",
"'05'",
",",
"'06'",
",",
"'07'",
",",
"'08'",
",",
"'09'",
",",
"'0A'",
",",
"'20'",
",",
"'21'",
",",
"'40'",
",",
"'41'",
",",
"'42'",
",",
"'43'",
",",
"'44'",
",",
"'45'",
",",
"'48'",
",",
"'50'",
",",
"'51'",
",",
"'52'",
",",
"'53'",
",",
"'54'",
",",
"'55'",
",",
"'56'",
",",
"'5F'",
",",
"'60'",
",",
"'NA'",
",",
"'NA'",
",",
"'E1'",
",",
"'E2'",
"]",
"d",
"=",
"hex2bin",
"(",
"data",
"(",
"msg",
")",
")",
"idx",
"=",
"[",
"i",
"for",
"i",
",",
"v",
"in",
"enumerate",
"(",
"d",
"[",
":",
"28",
"]",
")",
"if",
"v",
"==",
"'1'",
"]",
"capacity",
"=",
"[",
"'BDS'",
"+",
"allbds",
"[",
"i",
"]",
"for",
"i",
"in",
"idx",
"if",
"allbds",
"[",
"i",
"]",
"is",
"not",
"'NA'",
"]",
"return",
"capacity"
] | Extract capacities from BDS 1,7 message
Args:
msg (String): 28 bytes hexadecimal message string
Returns:
list: list of suport BDS codes | [
"Extract",
"capacities",
"from",
"BDS",
"1",
"7",
"message"
] | 8cd5655a04b08171a9ad5f1ffd232b7e0178ea53 | https://github.com/junzis/pyModeS/blob/8cd5655a04b08171a9ad5f1ffd232b7e0178ea53/pyModeS/decoder/bds/bds17.py#L58-L75 |
248,379 | junzis/pyModeS | pyModeS/streamer/stream.py | Stream.get_aircraft | def get_aircraft(self):
"""all aircraft that are stored in memeory"""
acs = self.acs
icaos = list(acs.keys())
for icao in icaos:
if acs[icao]['lat'] is None:
acs.pop(icao)
return acs | python | def get_aircraft(self):
acs = self.acs
icaos = list(acs.keys())
for icao in icaos:
if acs[icao]['lat'] is None:
acs.pop(icao)
return acs | [
"def",
"get_aircraft",
"(",
"self",
")",
":",
"acs",
"=",
"self",
".",
"acs",
"icaos",
"=",
"list",
"(",
"acs",
".",
"keys",
"(",
")",
")",
"for",
"icao",
"in",
"icaos",
":",
"if",
"acs",
"[",
"icao",
"]",
"[",
"'lat'",
"]",
"is",
"None",
":",
"acs",
".",
"pop",
"(",
"icao",
")",
"return",
"acs"
] | all aircraft that are stored in memeory | [
"all",
"aircraft",
"that",
"are",
"stored",
"in",
"memeory"
] | 8cd5655a04b08171a9ad5f1ffd232b7e0178ea53 | https://github.com/junzis/pyModeS/blob/8cd5655a04b08171a9ad5f1ffd232b7e0178ea53/pyModeS/streamer/stream.py#L248-L255 |
248,380 | junzis/pyModeS | pyModeS/decoder/bds/bds09.py | altitude_diff | def altitude_diff(msg):
"""Decode the differece between GNSS and barometric altitude
Args:
msg (string): 28 bytes hexadecimal message string, TC=19
Returns:
int: Altitude difference in ft. Negative value indicates GNSS altitude
below barometric altitude.
"""
tc = common.typecode(msg)
if tc != 19:
raise RuntimeError("%s: Not a airborne velocity message, expecting TC=19" % msg)
msgbin = common.hex2bin(msg)
sign = -1 if int(msgbin[80]) else 1
value = common.bin2int(msgbin[81:88])
if value == 0 or value == 127:
return None
else:
return sign * (value - 1) * 25 | python | def altitude_diff(msg):
tc = common.typecode(msg)
if tc != 19:
raise RuntimeError("%s: Not a airborne velocity message, expecting TC=19" % msg)
msgbin = common.hex2bin(msg)
sign = -1 if int(msgbin[80]) else 1
value = common.bin2int(msgbin[81:88])
if value == 0 or value == 127:
return None
else:
return sign * (value - 1) * 25 | [
"def",
"altitude_diff",
"(",
"msg",
")",
":",
"tc",
"=",
"common",
".",
"typecode",
"(",
"msg",
")",
"if",
"tc",
"!=",
"19",
":",
"raise",
"RuntimeError",
"(",
"\"%s: Not a airborne velocity message, expecting TC=19\"",
"%",
"msg",
")",
"msgbin",
"=",
"common",
".",
"hex2bin",
"(",
"msg",
")",
"sign",
"=",
"-",
"1",
"if",
"int",
"(",
"msgbin",
"[",
"80",
"]",
")",
"else",
"1",
"value",
"=",
"common",
".",
"bin2int",
"(",
"msgbin",
"[",
"81",
":",
"88",
"]",
")",
"if",
"value",
"==",
"0",
"or",
"value",
"==",
"127",
":",
"return",
"None",
"else",
":",
"return",
"sign",
"*",
"(",
"value",
"-",
"1",
")",
"*",
"25"
] | Decode the differece between GNSS and barometric altitude
Args:
msg (string): 28 bytes hexadecimal message string, TC=19
Returns:
int: Altitude difference in ft. Negative value indicates GNSS altitude
below barometric altitude. | [
"Decode",
"the",
"differece",
"between",
"GNSS",
"and",
"barometric",
"altitude"
] | 8cd5655a04b08171a9ad5f1ffd232b7e0178ea53 | https://github.com/junzis/pyModeS/blob/8cd5655a04b08171a9ad5f1ffd232b7e0178ea53/pyModeS/decoder/bds/bds09.py#L93-L115 |
248,381 | junzis/pyModeS | pyModeS/decoder/bds/__init__.py | is50or60 | def is50or60(msg, spd_ref, trk_ref, alt_ref):
"""Use reference ground speed and trk to determine BDS50 and DBS60.
Args:
msg (String): 28 bytes hexadecimal message string
spd_ref (float): reference speed (ADS-B ground speed), kts
trk_ref (float): reference track (ADS-B track angle), deg
alt_ref (float): reference altitude (ADS-B altitude), ft
Returns:
String or None: BDS version, or possible versions, or None if nothing matches.
"""
def vxy(v, angle):
vx = v * np.sin(np.radians(angle))
vy = v * np.cos(np.radians(angle))
return vx, vy
if not (bds50.is50(msg) and bds60.is60(msg)):
return None
h50 = bds50.trk50(msg)
v50 = bds50.gs50(msg)
if h50 is None or v50 is None:
return 'BDS50,BDS60'
h60 = bds60.hdg60(msg)
m60 = bds60.mach60(msg)
i60 = bds60.ias60(msg)
if h60 is None or (m60 is None and i60 is None):
return 'BDS50,BDS60'
m60 = np.nan if m60 is None else m60
i60 = np.nan if i60 is None else i60
XY5 = vxy(v50*aero.kts, h50)
XY6m = vxy(aero.mach2tas(m60, alt_ref*aero.ft), h60)
XY6i = vxy(aero.cas2tas(i60*aero.kts, alt_ref*aero.ft), h60)
allbds = ['BDS50', 'BDS60', 'BDS60']
X = np.array([XY5, XY6m, XY6i])
Mu = np.array(vxy(spd_ref*aero.kts, trk_ref))
# compute Mahalanobis distance matrix
# Cov = [[20**2, 0], [0, 20**2]]
# mmatrix = np.sqrt(np.dot(np.dot(X-Mu, np.linalg.inv(Cov)), (X-Mu).T))
# dist = np.diag(mmatrix)
# since the covariance matrix is identity matrix,
# M-dist is same as eculidian distance
try:
dist = np.linalg.norm(X-Mu, axis=1)
BDS = allbds[np.nanargmin(dist)]
except ValueError:
return 'BDS50,BDS60'
return BDS | python | def is50or60(msg, spd_ref, trk_ref, alt_ref):
def vxy(v, angle):
vx = v * np.sin(np.radians(angle))
vy = v * np.cos(np.radians(angle))
return vx, vy
if not (bds50.is50(msg) and bds60.is60(msg)):
return None
h50 = bds50.trk50(msg)
v50 = bds50.gs50(msg)
if h50 is None or v50 is None:
return 'BDS50,BDS60'
h60 = bds60.hdg60(msg)
m60 = bds60.mach60(msg)
i60 = bds60.ias60(msg)
if h60 is None or (m60 is None and i60 is None):
return 'BDS50,BDS60'
m60 = np.nan if m60 is None else m60
i60 = np.nan if i60 is None else i60
XY5 = vxy(v50*aero.kts, h50)
XY6m = vxy(aero.mach2tas(m60, alt_ref*aero.ft), h60)
XY6i = vxy(aero.cas2tas(i60*aero.kts, alt_ref*aero.ft), h60)
allbds = ['BDS50', 'BDS60', 'BDS60']
X = np.array([XY5, XY6m, XY6i])
Mu = np.array(vxy(spd_ref*aero.kts, trk_ref))
# compute Mahalanobis distance matrix
# Cov = [[20**2, 0], [0, 20**2]]
# mmatrix = np.sqrt(np.dot(np.dot(X-Mu, np.linalg.inv(Cov)), (X-Mu).T))
# dist = np.diag(mmatrix)
# since the covariance matrix is identity matrix,
# M-dist is same as eculidian distance
try:
dist = np.linalg.norm(X-Mu, axis=1)
BDS = allbds[np.nanargmin(dist)]
except ValueError:
return 'BDS50,BDS60'
return BDS | [
"def",
"is50or60",
"(",
"msg",
",",
"spd_ref",
",",
"trk_ref",
",",
"alt_ref",
")",
":",
"def",
"vxy",
"(",
"v",
",",
"angle",
")",
":",
"vx",
"=",
"v",
"*",
"np",
".",
"sin",
"(",
"np",
".",
"radians",
"(",
"angle",
")",
")",
"vy",
"=",
"v",
"*",
"np",
".",
"cos",
"(",
"np",
".",
"radians",
"(",
"angle",
")",
")",
"return",
"vx",
",",
"vy",
"if",
"not",
"(",
"bds50",
".",
"is50",
"(",
"msg",
")",
"and",
"bds60",
".",
"is60",
"(",
"msg",
")",
")",
":",
"return",
"None",
"h50",
"=",
"bds50",
".",
"trk50",
"(",
"msg",
")",
"v50",
"=",
"bds50",
".",
"gs50",
"(",
"msg",
")",
"if",
"h50",
"is",
"None",
"or",
"v50",
"is",
"None",
":",
"return",
"'BDS50,BDS60'",
"h60",
"=",
"bds60",
".",
"hdg60",
"(",
"msg",
")",
"m60",
"=",
"bds60",
".",
"mach60",
"(",
"msg",
")",
"i60",
"=",
"bds60",
".",
"ias60",
"(",
"msg",
")",
"if",
"h60",
"is",
"None",
"or",
"(",
"m60",
"is",
"None",
"and",
"i60",
"is",
"None",
")",
":",
"return",
"'BDS50,BDS60'",
"m60",
"=",
"np",
".",
"nan",
"if",
"m60",
"is",
"None",
"else",
"m60",
"i60",
"=",
"np",
".",
"nan",
"if",
"i60",
"is",
"None",
"else",
"i60",
"XY5",
"=",
"vxy",
"(",
"v50",
"*",
"aero",
".",
"kts",
",",
"h50",
")",
"XY6m",
"=",
"vxy",
"(",
"aero",
".",
"mach2tas",
"(",
"m60",
",",
"alt_ref",
"*",
"aero",
".",
"ft",
")",
",",
"h60",
")",
"XY6i",
"=",
"vxy",
"(",
"aero",
".",
"cas2tas",
"(",
"i60",
"*",
"aero",
".",
"kts",
",",
"alt_ref",
"*",
"aero",
".",
"ft",
")",
",",
"h60",
")",
"allbds",
"=",
"[",
"'BDS50'",
",",
"'BDS60'",
",",
"'BDS60'",
"]",
"X",
"=",
"np",
".",
"array",
"(",
"[",
"XY5",
",",
"XY6m",
",",
"XY6i",
"]",
")",
"Mu",
"=",
"np",
".",
"array",
"(",
"vxy",
"(",
"spd_ref",
"*",
"aero",
".",
"kts",
",",
"trk_ref",
")",
")",
"# compute Mahalanobis distance matrix",
"# Cov = [[20**2, 0], [0, 20**2]]",
"# mmatrix = np.sqrt(np.dot(np.dot(X-Mu, np.linalg.inv(Cov)), (X-Mu).T))",
"# dist = np.diag(mmatrix)",
"# since the covariance matrix is identity matrix,",
"# M-dist is same as eculidian distance",
"try",
":",
"dist",
"=",
"np",
".",
"linalg",
".",
"norm",
"(",
"X",
"-",
"Mu",
",",
"axis",
"=",
"1",
")",
"BDS",
"=",
"allbds",
"[",
"np",
".",
"nanargmin",
"(",
"dist",
")",
"]",
"except",
"ValueError",
":",
"return",
"'BDS50,BDS60'",
"return",
"BDS"
] | Use reference ground speed and trk to determine BDS50 and DBS60.
Args:
msg (String): 28 bytes hexadecimal message string
spd_ref (float): reference speed (ADS-B ground speed), kts
trk_ref (float): reference track (ADS-B track angle), deg
alt_ref (float): reference altitude (ADS-B altitude), ft
Returns:
String or None: BDS version, or possible versions, or None if nothing matches. | [
"Use",
"reference",
"ground",
"speed",
"and",
"trk",
"to",
"determine",
"BDS50",
"and",
"DBS60",
"."
] | 8cd5655a04b08171a9ad5f1ffd232b7e0178ea53 | https://github.com/junzis/pyModeS/blob/8cd5655a04b08171a9ad5f1ffd232b7e0178ea53/pyModeS/decoder/bds/__init__.py#L30-L89 |
248,382 | junzis/pyModeS | pyModeS/decoder/bds/__init__.py | infer | def infer(msg, mrar=False):
"""Estimate the most likely BDS code of an message.
Args:
msg (String): 28 bytes hexadecimal message string
mrar (bool): Also infer MRAR (BDS 44) and MHR (BDS 45). Defaults to False.
Returns:
String or None: BDS version, or possible versions, or None if nothing matches.
"""
df = common.df(msg)
if common.allzeros(msg):
return 'EMPTY'
# For ADS-B / Mode-S extended squitter
if df == 17:
tc = common.typecode(msg)
if 1 <= tc <= 4:
return 'BDS08' # indentification and category
if 5 <= tc <= 8:
return 'BDS06' # surface movement
if 9 <= tc <= 18:
return 'BDS05' # airborne position, baro-alt
if tc == 19:
return 'BDS09' # airborne velocity
if 20 <= tc <= 22:
return 'BDS05' # airborne position, gnss-alt
if tc == 28:
return 'BDS61' # aircraft status
if tc == 29:
return 'BDS62' # target state and status
if tc == 31:
return 'BDS65' # operational status
# For Comm-B replies
IS10 = bds10.is10(msg)
IS17 = bds17.is17(msg)
IS20 = bds20.is20(msg)
IS30 = bds30.is30(msg)
IS40 = bds40.is40(msg)
IS50 = bds50.is50(msg)
IS60 = bds60.is60(msg)
IS44 = bds44.is44(msg)
IS45 = bds45.is45(msg)
if mrar:
allbds = np.array(["BDS10", "BDS17", "BDS20", "BDS30", "BDS40",
"BDS44", "BDS45", "BDS50", "BDS60"])
mask = [IS10, IS17, IS20, IS30, IS40, IS44, IS45, IS50, IS60]
else:
allbds = np.array(["BDS10", "BDS17", "BDS20", "BDS30", "BDS40",
"BDS50", "BDS60"])
mask = [IS10, IS17, IS20, IS30, IS40, IS50, IS60]
bds = ','.join(sorted(allbds[mask]))
if len(bds) == 0:
return None
else:
return bds | python | def infer(msg, mrar=False):
df = common.df(msg)
if common.allzeros(msg):
return 'EMPTY'
# For ADS-B / Mode-S extended squitter
if df == 17:
tc = common.typecode(msg)
if 1 <= tc <= 4:
return 'BDS08' # indentification and category
if 5 <= tc <= 8:
return 'BDS06' # surface movement
if 9 <= tc <= 18:
return 'BDS05' # airborne position, baro-alt
if tc == 19:
return 'BDS09' # airborne velocity
if 20 <= tc <= 22:
return 'BDS05' # airborne position, gnss-alt
if tc == 28:
return 'BDS61' # aircraft status
if tc == 29:
return 'BDS62' # target state and status
if tc == 31:
return 'BDS65' # operational status
# For Comm-B replies
IS10 = bds10.is10(msg)
IS17 = bds17.is17(msg)
IS20 = bds20.is20(msg)
IS30 = bds30.is30(msg)
IS40 = bds40.is40(msg)
IS50 = bds50.is50(msg)
IS60 = bds60.is60(msg)
IS44 = bds44.is44(msg)
IS45 = bds45.is45(msg)
if mrar:
allbds = np.array(["BDS10", "BDS17", "BDS20", "BDS30", "BDS40",
"BDS44", "BDS45", "BDS50", "BDS60"])
mask = [IS10, IS17, IS20, IS30, IS40, IS44, IS45, IS50, IS60]
else:
allbds = np.array(["BDS10", "BDS17", "BDS20", "BDS30", "BDS40",
"BDS50", "BDS60"])
mask = [IS10, IS17, IS20, IS30, IS40, IS50, IS60]
bds = ','.join(sorted(allbds[mask]))
if len(bds) == 0:
return None
else:
return bds | [
"def",
"infer",
"(",
"msg",
",",
"mrar",
"=",
"False",
")",
":",
"df",
"=",
"common",
".",
"df",
"(",
"msg",
")",
"if",
"common",
".",
"allzeros",
"(",
"msg",
")",
":",
"return",
"'EMPTY'",
"# For ADS-B / Mode-S extended squitter",
"if",
"df",
"==",
"17",
":",
"tc",
"=",
"common",
".",
"typecode",
"(",
"msg",
")",
"if",
"1",
"<=",
"tc",
"<=",
"4",
":",
"return",
"'BDS08'",
"# indentification and category",
"if",
"5",
"<=",
"tc",
"<=",
"8",
":",
"return",
"'BDS06'",
"# surface movement",
"if",
"9",
"<=",
"tc",
"<=",
"18",
":",
"return",
"'BDS05'",
"# airborne position, baro-alt",
"if",
"tc",
"==",
"19",
":",
"return",
"'BDS09'",
"# airborne velocity",
"if",
"20",
"<=",
"tc",
"<=",
"22",
":",
"return",
"'BDS05'",
"# airborne position, gnss-alt",
"if",
"tc",
"==",
"28",
":",
"return",
"'BDS61'",
"# aircraft status",
"if",
"tc",
"==",
"29",
":",
"return",
"'BDS62'",
"# target state and status",
"if",
"tc",
"==",
"31",
":",
"return",
"'BDS65'",
"# operational status",
"# For Comm-B replies",
"IS10",
"=",
"bds10",
".",
"is10",
"(",
"msg",
")",
"IS17",
"=",
"bds17",
".",
"is17",
"(",
"msg",
")",
"IS20",
"=",
"bds20",
".",
"is20",
"(",
"msg",
")",
"IS30",
"=",
"bds30",
".",
"is30",
"(",
"msg",
")",
"IS40",
"=",
"bds40",
".",
"is40",
"(",
"msg",
")",
"IS50",
"=",
"bds50",
".",
"is50",
"(",
"msg",
")",
"IS60",
"=",
"bds60",
".",
"is60",
"(",
"msg",
")",
"IS44",
"=",
"bds44",
".",
"is44",
"(",
"msg",
")",
"IS45",
"=",
"bds45",
".",
"is45",
"(",
"msg",
")",
"if",
"mrar",
":",
"allbds",
"=",
"np",
".",
"array",
"(",
"[",
"\"BDS10\"",
",",
"\"BDS17\"",
",",
"\"BDS20\"",
",",
"\"BDS30\"",
",",
"\"BDS40\"",
",",
"\"BDS44\"",
",",
"\"BDS45\"",
",",
"\"BDS50\"",
",",
"\"BDS60\"",
"]",
")",
"mask",
"=",
"[",
"IS10",
",",
"IS17",
",",
"IS20",
",",
"IS30",
",",
"IS40",
",",
"IS44",
",",
"IS45",
",",
"IS50",
",",
"IS60",
"]",
"else",
":",
"allbds",
"=",
"np",
".",
"array",
"(",
"[",
"\"BDS10\"",
",",
"\"BDS17\"",
",",
"\"BDS20\"",
",",
"\"BDS30\"",
",",
"\"BDS40\"",
",",
"\"BDS50\"",
",",
"\"BDS60\"",
"]",
")",
"mask",
"=",
"[",
"IS10",
",",
"IS17",
",",
"IS20",
",",
"IS30",
",",
"IS40",
",",
"IS50",
",",
"IS60",
"]",
"bds",
"=",
"','",
".",
"join",
"(",
"sorted",
"(",
"allbds",
"[",
"mask",
"]",
")",
")",
"if",
"len",
"(",
"bds",
")",
"==",
"0",
":",
"return",
"None",
"else",
":",
"return",
"bds"
] | Estimate the most likely BDS code of an message.
Args:
msg (String): 28 bytes hexadecimal message string
mrar (bool): Also infer MRAR (BDS 44) and MHR (BDS 45). Defaults to False.
Returns:
String or None: BDS version, or possible versions, or None if nothing matches. | [
"Estimate",
"the",
"most",
"likely",
"BDS",
"code",
"of",
"an",
"message",
"."
] | 8cd5655a04b08171a9ad5f1ffd232b7e0178ea53 | https://github.com/junzis/pyModeS/blob/8cd5655a04b08171a9ad5f1ffd232b7e0178ea53/pyModeS/decoder/bds/__init__.py#L92-L154 |
248,383 | junzis/pyModeS | pyModeS/decoder/bds/bds40.py | is40 | def is40(msg):
"""Check if a message is likely to be BDS code 4,0
Args:
msg (String): 28 bytes hexadecimal message string
Returns:
bool: True or False
"""
if allzeros(msg):
return False
d = hex2bin(data(msg))
# status bit 1, 14, and 27
if wrongstatus(d, 1, 2, 13):
return False
if wrongstatus(d, 14, 15, 26):
return False
if wrongstatus(d, 27, 28, 39):
return False
if wrongstatus(d, 48, 49, 51):
return False
if wrongstatus(d, 54, 55, 56):
return False
# bits 40-47 and 52-53 shall all be zero
if bin2int(d[39:47]) != 0:
return False
if bin2int(d[51:53]) != 0:
return False
return True | python | def is40(msg):
if allzeros(msg):
return False
d = hex2bin(data(msg))
# status bit 1, 14, and 27
if wrongstatus(d, 1, 2, 13):
return False
if wrongstatus(d, 14, 15, 26):
return False
if wrongstatus(d, 27, 28, 39):
return False
if wrongstatus(d, 48, 49, 51):
return False
if wrongstatus(d, 54, 55, 56):
return False
# bits 40-47 and 52-53 shall all be zero
if bin2int(d[39:47]) != 0:
return False
if bin2int(d[51:53]) != 0:
return False
return True | [
"def",
"is40",
"(",
"msg",
")",
":",
"if",
"allzeros",
"(",
"msg",
")",
":",
"return",
"False",
"d",
"=",
"hex2bin",
"(",
"data",
"(",
"msg",
")",
")",
"# status bit 1, 14, and 27",
"if",
"wrongstatus",
"(",
"d",
",",
"1",
",",
"2",
",",
"13",
")",
":",
"return",
"False",
"if",
"wrongstatus",
"(",
"d",
",",
"14",
",",
"15",
",",
"26",
")",
":",
"return",
"False",
"if",
"wrongstatus",
"(",
"d",
",",
"27",
",",
"28",
",",
"39",
")",
":",
"return",
"False",
"if",
"wrongstatus",
"(",
"d",
",",
"48",
",",
"49",
",",
"51",
")",
":",
"return",
"False",
"if",
"wrongstatus",
"(",
"d",
",",
"54",
",",
"55",
",",
"56",
")",
":",
"return",
"False",
"# bits 40-47 and 52-53 shall all be zero",
"if",
"bin2int",
"(",
"d",
"[",
"39",
":",
"47",
"]",
")",
"!=",
"0",
":",
"return",
"False",
"if",
"bin2int",
"(",
"d",
"[",
"51",
":",
"53",
"]",
")",
"!=",
"0",
":",
"return",
"False",
"return",
"True"
] | Check if a message is likely to be BDS code 4,0
Args:
msg (String): 28 bytes hexadecimal message string
Returns:
bool: True or False | [
"Check",
"if",
"a",
"message",
"is",
"likely",
"to",
"be",
"BDS",
"code",
"4",
"0"
] | 8cd5655a04b08171a9ad5f1ffd232b7e0178ea53 | https://github.com/junzis/pyModeS/blob/8cd5655a04b08171a9ad5f1ffd232b7e0178ea53/pyModeS/decoder/bds/bds40.py#L25-L65 |
248,384 | junzis/pyModeS | pyModeS/decoder/bds/bds40.py | alt40fms | def alt40fms(msg):
"""Selected altitude, FMS
Args:
msg (String): 28 bytes hexadecimal message (BDS40) string
Returns:
int: altitude in feet
"""
d = hex2bin(data(msg))
if d[13] == '0':
return None
alt = bin2int(d[14:26]) * 16 # ft
return alt | python | def alt40fms(msg):
d = hex2bin(data(msg))
if d[13] == '0':
return None
alt = bin2int(d[14:26]) * 16 # ft
return alt | [
"def",
"alt40fms",
"(",
"msg",
")",
":",
"d",
"=",
"hex2bin",
"(",
"data",
"(",
"msg",
")",
")",
"if",
"d",
"[",
"13",
"]",
"==",
"'0'",
":",
"return",
"None",
"alt",
"=",
"bin2int",
"(",
"d",
"[",
"14",
":",
"26",
"]",
")",
"*",
"16",
"# ft",
"return",
"alt"
] | Selected altitude, FMS
Args:
msg (String): 28 bytes hexadecimal message (BDS40) string
Returns:
int: altitude in feet | [
"Selected",
"altitude",
"FMS"
] | 8cd5655a04b08171a9ad5f1ffd232b7e0178ea53 | https://github.com/junzis/pyModeS/blob/8cd5655a04b08171a9ad5f1ffd232b7e0178ea53/pyModeS/decoder/bds/bds40.py#L86-L101 |
248,385 | junzis/pyModeS | pyModeS/decoder/bds/bds40.py | p40baro | def p40baro(msg):
"""Barometric pressure setting
Args:
msg (String): 28 bytes hexadecimal message (BDS40) string
Returns:
float: pressure in millibar
"""
d = hex2bin(data(msg))
if d[26] == '0':
return None
p = bin2int(d[27:39]) * 0.1 + 800 # millibar
return p | python | def p40baro(msg):
d = hex2bin(data(msg))
if d[26] == '0':
return None
p = bin2int(d[27:39]) * 0.1 + 800 # millibar
return p | [
"def",
"p40baro",
"(",
"msg",
")",
":",
"d",
"=",
"hex2bin",
"(",
"data",
"(",
"msg",
")",
")",
"if",
"d",
"[",
"26",
"]",
"==",
"'0'",
":",
"return",
"None",
"p",
"=",
"bin2int",
"(",
"d",
"[",
"27",
":",
"39",
"]",
")",
"*",
"0.1",
"+",
"800",
"# millibar",
"return",
"p"
] | Barometric pressure setting
Args:
msg (String): 28 bytes hexadecimal message (BDS40) string
Returns:
float: pressure in millibar | [
"Barometric",
"pressure",
"setting"
] | 8cd5655a04b08171a9ad5f1ffd232b7e0178ea53 | https://github.com/junzis/pyModeS/blob/8cd5655a04b08171a9ad5f1ffd232b7e0178ea53/pyModeS/decoder/bds/bds40.py#L104-L119 |
248,386 | junzis/pyModeS | pyModeS/decoder/bds/bds44.py | is44 | def is44(msg):
"""Check if a message is likely to be BDS code 4,4.
Meteorological routine air report
Args:
msg (String): 28 bytes hexadecimal message string
Returns:
bool: True or False
"""
if allzeros(msg):
return False
d = hex2bin(data(msg))
# status bit 5, 35, 47, 50
if wrongstatus(d, 5, 6, 23):
return False
if wrongstatus(d, 35, 36, 46):
return False
if wrongstatus(d, 47, 48, 49):
return False
if wrongstatus(d, 50, 51, 56):
return False
# Bits 1-4 indicate source, values > 4 reserved and should not occur
if bin2int(d[0:4]) > 4:
return False
vw = wind44(msg)
if vw is not None and vw[0] > 250:
return False
temp, temp2 = temp44(msg)
if min(temp, temp2) > 60 or max(temp, temp2) < -80:
return False
return True | python | def is44(msg):
if allzeros(msg):
return False
d = hex2bin(data(msg))
# status bit 5, 35, 47, 50
if wrongstatus(d, 5, 6, 23):
return False
if wrongstatus(d, 35, 36, 46):
return False
if wrongstatus(d, 47, 48, 49):
return False
if wrongstatus(d, 50, 51, 56):
return False
# Bits 1-4 indicate source, values > 4 reserved and should not occur
if bin2int(d[0:4]) > 4:
return False
vw = wind44(msg)
if vw is not None and vw[0] > 250:
return False
temp, temp2 = temp44(msg)
if min(temp, temp2) > 60 or max(temp, temp2) < -80:
return False
return True | [
"def",
"is44",
"(",
"msg",
")",
":",
"if",
"allzeros",
"(",
"msg",
")",
":",
"return",
"False",
"d",
"=",
"hex2bin",
"(",
"data",
"(",
"msg",
")",
")",
"# status bit 5, 35, 47, 50",
"if",
"wrongstatus",
"(",
"d",
",",
"5",
",",
"6",
",",
"23",
")",
":",
"return",
"False",
"if",
"wrongstatus",
"(",
"d",
",",
"35",
",",
"36",
",",
"46",
")",
":",
"return",
"False",
"if",
"wrongstatus",
"(",
"d",
",",
"47",
",",
"48",
",",
"49",
")",
":",
"return",
"False",
"if",
"wrongstatus",
"(",
"d",
",",
"50",
",",
"51",
",",
"56",
")",
":",
"return",
"False",
"# Bits 1-4 indicate source, values > 4 reserved and should not occur",
"if",
"bin2int",
"(",
"d",
"[",
"0",
":",
"4",
"]",
")",
">",
"4",
":",
"return",
"False",
"vw",
"=",
"wind44",
"(",
"msg",
")",
"if",
"vw",
"is",
"not",
"None",
"and",
"vw",
"[",
"0",
"]",
">",
"250",
":",
"return",
"False",
"temp",
",",
"temp2",
"=",
"temp44",
"(",
"msg",
")",
"if",
"min",
"(",
"temp",
",",
"temp2",
")",
">",
"60",
"or",
"max",
"(",
"temp",
",",
"temp2",
")",
"<",
"-",
"80",
":",
"return",
"False",
"return",
"True"
] | Check if a message is likely to be BDS code 4,4.
Meteorological routine air report
Args:
msg (String): 28 bytes hexadecimal message string
Returns:
bool: True or False | [
"Check",
"if",
"a",
"message",
"is",
"likely",
"to",
"be",
"BDS",
"code",
"4",
"4",
"."
] | 8cd5655a04b08171a9ad5f1ffd232b7e0178ea53 | https://github.com/junzis/pyModeS/blob/8cd5655a04b08171a9ad5f1ffd232b7e0178ea53/pyModeS/decoder/bds/bds44.py#L25-L67 |
248,387 | junzis/pyModeS | pyModeS/decoder/bds/bds44.py | wind44 | def wind44(msg):
"""Wind speed and direction.
Args:
msg (String): 28 bytes hexadecimal message string
Returns:
(int, float): speed (kt), direction (degree)
"""
d = hex2bin(data(msg))
status = int(d[4])
if not status:
return None
speed = bin2int(d[5:14]) # knots
direction = bin2int(d[14:23]) * 180.0 / 256.0 # degree
return round(speed, 0), round(direction, 1) | python | def wind44(msg):
d = hex2bin(data(msg))
status = int(d[4])
if not status:
return None
speed = bin2int(d[5:14]) # knots
direction = bin2int(d[14:23]) * 180.0 / 256.0 # degree
return round(speed, 0), round(direction, 1) | [
"def",
"wind44",
"(",
"msg",
")",
":",
"d",
"=",
"hex2bin",
"(",
"data",
"(",
"msg",
")",
")",
"status",
"=",
"int",
"(",
"d",
"[",
"4",
"]",
")",
"if",
"not",
"status",
":",
"return",
"None",
"speed",
"=",
"bin2int",
"(",
"d",
"[",
"5",
":",
"14",
"]",
")",
"# knots",
"direction",
"=",
"bin2int",
"(",
"d",
"[",
"14",
":",
"23",
"]",
")",
"*",
"180.0",
"/",
"256.0",
"# degree",
"return",
"round",
"(",
"speed",
",",
"0",
")",
",",
"round",
"(",
"direction",
",",
"1",
")"
] | Wind speed and direction.
Args:
msg (String): 28 bytes hexadecimal message string
Returns:
(int, float): speed (kt), direction (degree) | [
"Wind",
"speed",
"and",
"direction",
"."
] | 8cd5655a04b08171a9ad5f1ffd232b7e0178ea53 | https://github.com/junzis/pyModeS/blob/8cd5655a04b08171a9ad5f1ffd232b7e0178ea53/pyModeS/decoder/bds/bds44.py#L70-L89 |
248,388 | junzis/pyModeS | pyModeS/decoder/bds/bds44.py | p44 | def p44(msg):
"""Static pressure.
Args:
msg (String): 28 bytes hexadecimal message string
Returns:
int: static pressure in hPa
"""
d = hex2bin(data(msg))
if d[34] == '0':
return None
p = bin2int(d[35:46]) # hPa
return p | python | def p44(msg):
d = hex2bin(data(msg))
if d[34] == '0':
return None
p = bin2int(d[35:46]) # hPa
return p | [
"def",
"p44",
"(",
"msg",
")",
":",
"d",
"=",
"hex2bin",
"(",
"data",
"(",
"msg",
")",
")",
"if",
"d",
"[",
"34",
"]",
"==",
"'0'",
":",
"return",
"None",
"p",
"=",
"bin2int",
"(",
"d",
"[",
"35",
":",
"46",
"]",
")",
"# hPa",
"return",
"p"
] | Static pressure.
Args:
msg (String): 28 bytes hexadecimal message string
Returns:
int: static pressure in hPa | [
"Static",
"pressure",
"."
] | 8cd5655a04b08171a9ad5f1ffd232b7e0178ea53 | https://github.com/junzis/pyModeS/blob/8cd5655a04b08171a9ad5f1ffd232b7e0178ea53/pyModeS/decoder/bds/bds44.py#L121-L138 |
248,389 | junzis/pyModeS | pyModeS/decoder/bds/bds60.py | is60 | def is60(msg):
"""Check if a message is likely to be BDS code 6,0
Args:
msg (String): 28 bytes hexadecimal message string
Returns:
bool: True or False
"""
if allzeros(msg):
return False
d = hex2bin(data(msg))
# status bit 1, 13, 24, 35, 46
if wrongstatus(d, 1, 2, 12):
return False
if wrongstatus(d, 13, 14, 23):
return False
if wrongstatus(d, 24, 25, 34):
return False
if wrongstatus(d, 35, 36, 45):
return False
if wrongstatus(d, 46, 47, 56):
return False
ias = ias60(msg)
if ias is not None and ias > 500:
return False
mach = mach60(msg)
if mach is not None and mach > 1:
return False
vr_baro = vr60baro(msg)
if vr_baro is not None and abs(vr_baro) > 6000:
return False
vr_ins = vr60ins(msg)
if vr_ins is not None and abs(vr_ins) > 6000:
return False
return True | python | def is60(msg):
if allzeros(msg):
return False
d = hex2bin(data(msg))
# status bit 1, 13, 24, 35, 46
if wrongstatus(d, 1, 2, 12):
return False
if wrongstatus(d, 13, 14, 23):
return False
if wrongstatus(d, 24, 25, 34):
return False
if wrongstatus(d, 35, 36, 45):
return False
if wrongstatus(d, 46, 47, 56):
return False
ias = ias60(msg)
if ias is not None and ias > 500:
return False
mach = mach60(msg)
if mach is not None and mach > 1:
return False
vr_baro = vr60baro(msg)
if vr_baro is not None and abs(vr_baro) > 6000:
return False
vr_ins = vr60ins(msg)
if vr_ins is not None and abs(vr_ins) > 6000:
return False
return True | [
"def",
"is60",
"(",
"msg",
")",
":",
"if",
"allzeros",
"(",
"msg",
")",
":",
"return",
"False",
"d",
"=",
"hex2bin",
"(",
"data",
"(",
"msg",
")",
")",
"# status bit 1, 13, 24, 35, 46",
"if",
"wrongstatus",
"(",
"d",
",",
"1",
",",
"2",
",",
"12",
")",
":",
"return",
"False",
"if",
"wrongstatus",
"(",
"d",
",",
"13",
",",
"14",
",",
"23",
")",
":",
"return",
"False",
"if",
"wrongstatus",
"(",
"d",
",",
"24",
",",
"25",
",",
"34",
")",
":",
"return",
"False",
"if",
"wrongstatus",
"(",
"d",
",",
"35",
",",
"36",
",",
"45",
")",
":",
"return",
"False",
"if",
"wrongstatus",
"(",
"d",
",",
"46",
",",
"47",
",",
"56",
")",
":",
"return",
"False",
"ias",
"=",
"ias60",
"(",
"msg",
")",
"if",
"ias",
"is",
"not",
"None",
"and",
"ias",
">",
"500",
":",
"return",
"False",
"mach",
"=",
"mach60",
"(",
"msg",
")",
"if",
"mach",
"is",
"not",
"None",
"and",
"mach",
">",
"1",
":",
"return",
"False",
"vr_baro",
"=",
"vr60baro",
"(",
"msg",
")",
"if",
"vr_baro",
"is",
"not",
"None",
"and",
"abs",
"(",
"vr_baro",
")",
">",
"6000",
":",
"return",
"False",
"vr_ins",
"=",
"vr60ins",
"(",
"msg",
")",
"if",
"vr_ins",
"is",
"not",
"None",
"and",
"abs",
"(",
"vr_ins",
")",
">",
"6000",
":",
"return",
"False",
"return",
"True"
] | Check if a message is likely to be BDS code 6,0
Args:
msg (String): 28 bytes hexadecimal message string
Returns:
bool: True or False | [
"Check",
"if",
"a",
"message",
"is",
"likely",
"to",
"be",
"BDS",
"code",
"6",
"0"
] | 8cd5655a04b08171a9ad5f1ffd232b7e0178ea53 | https://github.com/junzis/pyModeS/blob/8cd5655a04b08171a9ad5f1ffd232b7e0178ea53/pyModeS/decoder/bds/bds60.py#L24-L72 |
248,390 | junzis/pyModeS | pyModeS/decoder/bds/bds60.py | hdg60 | def hdg60(msg):
"""Megnetic heading of aircraft
Args:
msg (String): 28 bytes hexadecimal message (BDS60) string
Returns:
float: heading in degrees to megnetic north (from 0 to 360)
"""
d = hex2bin(data(msg))
if d[0] == '0':
return None
sign = int(d[1]) # 1 -> west
value = bin2int(d[2:12])
if sign:
value = value - 1024
hdg = value * 90 / 512.0 # degree
# convert from [-180, 180] to [0, 360]
if hdg < 0:
hdg = 360 + hdg
return round(hdg, 3) | python | def hdg60(msg):
d = hex2bin(data(msg))
if d[0] == '0':
return None
sign = int(d[1]) # 1 -> west
value = bin2int(d[2:12])
if sign:
value = value - 1024
hdg = value * 90 / 512.0 # degree
# convert from [-180, 180] to [0, 360]
if hdg < 0:
hdg = 360 + hdg
return round(hdg, 3) | [
"def",
"hdg60",
"(",
"msg",
")",
":",
"d",
"=",
"hex2bin",
"(",
"data",
"(",
"msg",
")",
")",
"if",
"d",
"[",
"0",
"]",
"==",
"'0'",
":",
"return",
"None",
"sign",
"=",
"int",
"(",
"d",
"[",
"1",
"]",
")",
"# 1 -> west",
"value",
"=",
"bin2int",
"(",
"d",
"[",
"2",
":",
"12",
"]",
")",
"if",
"sign",
":",
"value",
"=",
"value",
"-",
"1024",
"hdg",
"=",
"value",
"*",
"90",
"/",
"512.0",
"# degree",
"# convert from [-180, 180] to [0, 360]",
"if",
"hdg",
"<",
"0",
":",
"hdg",
"=",
"360",
"+",
"hdg",
"return",
"round",
"(",
"hdg",
",",
"3",
")"
] | Megnetic heading of aircraft
Args:
msg (String): 28 bytes hexadecimal message (BDS60) string
Returns:
float: heading in degrees to megnetic north (from 0 to 360) | [
"Megnetic",
"heading",
"of",
"aircraft"
] | 8cd5655a04b08171a9ad5f1ffd232b7e0178ea53 | https://github.com/junzis/pyModeS/blob/8cd5655a04b08171a9ad5f1ffd232b7e0178ea53/pyModeS/decoder/bds/bds60.py#L75-L101 |
248,391 | junzis/pyModeS | pyModeS/decoder/bds/bds60.py | mach60 | def mach60(msg):
"""Aircraft MACH number
Args:
msg (String): 28 bytes hexadecimal message (BDS60) string
Returns:
float: MACH number
"""
d = hex2bin(data(msg))
if d[23] == '0':
return None
mach = bin2int(d[24:34]) * 2.048 / 512.0
return round(mach, 3) | python | def mach60(msg):
d = hex2bin(data(msg))
if d[23] == '0':
return None
mach = bin2int(d[24:34]) * 2.048 / 512.0
return round(mach, 3) | [
"def",
"mach60",
"(",
"msg",
")",
":",
"d",
"=",
"hex2bin",
"(",
"data",
"(",
"msg",
")",
")",
"if",
"d",
"[",
"23",
"]",
"==",
"'0'",
":",
"return",
"None",
"mach",
"=",
"bin2int",
"(",
"d",
"[",
"24",
":",
"34",
"]",
")",
"*",
"2.048",
"/",
"512.0",
"return",
"round",
"(",
"mach",
",",
"3",
")"
] | Aircraft MACH number
Args:
msg (String): 28 bytes hexadecimal message (BDS60) string
Returns:
float: MACH number | [
"Aircraft",
"MACH",
"number"
] | 8cd5655a04b08171a9ad5f1ffd232b7e0178ea53 | https://github.com/junzis/pyModeS/blob/8cd5655a04b08171a9ad5f1ffd232b7e0178ea53/pyModeS/decoder/bds/bds60.py#L122-L137 |
248,392 | junzis/pyModeS | pyModeS/decoder/bds/bds60.py | vr60baro | def vr60baro(msg):
"""Vertical rate from barometric measurement, this value may be very noisy.
Args:
msg (String): 28 bytes hexadecimal message (BDS60) string
Returns:
int: vertical rate in feet/minutes
"""
d = hex2bin(data(msg))
if d[34] == '0':
return None
sign = int(d[35]) # 1 -> negative value, two's complement
value = bin2int(d[36:45])
if value == 0 or value == 511: # all zeros or all ones
return 0
value = value - 512 if sign else value
roc = value * 32 # feet/min
return roc | python | def vr60baro(msg):
d = hex2bin(data(msg))
if d[34] == '0':
return None
sign = int(d[35]) # 1 -> negative value, two's complement
value = bin2int(d[36:45])
if value == 0 or value == 511: # all zeros or all ones
return 0
value = value - 512 if sign else value
roc = value * 32 # feet/min
return roc | [
"def",
"vr60baro",
"(",
"msg",
")",
":",
"d",
"=",
"hex2bin",
"(",
"data",
"(",
"msg",
")",
")",
"if",
"d",
"[",
"34",
"]",
"==",
"'0'",
":",
"return",
"None",
"sign",
"=",
"int",
"(",
"d",
"[",
"35",
"]",
")",
"# 1 -> negative value, two's complement",
"value",
"=",
"bin2int",
"(",
"d",
"[",
"36",
":",
"45",
"]",
")",
"if",
"value",
"==",
"0",
"or",
"value",
"==",
"511",
":",
"# all zeros or all ones",
"return",
"0",
"value",
"=",
"value",
"-",
"512",
"if",
"sign",
"else",
"value",
"roc",
"=",
"value",
"*",
"32",
"# feet/min",
"return",
"roc"
] | Vertical rate from barometric measurement, this value may be very noisy.
Args:
msg (String): 28 bytes hexadecimal message (BDS60) string
Returns:
int: vertical rate in feet/minutes | [
"Vertical",
"rate",
"from",
"barometric",
"measurement",
"this",
"value",
"may",
"be",
"very",
"noisy",
"."
] | 8cd5655a04b08171a9ad5f1ffd232b7e0178ea53 | https://github.com/junzis/pyModeS/blob/8cd5655a04b08171a9ad5f1ffd232b7e0178ea53/pyModeS/decoder/bds/bds60.py#L140-L163 |
248,393 | junzis/pyModeS | pyModeS/decoder/bds/bds45.py | is45 | def is45(msg):
"""Check if a message is likely to be BDS code 4,5.
Meteorological hazard report
Args:
msg (String): 28 bytes hexadecimal message string
Returns:
bool: True or False
"""
if allzeros(msg):
return False
d = hex2bin(data(msg))
# status bit 1, 4, 7, 10, 13, 16, 27, 39
if wrongstatus(d, 1, 2, 3):
return False
if wrongstatus(d, 4, 5, 6):
return False
if wrongstatus(d, 7, 8, 9):
return False
if wrongstatus(d, 10, 11, 12):
return False
if wrongstatus(d, 13, 14, 15):
return False
if wrongstatus(d, 16, 17, 26):
return False
if wrongstatus(d, 27, 28, 38):
return False
if wrongstatus(d, 39, 40, 51):
return False
# reserved
if bin2int(d[51:56]) != 0:
return False
temp = temp45(msg)
if temp:
if temp > 60 or temp < -80:
return False
return True | python | def is45(msg):
if allzeros(msg):
return False
d = hex2bin(data(msg))
# status bit 1, 4, 7, 10, 13, 16, 27, 39
if wrongstatus(d, 1, 2, 3):
return False
if wrongstatus(d, 4, 5, 6):
return False
if wrongstatus(d, 7, 8, 9):
return False
if wrongstatus(d, 10, 11, 12):
return False
if wrongstatus(d, 13, 14, 15):
return False
if wrongstatus(d, 16, 17, 26):
return False
if wrongstatus(d, 27, 28, 38):
return False
if wrongstatus(d, 39, 40, 51):
return False
# reserved
if bin2int(d[51:56]) != 0:
return False
temp = temp45(msg)
if temp:
if temp > 60 or temp < -80:
return False
return True | [
"def",
"is45",
"(",
"msg",
")",
":",
"if",
"allzeros",
"(",
"msg",
")",
":",
"return",
"False",
"d",
"=",
"hex2bin",
"(",
"data",
"(",
"msg",
")",
")",
"# status bit 1, 4, 7, 10, 13, 16, 27, 39",
"if",
"wrongstatus",
"(",
"d",
",",
"1",
",",
"2",
",",
"3",
")",
":",
"return",
"False",
"if",
"wrongstatus",
"(",
"d",
",",
"4",
",",
"5",
",",
"6",
")",
":",
"return",
"False",
"if",
"wrongstatus",
"(",
"d",
",",
"7",
",",
"8",
",",
"9",
")",
":",
"return",
"False",
"if",
"wrongstatus",
"(",
"d",
",",
"10",
",",
"11",
",",
"12",
")",
":",
"return",
"False",
"if",
"wrongstatus",
"(",
"d",
",",
"13",
",",
"14",
",",
"15",
")",
":",
"return",
"False",
"if",
"wrongstatus",
"(",
"d",
",",
"16",
",",
"17",
",",
"26",
")",
":",
"return",
"False",
"if",
"wrongstatus",
"(",
"d",
",",
"27",
",",
"28",
",",
"38",
")",
":",
"return",
"False",
"if",
"wrongstatus",
"(",
"d",
",",
"39",
",",
"40",
",",
"51",
")",
":",
"return",
"False",
"# reserved",
"if",
"bin2int",
"(",
"d",
"[",
"51",
":",
"56",
"]",
")",
"!=",
"0",
":",
"return",
"False",
"temp",
"=",
"temp45",
"(",
"msg",
")",
"if",
"temp",
":",
"if",
"temp",
">",
"60",
"or",
"temp",
"<",
"-",
"80",
":",
"return",
"False",
"return",
"True"
] | Check if a message is likely to be BDS code 4,5.
Meteorological hazard report
Args:
msg (String): 28 bytes hexadecimal message string
Returns:
bool: True or False | [
"Check",
"if",
"a",
"message",
"is",
"likely",
"to",
"be",
"BDS",
"code",
"4",
"5",
"."
] | 8cd5655a04b08171a9ad5f1ffd232b7e0178ea53 | https://github.com/junzis/pyModeS/blob/8cd5655a04b08171a9ad5f1ffd232b7e0178ea53/pyModeS/decoder/bds/bds45.py#L25-L76 |
248,394 | junzis/pyModeS | pyModeS/decoder/bds/bds45.py | ws45 | def ws45(msg):
"""Wind shear.
Args:
msg (String): 28 bytes hexadecimal message string
Returns:
int: Wind shear level. 0=NIL, 1=Light, 2=Moderate, 3=Severe
"""
d = hex2bin(data(msg))
if d[3] == '0':
return None
ws = bin2int(d[4:6])
return ws | python | def ws45(msg):
d = hex2bin(data(msg))
if d[3] == '0':
return None
ws = bin2int(d[4:6])
return ws | [
"def",
"ws45",
"(",
"msg",
")",
":",
"d",
"=",
"hex2bin",
"(",
"data",
"(",
"msg",
")",
")",
"if",
"d",
"[",
"3",
"]",
"==",
"'0'",
":",
"return",
"None",
"ws",
"=",
"bin2int",
"(",
"d",
"[",
"4",
":",
"6",
"]",
")",
"return",
"ws"
] | Wind shear.
Args:
msg (String): 28 bytes hexadecimal message string
Returns:
int: Wind shear level. 0=NIL, 1=Light, 2=Moderate, 3=Severe | [
"Wind",
"shear",
"."
] | 8cd5655a04b08171a9ad5f1ffd232b7e0178ea53 | https://github.com/junzis/pyModeS/blob/8cd5655a04b08171a9ad5f1ffd232b7e0178ea53/pyModeS/decoder/bds/bds45.py#L97-L112 |
248,395 | junzis/pyModeS | pyModeS/decoder/bds/bds45.py | wv45 | def wv45(msg):
"""Wake vortex.
Args:
msg (String): 28 bytes hexadecimal message string
Returns:
int: Wake vortex level. 0=NIL, 1=Light, 2=Moderate, 3=Severe
"""
d = hex2bin(data(msg))
if d[12] == '0':
return None
ws = bin2int(d[13:15])
return ws | python | def wv45(msg):
d = hex2bin(data(msg))
if d[12] == '0':
return None
ws = bin2int(d[13:15])
return ws | [
"def",
"wv45",
"(",
"msg",
")",
":",
"d",
"=",
"hex2bin",
"(",
"data",
"(",
"msg",
")",
")",
"if",
"d",
"[",
"12",
"]",
"==",
"'0'",
":",
"return",
"None",
"ws",
"=",
"bin2int",
"(",
"d",
"[",
"13",
":",
"15",
"]",
")",
"return",
"ws"
] | Wake vortex.
Args:
msg (String): 28 bytes hexadecimal message string
Returns:
int: Wake vortex level. 0=NIL, 1=Light, 2=Moderate, 3=Severe | [
"Wake",
"vortex",
"."
] | 8cd5655a04b08171a9ad5f1ffd232b7e0178ea53 | https://github.com/junzis/pyModeS/blob/8cd5655a04b08171a9ad5f1ffd232b7e0178ea53/pyModeS/decoder/bds/bds45.py#L151-L166 |
248,396 | junzis/pyModeS | pyModeS/decoder/bds/bds45.py | p45 | def p45(msg):
"""Average static pressure.
Args:
msg (String): 28 bytes hexadecimal message string
Returns:
int: static pressure in hPa
"""
d = hex2bin(data(msg))
if d[26] == '0':
return None
p = bin2int(d[27:38]) # hPa
return p | python | def p45(msg):
d = hex2bin(data(msg))
if d[26] == '0':
return None
p = bin2int(d[27:38]) # hPa
return p | [
"def",
"p45",
"(",
"msg",
")",
":",
"d",
"=",
"hex2bin",
"(",
"data",
"(",
"msg",
")",
")",
"if",
"d",
"[",
"26",
"]",
"==",
"'0'",
":",
"return",
"None",
"p",
"=",
"bin2int",
"(",
"d",
"[",
"27",
":",
"38",
"]",
")",
"# hPa",
"return",
"p"
] | Average static pressure.
Args:
msg (String): 28 bytes hexadecimal message string
Returns:
int: static pressure in hPa | [
"Average",
"static",
"pressure",
"."
] | 8cd5655a04b08171a9ad5f1ffd232b7e0178ea53 | https://github.com/junzis/pyModeS/blob/8cd5655a04b08171a9ad5f1ffd232b7e0178ea53/pyModeS/decoder/bds/bds45.py#L193-L207 |
248,397 | junzis/pyModeS | pyModeS/decoder/bds/bds45.py | rh45 | def rh45(msg):
"""Radio height.
Args:
msg (String): 28 bytes hexadecimal message string
Returns:
int: radio height in ft
"""
d = hex2bin(data(msg))
if d[38] == '0':
return None
rh = bin2int(d[39:51]) * 16
return rh | python | def rh45(msg):
d = hex2bin(data(msg))
if d[38] == '0':
return None
rh = bin2int(d[39:51]) * 16
return rh | [
"def",
"rh45",
"(",
"msg",
")",
":",
"d",
"=",
"hex2bin",
"(",
"data",
"(",
"msg",
")",
")",
"if",
"d",
"[",
"38",
"]",
"==",
"'0'",
":",
"return",
"None",
"rh",
"=",
"bin2int",
"(",
"d",
"[",
"39",
":",
"51",
"]",
")",
"*",
"16",
"return",
"rh"
] | Radio height.
Args:
msg (String): 28 bytes hexadecimal message string
Returns:
int: radio height in ft | [
"Radio",
"height",
"."
] | 8cd5655a04b08171a9ad5f1ffd232b7e0178ea53 | https://github.com/junzis/pyModeS/blob/8cd5655a04b08171a9ad5f1ffd232b7e0178ea53/pyModeS/decoder/bds/bds45.py#L210-L224 |
248,398 | junzis/pyModeS | pyModeS/extra/aero.py | vsound | def vsound(H):
"""Speed of sound"""
T = temperature(H)
a = np.sqrt(gamma * R * T)
return a | python | def vsound(H):
T = temperature(H)
a = np.sqrt(gamma * R * T)
return a | [
"def",
"vsound",
"(",
"H",
")",
":",
"T",
"=",
"temperature",
"(",
"H",
")",
"a",
"=",
"np",
".",
"sqrt",
"(",
"gamma",
"*",
"R",
"*",
"T",
")",
"return",
"a"
] | Speed of sound | [
"Speed",
"of",
"sound"
] | 8cd5655a04b08171a9ad5f1ffd232b7e0178ea53 | https://github.com/junzis/pyModeS/blob/8cd5655a04b08171a9ad5f1ffd232b7e0178ea53/pyModeS/extra/aero.py#L78-L82 |
248,399 | junzis/pyModeS | pyModeS/extra/aero.py | distance | def distance(lat1, lon1, lat2, lon2, H=0):
"""
Compute spherical distance from spherical coordinates.
For two locations in spherical coordinates
(1, theta, phi) and (1, theta', phi')
cosine( arc length ) =
sin phi sin phi' cos(theta-theta') + cos phi cos phi'
distance = rho * arc length
"""
# phi = 90 - latitude
phi1 = np.radians(90.0 - lat1)
phi2 = np.radians(90.0 - lat2)
# theta = longitude
theta1 = np.radians(lon1)
theta2 = np.radians(lon2)
cos = np.sin(phi1) * np.sin(phi2) * np.cos(theta1 - theta2) + np.cos(phi1) * np.cos(phi2)
cos = np.where(cos>1, 1, cos)
arc = np.arccos(cos)
dist = arc * (r_earth + H) # meters, radius of earth
return dist | python | def distance(lat1, lon1, lat2, lon2, H=0):
# phi = 90 - latitude
phi1 = np.radians(90.0 - lat1)
phi2 = np.radians(90.0 - lat2)
# theta = longitude
theta1 = np.radians(lon1)
theta2 = np.radians(lon2)
cos = np.sin(phi1) * np.sin(phi2) * np.cos(theta1 - theta2) + np.cos(phi1) * np.cos(phi2)
cos = np.where(cos>1, 1, cos)
arc = np.arccos(cos)
dist = arc * (r_earth + H) # meters, radius of earth
return dist | [
"def",
"distance",
"(",
"lat1",
",",
"lon1",
",",
"lat2",
",",
"lon2",
",",
"H",
"=",
"0",
")",
":",
"# phi = 90 - latitude",
"phi1",
"=",
"np",
".",
"radians",
"(",
"90.0",
"-",
"lat1",
")",
"phi2",
"=",
"np",
".",
"radians",
"(",
"90.0",
"-",
"lat2",
")",
"# theta = longitude",
"theta1",
"=",
"np",
".",
"radians",
"(",
"lon1",
")",
"theta2",
"=",
"np",
".",
"radians",
"(",
"lon2",
")",
"cos",
"=",
"np",
".",
"sin",
"(",
"phi1",
")",
"*",
"np",
".",
"sin",
"(",
"phi2",
")",
"*",
"np",
".",
"cos",
"(",
"theta1",
"-",
"theta2",
")",
"+",
"np",
".",
"cos",
"(",
"phi1",
")",
"*",
"np",
".",
"cos",
"(",
"phi2",
")",
"cos",
"=",
"np",
".",
"where",
"(",
"cos",
">",
"1",
",",
"1",
",",
"cos",
")",
"arc",
"=",
"np",
".",
"arccos",
"(",
"cos",
")",
"dist",
"=",
"arc",
"*",
"(",
"r_earth",
"+",
"H",
")",
"# meters, radius of earth",
"return",
"dist"
] | Compute spherical distance from spherical coordinates.
For two locations in spherical coordinates
(1, theta, phi) and (1, theta', phi')
cosine( arc length ) =
sin phi sin phi' cos(theta-theta') + cos phi cos phi'
distance = rho * arc length | [
"Compute",
"spherical",
"distance",
"from",
"spherical",
"coordinates",
"."
] | 8cd5655a04b08171a9ad5f1ffd232b7e0178ea53 | https://github.com/junzis/pyModeS/blob/8cd5655a04b08171a9ad5f1ffd232b7e0178ea53/pyModeS/extra/aero.py#L85-L109 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.