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
75
19.8k
code_tokens
sequence
docstring
stringlengths
3
17.3k
docstring_tokens
sequence
sha
stringlengths
40
40
url
stringlengths
87
242
4,100
MozillaSecurity/laniakea
laniakea/core/providers/packet/manager.py
PacketManager.filter
def filter(criterias, devices): # pylint: disable=too-many-branches """Filter a device by criterias on the root level of the dictionary. """ if not criterias: return devices result = [] for device in devices: # pylint: disable=too-many-nested-blocks for criteria_name, criteria_values in criterias.items(): if criteria_name in device.keys(): if isinstance(device[criteria_name], list): for criteria_value in criteria_values: if criteria_value in device[criteria_name]: result.append(device) break elif isinstance(device[criteria_name], str): for criteria_value in criteria_values: if criteria_value == device[criteria_name]: result.append(device) elif isinstance(device[criteria_name], int): for criteria_value in criteria_values: if criteria_value == device[criteria_name]: result.append(device) else: continue return result
python
def filter(criterias, devices): # pylint: disable=too-many-branches """Filter a device by criterias on the root level of the dictionary. """ if not criterias: return devices result = [] for device in devices: # pylint: disable=too-many-nested-blocks for criteria_name, criteria_values in criterias.items(): if criteria_name in device.keys(): if isinstance(device[criteria_name], list): for criteria_value in criteria_values: if criteria_value in device[criteria_name]: result.append(device) break elif isinstance(device[criteria_name], str): for criteria_value in criteria_values: if criteria_value == device[criteria_name]: result.append(device) elif isinstance(device[criteria_name], int): for criteria_value in criteria_values: if criteria_value == device[criteria_name]: result.append(device) else: continue return result
[ "def", "filter", "(", "criterias", ",", "devices", ")", ":", "# pylint: disable=too-many-branches", "if", "not", "criterias", ":", "return", "devices", "result", "=", "[", "]", "for", "device", "in", "devices", ":", "# pylint: disable=too-many-nested-blocks", "for", "criteria_name", ",", "criteria_values", "in", "criterias", ".", "items", "(", ")", ":", "if", "criteria_name", "in", "device", ".", "keys", "(", ")", ":", "if", "isinstance", "(", "device", "[", "criteria_name", "]", ",", "list", ")", ":", "for", "criteria_value", "in", "criteria_values", ":", "if", "criteria_value", "in", "device", "[", "criteria_name", "]", ":", "result", ".", "append", "(", "device", ")", "break", "elif", "isinstance", "(", "device", "[", "criteria_name", "]", ",", "str", ")", ":", "for", "criteria_value", "in", "criteria_values", ":", "if", "criteria_value", "==", "device", "[", "criteria_name", "]", ":", "result", ".", "append", "(", "device", ")", "elif", "isinstance", "(", "device", "[", "criteria_name", "]", ",", "int", ")", ":", "for", "criteria_value", "in", "criteria_values", ":", "if", "criteria_value", "==", "device", "[", "criteria_name", "]", ":", "result", ".", "append", "(", "device", ")", "else", ":", "continue", "return", "result" ]
Filter a device by criterias on the root level of the dictionary.
[ "Filter", "a", "device", "by", "criterias", "on", "the", "root", "level", "of", "the", "dictionary", "." ]
7e80adc6ae92c6c1332d4c08473bb271fb3b6833
https://github.com/MozillaSecurity/laniakea/blob/7e80adc6ae92c6c1332d4c08473bb271fb3b6833/laniakea/core/providers/packet/manager.py#L159-L183
4,101
MozillaSecurity/laniakea
laniakea/core/providers/packet/manager.py
PacketManager.get_public_ip
def get_public_ip(addresses, version=4): """Return either the devices public IPv4 or IPv6 address. """ for addr in addresses: if addr['public'] and addr['address_family'] == version: return addr.get('address') return None
python
def get_public_ip(addresses, version=4): """Return either the devices public IPv4 or IPv6 address. """ for addr in addresses: if addr['public'] and addr['address_family'] == version: return addr.get('address') return None
[ "def", "get_public_ip", "(", "addresses", ",", "version", "=", "4", ")", ":", "for", "addr", "in", "addresses", ":", "if", "addr", "[", "'public'", "]", "and", "addr", "[", "'address_family'", "]", "==", "version", ":", "return", "addr", ".", "get", "(", "'address'", ")", "return", "None" ]
Return either the devices public IPv4 or IPv6 address.
[ "Return", "either", "the", "devices", "public", "IPv4", "or", "IPv6", "address", "." ]
7e80adc6ae92c6c1332d4c08473bb271fb3b6833
https://github.com/MozillaSecurity/laniakea/blob/7e80adc6ae92c6c1332d4c08473bb271fb3b6833/laniakea/core/providers/packet/manager.py#L192-L198
4,102
MozillaSecurity/laniakea
laniakea/core/providers/packet/manager.py
PacketManager.validate_capacity
def validate_capacity(self, servers): """Validates if a deploy can be fulfilled. """ try: return self.manager.validate_capacity(servers) except packet.baseapi.Error as msg: raise PacketManagerException(msg)
python
def validate_capacity(self, servers): """Validates if a deploy can be fulfilled. """ try: return self.manager.validate_capacity(servers) except packet.baseapi.Error as msg: raise PacketManagerException(msg)
[ "def", "validate_capacity", "(", "self", ",", "servers", ")", ":", "try", ":", "return", "self", ".", "manager", ".", "validate_capacity", "(", "servers", ")", "except", "packet", ".", "baseapi", ".", "Error", "as", "msg", ":", "raise", "PacketManagerException", "(", "msg", ")" ]
Validates if a deploy can be fulfilled.
[ "Validates", "if", "a", "deploy", "can", "be", "fulfilled", "." ]
7e80adc6ae92c6c1332d4c08473bb271fb3b6833
https://github.com/MozillaSecurity/laniakea/blob/7e80adc6ae92c6c1332d4c08473bb271fb3b6833/laniakea/core/providers/packet/manager.py#L200-L206
4,103
MozillaSecurity/laniakea
laniakea/core/providers/packet/manager.py
PacketManager.create_volume
def create_volume(self, project_id, plan, size, facility, label=""): """Creates a new volume. """ try: return self.manager.create_volume(project_id, label, plan, size, facility) except packet.baseapi.Error as msg: raise PacketManagerException(msg)
python
def create_volume(self, project_id, plan, size, facility, label=""): """Creates a new volume. """ try: return self.manager.create_volume(project_id, label, plan, size, facility) except packet.baseapi.Error as msg: raise PacketManagerException(msg)
[ "def", "create_volume", "(", "self", ",", "project_id", ",", "plan", ",", "size", ",", "facility", ",", "label", "=", "\"\"", ")", ":", "try", ":", "return", "self", ".", "manager", ".", "create_volume", "(", "project_id", ",", "label", ",", "plan", ",", "size", ",", "facility", ")", "except", "packet", ".", "baseapi", ".", "Error", "as", "msg", ":", "raise", "PacketManagerException", "(", "msg", ")" ]
Creates a new volume.
[ "Creates", "a", "new", "volume", "." ]
7e80adc6ae92c6c1332d4c08473bb271fb3b6833
https://github.com/MozillaSecurity/laniakea/blob/7e80adc6ae92c6c1332d4c08473bb271fb3b6833/laniakea/core/providers/packet/manager.py#L208-L214
4,104
MozillaSecurity/laniakea
laniakea/core/providers/packet/manager.py
PacketManager.attach_volume_to_device
def attach_volume_to_device(self, volume_id, device_id): """Attaches the created Volume to a Device. """ try: volume = self.manager.get_volume(volume_id) volume.attach(device_id) except packet.baseapi.Error as msg: raise PacketManagerException(msg) return volume
python
def attach_volume_to_device(self, volume_id, device_id): """Attaches the created Volume to a Device. """ try: volume = self.manager.get_volume(volume_id) volume.attach(device_id) except packet.baseapi.Error as msg: raise PacketManagerException(msg) return volume
[ "def", "attach_volume_to_device", "(", "self", ",", "volume_id", ",", "device_id", ")", ":", "try", ":", "volume", "=", "self", ".", "manager", ".", "get_volume", "(", "volume_id", ")", "volume", ".", "attach", "(", "device_id", ")", "except", "packet", ".", "baseapi", ".", "Error", "as", "msg", ":", "raise", "PacketManagerException", "(", "msg", ")", "return", "volume" ]
Attaches the created Volume to a Device.
[ "Attaches", "the", "created", "Volume", "to", "a", "Device", "." ]
7e80adc6ae92c6c1332d4c08473bb271fb3b6833
https://github.com/MozillaSecurity/laniakea/blob/7e80adc6ae92c6c1332d4c08473bb271fb3b6833/laniakea/core/providers/packet/manager.py#L216-L224
4,105
MozillaSecurity/laniakea
laniakea/core/providers/packet/manager.py
PacketManager.create_demand
def create_demand(self, project_id, facility, plan, operating_system, tags=None, userdata='', hostname=None, count=1): """Create a new on demand device under the given project. """ tags = {} if tags is None else tags hostname = self.get_random_hostname() if hostname is None else hostname devices = [] for i in range(1, count + 1): new_hostname = hostname if count == 1 else hostname + '-' + str(i) self.logger.info('Adding to project %s: %s, %s, %s, %s, %r', project_id, new_hostname, facility, plan, operating_system, tags) try: device = self.manager.create_device(project_id=project_id, hostname=new_hostname, facility=facility, plan=plan, tags=tags, userdata=userdata, operating_system=operating_system) devices.append(device) except packet.baseapi.Error as msg: raise PacketManagerException(msg) return devices
python
def create_demand(self, project_id, facility, plan, operating_system, tags=None, userdata='', hostname=None, count=1): """Create a new on demand device under the given project. """ tags = {} if tags is None else tags hostname = self.get_random_hostname() if hostname is None else hostname devices = [] for i in range(1, count + 1): new_hostname = hostname if count == 1 else hostname + '-' + str(i) self.logger.info('Adding to project %s: %s, %s, %s, %s, %r', project_id, new_hostname, facility, plan, operating_system, tags) try: device = self.manager.create_device(project_id=project_id, hostname=new_hostname, facility=facility, plan=plan, tags=tags, userdata=userdata, operating_system=operating_system) devices.append(device) except packet.baseapi.Error as msg: raise PacketManagerException(msg) return devices
[ "def", "create_demand", "(", "self", ",", "project_id", ",", "facility", ",", "plan", ",", "operating_system", ",", "tags", "=", "None", ",", "userdata", "=", "''", ",", "hostname", "=", "None", ",", "count", "=", "1", ")", ":", "tags", "=", "{", "}", "if", "tags", "is", "None", "else", "tags", "hostname", "=", "self", ".", "get_random_hostname", "(", ")", "if", "hostname", "is", "None", "else", "hostname", "devices", "=", "[", "]", "for", "i", "in", "range", "(", "1", ",", "count", "+", "1", ")", ":", "new_hostname", "=", "hostname", "if", "count", "==", "1", "else", "hostname", "+", "'-'", "+", "str", "(", "i", ")", "self", ".", "logger", ".", "info", "(", "'Adding to project %s: %s, %s, %s, %s, %r'", ",", "project_id", ",", "new_hostname", ",", "facility", ",", "plan", ",", "operating_system", ",", "tags", ")", "try", ":", "device", "=", "self", ".", "manager", ".", "create_device", "(", "project_id", "=", "project_id", ",", "hostname", "=", "new_hostname", ",", "facility", "=", "facility", ",", "plan", "=", "plan", ",", "tags", "=", "tags", ",", "userdata", "=", "userdata", ",", "operating_system", "=", "operating_system", ")", "devices", ".", "append", "(", "device", ")", "except", "packet", ".", "baseapi", ".", "Error", "as", "msg", ":", "raise", "PacketManagerException", "(", "msg", ")", "return", "devices" ]
Create a new on demand device under the given project.
[ "Create", "a", "new", "on", "demand", "device", "under", "the", "given", "project", "." ]
7e80adc6ae92c6c1332d4c08473bb271fb3b6833
https://github.com/MozillaSecurity/laniakea/blob/7e80adc6ae92c6c1332d4c08473bb271fb3b6833/laniakea/core/providers/packet/manager.py#L226-L260
4,106
MozillaSecurity/laniakea
laniakea/core/providers/packet/manager.py
PacketManager.stop
def stop(self, devices): """Power-Off one or more running devices. """ for device in devices: self.logger.info('Stopping: %s', device.id) try: device.power_off() except packet.baseapi.Error: raise PacketManagerException('Unable to stop instance "{}"'.format(device.id))
python
def stop(self, devices): """Power-Off one or more running devices. """ for device in devices: self.logger.info('Stopping: %s', device.id) try: device.power_off() except packet.baseapi.Error: raise PacketManagerException('Unable to stop instance "{}"'.format(device.id))
[ "def", "stop", "(", "self", ",", "devices", ")", ":", "for", "device", "in", "devices", ":", "self", ".", "logger", ".", "info", "(", "'Stopping: %s'", ",", "device", ".", "id", ")", "try", ":", "device", ".", "power_off", "(", ")", "except", "packet", ".", "baseapi", ".", "Error", ":", "raise", "PacketManagerException", "(", "'Unable to stop instance \"{}\"'", ".", "format", "(", "device", ".", "id", ")", ")" ]
Power-Off one or more running devices.
[ "Power", "-", "Off", "one", "or", "more", "running", "devices", "." ]
7e80adc6ae92c6c1332d4c08473bb271fb3b6833
https://github.com/MozillaSecurity/laniakea/blob/7e80adc6ae92c6c1332d4c08473bb271fb3b6833/laniakea/core/providers/packet/manager.py#L302-L310
4,107
MozillaSecurity/laniakea
laniakea/core/providers/packet/manager.py
PacketManager.reboot
def reboot(self, devices): """Reboot one or more devices. """ for device in devices: self.logger.info('Rebooting: %s', device.id) try: device.reboot() except packet.baseapi.Error: raise PacketManagerException('Unable to reboot instance "{}"'.format(device.id))
python
def reboot(self, devices): """Reboot one or more devices. """ for device in devices: self.logger.info('Rebooting: %s', device.id) try: device.reboot() except packet.baseapi.Error: raise PacketManagerException('Unable to reboot instance "{}"'.format(device.id))
[ "def", "reboot", "(", "self", ",", "devices", ")", ":", "for", "device", "in", "devices", ":", "self", ".", "logger", ".", "info", "(", "'Rebooting: %s'", ",", "device", ".", "id", ")", "try", ":", "device", ".", "reboot", "(", ")", "except", "packet", ".", "baseapi", ".", "Error", ":", "raise", "PacketManagerException", "(", "'Unable to reboot instance \"{}\"'", ".", "format", "(", "device", ".", "id", ")", ")" ]
Reboot one or more devices.
[ "Reboot", "one", "or", "more", "devices", "." ]
7e80adc6ae92c6c1332d4c08473bb271fb3b6833
https://github.com/MozillaSecurity/laniakea/blob/7e80adc6ae92c6c1332d4c08473bb271fb3b6833/laniakea/core/providers/packet/manager.py#L312-L320
4,108
MozillaSecurity/laniakea
laniakea/core/providers/packet/manager.py
PacketManager.terminate
def terminate(self, devices): """Terminate one or more running or stopped instances. """ for device in devices: self.logger.info('Terminating: %s', device.id) try: device.delete() except packet.baseapi.Error: raise PacketManagerException('Unable to terminate instance "{}"'.format(device.id))
python
def terminate(self, devices): """Terminate one or more running or stopped instances. """ for device in devices: self.logger.info('Terminating: %s', device.id) try: device.delete() except packet.baseapi.Error: raise PacketManagerException('Unable to terminate instance "{}"'.format(device.id))
[ "def", "terminate", "(", "self", ",", "devices", ")", ":", "for", "device", "in", "devices", ":", "self", ".", "logger", ".", "info", "(", "'Terminating: %s'", ",", "device", ".", "id", ")", "try", ":", "device", ".", "delete", "(", ")", "except", "packet", ".", "baseapi", ".", "Error", ":", "raise", "PacketManagerException", "(", "'Unable to terminate instance \"{}\"'", ".", "format", "(", "device", ".", "id", ")", ")" ]
Terminate one or more running or stopped instances.
[ "Terminate", "one", "or", "more", "running", "or", "stopped", "instances", "." ]
7e80adc6ae92c6c1332d4c08473bb271fb3b6833
https://github.com/MozillaSecurity/laniakea/blob/7e80adc6ae92c6c1332d4c08473bb271fb3b6833/laniakea/core/providers/packet/manager.py#L322-L330
4,109
MozillaSecurity/laniakea
laniakea/__init__.py
LaniakeaCommandLine.parse_args
def parse_args(cls): """Main argument parser of Laniakea. """ # Initialize configuration and userdata directories. dirs = appdirs.AppDirs(__title__, 'Mozilla Security') if not os.path.isdir(dirs.user_config_dir): shutil.copytree(os.path.join(cls.HOME, 'examples'), dirs.user_config_dir) shutil.copytree(os.path.join(cls.HOME, 'userdata'), os.path.join(dirs.user_config_dir, 'userdata')) parser = argparse.ArgumentParser( description='Laniakea Runtime v{}'.format(cls.VERSION), prog=__title__, add_help=False, formatter_class=lambda prog: argparse.ArgumentDefaultsHelpFormatter(prog, max_help_position=40, width=120), epilog='The exit status is 0 for non-failures and 1 for failures.') subparsers = parser.add_subparsers(dest='provider', description='Use -h to see the help menu of each provider.', title='Laniakea Cloud Providers', metavar='') modules = ModuleLoader() modules.load(cls.HOME, 'core/providers', 'laniakea') for name, module in modules.modules.items(): globals()[name] = module for module, cli in modules.command_line_interfaces(): getattr(module, cli).add_arguments(subparsers, dirs) base = parser.add_argument_group('Laniakea Base Parameters') base.add_argument('-verbosity', default=2, type=int, choices=list(range(1, 6, 1)), help='Log sensitivity.') base.add_argument('-focus', action='store_true', default=True, help=argparse.SUPPRESS) base.add_argument('-settings', metavar='path', type=argparse.FileType(), default=os.path.join(dirs.user_config_dir, 'laniakea.json'), help='Laniakea core settings.') base.add_argument('-h', '-help', '--help', action='help', help=argparse.SUPPRESS) base.add_argument('-version', action='version', version='%(prog)s {}'.format(cls.VERSION), help=argparse.SUPPRESS) userdata = parser.add_argument_group('UserData Parameters') userdata.add_argument('-userdata', metavar='path', type=argparse.FileType(), help='UserData script for the provisioning process.') userdata.add_argument('-list-userdata-macros', action='store_true', help='List available macros.') userdata.add_argument('-print-userdata', action='store_true', help='Print the UserData script to stdout.') userdata.add_argument('-userdata-macros', metavar='k=v', nargs='+', type=str, help='Custom macros for the UserData.') return parser.parse_args()
python
def parse_args(cls): """Main argument parser of Laniakea. """ # Initialize configuration and userdata directories. dirs = appdirs.AppDirs(__title__, 'Mozilla Security') if not os.path.isdir(dirs.user_config_dir): shutil.copytree(os.path.join(cls.HOME, 'examples'), dirs.user_config_dir) shutil.copytree(os.path.join(cls.HOME, 'userdata'), os.path.join(dirs.user_config_dir, 'userdata')) parser = argparse.ArgumentParser( description='Laniakea Runtime v{}'.format(cls.VERSION), prog=__title__, add_help=False, formatter_class=lambda prog: argparse.ArgumentDefaultsHelpFormatter(prog, max_help_position=40, width=120), epilog='The exit status is 0 for non-failures and 1 for failures.') subparsers = parser.add_subparsers(dest='provider', description='Use -h to see the help menu of each provider.', title='Laniakea Cloud Providers', metavar='') modules = ModuleLoader() modules.load(cls.HOME, 'core/providers', 'laniakea') for name, module in modules.modules.items(): globals()[name] = module for module, cli in modules.command_line_interfaces(): getattr(module, cli).add_arguments(subparsers, dirs) base = parser.add_argument_group('Laniakea Base Parameters') base.add_argument('-verbosity', default=2, type=int, choices=list(range(1, 6, 1)), help='Log sensitivity.') base.add_argument('-focus', action='store_true', default=True, help=argparse.SUPPRESS) base.add_argument('-settings', metavar='path', type=argparse.FileType(), default=os.path.join(dirs.user_config_dir, 'laniakea.json'), help='Laniakea core settings.') base.add_argument('-h', '-help', '--help', action='help', help=argparse.SUPPRESS) base.add_argument('-version', action='version', version='%(prog)s {}'.format(cls.VERSION), help=argparse.SUPPRESS) userdata = parser.add_argument_group('UserData Parameters') userdata.add_argument('-userdata', metavar='path', type=argparse.FileType(), help='UserData script for the provisioning process.') userdata.add_argument('-list-userdata-macros', action='store_true', help='List available macros.') userdata.add_argument('-print-userdata', action='store_true', help='Print the UserData script to stdout.') userdata.add_argument('-userdata-macros', metavar='k=v', nargs='+', type=str, help='Custom macros for the UserData.') return parser.parse_args()
[ "def", "parse_args", "(", "cls", ")", ":", "# Initialize configuration and userdata directories.", "dirs", "=", "appdirs", ".", "AppDirs", "(", "__title__", ",", "'Mozilla Security'", ")", "if", "not", "os", ".", "path", ".", "isdir", "(", "dirs", ".", "user_config_dir", ")", ":", "shutil", ".", "copytree", "(", "os", ".", "path", ".", "join", "(", "cls", ".", "HOME", ",", "'examples'", ")", ",", "dirs", ".", "user_config_dir", ")", "shutil", ".", "copytree", "(", "os", ".", "path", ".", "join", "(", "cls", ".", "HOME", ",", "'userdata'", ")", ",", "os", ".", "path", ".", "join", "(", "dirs", ".", "user_config_dir", ",", "'userdata'", ")", ")", "parser", "=", "argparse", ".", "ArgumentParser", "(", "description", "=", "'Laniakea Runtime v{}'", ".", "format", "(", "cls", ".", "VERSION", ")", ",", "prog", "=", "__title__", ",", "add_help", "=", "False", ",", "formatter_class", "=", "lambda", "prog", ":", "argparse", ".", "ArgumentDefaultsHelpFormatter", "(", "prog", ",", "max_help_position", "=", "40", ",", "width", "=", "120", ")", ",", "epilog", "=", "'The exit status is 0 for non-failures and 1 for failures.'", ")", "subparsers", "=", "parser", ".", "add_subparsers", "(", "dest", "=", "'provider'", ",", "description", "=", "'Use -h to see the help menu of each provider.'", ",", "title", "=", "'Laniakea Cloud Providers'", ",", "metavar", "=", "''", ")", "modules", "=", "ModuleLoader", "(", ")", "modules", ".", "load", "(", "cls", ".", "HOME", ",", "'core/providers'", ",", "'laniakea'", ")", "for", "name", ",", "module", "in", "modules", ".", "modules", ".", "items", "(", ")", ":", "globals", "(", ")", "[", "name", "]", "=", "module", "for", "module", ",", "cli", "in", "modules", ".", "command_line_interfaces", "(", ")", ":", "getattr", "(", "module", ",", "cli", ")", ".", "add_arguments", "(", "subparsers", ",", "dirs", ")", "base", "=", "parser", ".", "add_argument_group", "(", "'Laniakea Base Parameters'", ")", "base", ".", "add_argument", "(", "'-verbosity'", ",", "default", "=", "2", ",", "type", "=", "int", ",", "choices", "=", "list", "(", "range", "(", "1", ",", "6", ",", "1", ")", ")", ",", "help", "=", "'Log sensitivity.'", ")", "base", ".", "add_argument", "(", "'-focus'", ",", "action", "=", "'store_true'", ",", "default", "=", "True", ",", "help", "=", "argparse", ".", "SUPPRESS", ")", "base", ".", "add_argument", "(", "'-settings'", ",", "metavar", "=", "'path'", ",", "type", "=", "argparse", ".", "FileType", "(", ")", ",", "default", "=", "os", ".", "path", ".", "join", "(", "dirs", ".", "user_config_dir", ",", "'laniakea.json'", ")", ",", "help", "=", "'Laniakea core settings.'", ")", "base", ".", "add_argument", "(", "'-h'", ",", "'-help'", ",", "'--help'", ",", "action", "=", "'help'", ",", "help", "=", "argparse", ".", "SUPPRESS", ")", "base", ".", "add_argument", "(", "'-version'", ",", "action", "=", "'version'", ",", "version", "=", "'%(prog)s {}'", ".", "format", "(", "cls", ".", "VERSION", ")", ",", "help", "=", "argparse", ".", "SUPPRESS", ")", "userdata", "=", "parser", ".", "add_argument_group", "(", "'UserData Parameters'", ")", "userdata", ".", "add_argument", "(", "'-userdata'", ",", "metavar", "=", "'path'", ",", "type", "=", "argparse", ".", "FileType", "(", ")", ",", "help", "=", "'UserData script for the provisioning process.'", ")", "userdata", ".", "add_argument", "(", "'-list-userdata-macros'", ",", "action", "=", "'store_true'", ",", "help", "=", "'List available macros.'", ")", "userdata", ".", "add_argument", "(", "'-print-userdata'", ",", "action", "=", "'store_true'", ",", "help", "=", "'Print the UserData script to stdout.'", ")", "userdata", ".", "add_argument", "(", "'-userdata-macros'", ",", "metavar", "=", "'k=v'", ",", "nargs", "=", "'+'", ",", "type", "=", "str", ",", "help", "=", "'Custom macros for the UserData.'", ")", "return", "parser", ".", "parse_args", "(", ")" ]
Main argument parser of Laniakea.
[ "Main", "argument", "parser", "of", "Laniakea", "." ]
7e80adc6ae92c6c1332d4c08473bb271fb3b6833
https://github.com/MozillaSecurity/laniakea/blob/7e80adc6ae92c6c1332d4c08473bb271fb3b6833/laniakea/__init__.py#L31-L108
4,110
MozillaSecurity/laniakea
laniakea/__init__.py
LaniakeaCommandLine.main
def main(cls): """Main entry point of Laniakea. """ args = cls.parse_args() if args.focus: Focus.init() else: Focus.disable() logging.basicConfig(format='[Laniakea] %(asctime)s %(levelname)s: %(message)s', level=args.verbosity * 10, datefmt='%Y-%m-%d %H:%M:%S') # Laniakea base configuration logger.info('Loading Laniakea configuration from %s', Focus.data(args.settings.name)) try: settings = json.loads(args.settings.read()) except ValueError as msg: logger.error('Unable to parse %s: %s', args.settings.name, msg) return 1 # UserData userdata = '' if args.userdata: logger.info('Reading user data script content from %s', Focus.info(args.userdata.name)) try: userdata = UserData.handle_import_tags(args.userdata.read(), os.path.dirname(args.userdata.name)) except UserDataException as msg: logging.error(msg) return 1 if args.list_userdata_macros: UserData.list_tags(userdata) return 0 if args.userdata_macros: args.userdata_macros = UserData.convert_pair_to_dict(args.userdata_macros or '') userdata = UserData.handle_tags(userdata, args.userdata_macros) if args.print_userdata: logger.info('Combined UserData script:\n%s', userdata) return 0 if args.provider: provider = getattr(globals()[args.provider], args.provider.title() + 'CommandLine') provider().main(args, settings, userdata) return 0
python
def main(cls): """Main entry point of Laniakea. """ args = cls.parse_args() if args.focus: Focus.init() else: Focus.disable() logging.basicConfig(format='[Laniakea] %(asctime)s %(levelname)s: %(message)s', level=args.verbosity * 10, datefmt='%Y-%m-%d %H:%M:%S') # Laniakea base configuration logger.info('Loading Laniakea configuration from %s', Focus.data(args.settings.name)) try: settings = json.loads(args.settings.read()) except ValueError as msg: logger.error('Unable to parse %s: %s', args.settings.name, msg) return 1 # UserData userdata = '' if args.userdata: logger.info('Reading user data script content from %s', Focus.info(args.userdata.name)) try: userdata = UserData.handle_import_tags(args.userdata.read(), os.path.dirname(args.userdata.name)) except UserDataException as msg: logging.error(msg) return 1 if args.list_userdata_macros: UserData.list_tags(userdata) return 0 if args.userdata_macros: args.userdata_macros = UserData.convert_pair_to_dict(args.userdata_macros or '') userdata = UserData.handle_tags(userdata, args.userdata_macros) if args.print_userdata: logger.info('Combined UserData script:\n%s', userdata) return 0 if args.provider: provider = getattr(globals()[args.provider], args.provider.title() + 'CommandLine') provider().main(args, settings, userdata) return 0
[ "def", "main", "(", "cls", ")", ":", "args", "=", "cls", ".", "parse_args", "(", ")", "if", "args", ".", "focus", ":", "Focus", ".", "init", "(", ")", "else", ":", "Focus", ".", "disable", "(", ")", "logging", ".", "basicConfig", "(", "format", "=", "'[Laniakea] %(asctime)s %(levelname)s: %(message)s'", ",", "level", "=", "args", ".", "verbosity", "*", "10", ",", "datefmt", "=", "'%Y-%m-%d %H:%M:%S'", ")", "# Laniakea base configuration", "logger", ".", "info", "(", "'Loading Laniakea configuration from %s'", ",", "Focus", ".", "data", "(", "args", ".", "settings", ".", "name", ")", ")", "try", ":", "settings", "=", "json", ".", "loads", "(", "args", ".", "settings", ".", "read", "(", ")", ")", "except", "ValueError", "as", "msg", ":", "logger", ".", "error", "(", "'Unable to parse %s: %s'", ",", "args", ".", "settings", ".", "name", ",", "msg", ")", "return", "1", "# UserData", "userdata", "=", "''", "if", "args", ".", "userdata", ":", "logger", ".", "info", "(", "'Reading user data script content from %s'", ",", "Focus", ".", "info", "(", "args", ".", "userdata", ".", "name", ")", ")", "try", ":", "userdata", "=", "UserData", ".", "handle_import_tags", "(", "args", ".", "userdata", ".", "read", "(", ")", ",", "os", ".", "path", ".", "dirname", "(", "args", ".", "userdata", ".", "name", ")", ")", "except", "UserDataException", "as", "msg", ":", "logging", ".", "error", "(", "msg", ")", "return", "1", "if", "args", ".", "list_userdata_macros", ":", "UserData", ".", "list_tags", "(", "userdata", ")", "return", "0", "if", "args", ".", "userdata_macros", ":", "args", ".", "userdata_macros", "=", "UserData", ".", "convert_pair_to_dict", "(", "args", ".", "userdata_macros", "or", "''", ")", "userdata", "=", "UserData", ".", "handle_tags", "(", "userdata", ",", "args", ".", "userdata_macros", ")", "if", "args", ".", "print_userdata", ":", "logger", ".", "info", "(", "'Combined UserData script:\\n%s'", ",", "userdata", ")", "return", "0", "if", "args", ".", "provider", ":", "provider", "=", "getattr", "(", "globals", "(", ")", "[", "args", ".", "provider", "]", ",", "args", ".", "provider", ".", "title", "(", ")", "+", "'CommandLine'", ")", "provider", "(", ")", ".", "main", "(", "args", ",", "settings", ",", "userdata", ")", "return", "0" ]
Main entry point of Laniakea.
[ "Main", "entry", "point", "of", "Laniakea", "." ]
7e80adc6ae92c6c1332d4c08473bb271fb3b6833
https://github.com/MozillaSecurity/laniakea/blob/7e80adc6ae92c6c1332d4c08473bb271fb3b6833/laniakea/__init__.py#L111-L161
4,111
MozillaSecurity/laniakea
laniakea/core/providers/gce/manager.py
Filter.tags
def tags(self, tags=None): """Filter by tags. :param tags: Tags to filter. :type tags: ``list`` :return: A list of Node objects. :rtype: ``list`` of :class:`Node` """ if tags is None or not tags: return self nodes = [] for node in self.nodes: if any(tag in node.extra['tags'] for tag in tags): nodes.append(node) self.nodes = nodes return self
python
def tags(self, tags=None): """Filter by tags. :param tags: Tags to filter. :type tags: ``list`` :return: A list of Node objects. :rtype: ``list`` of :class:`Node` """ if tags is None or not tags: return self nodes = [] for node in self.nodes: if any(tag in node.extra['tags'] for tag in tags): nodes.append(node) self.nodes = nodes return self
[ "def", "tags", "(", "self", ",", "tags", "=", "None", ")", ":", "if", "tags", "is", "None", "or", "not", "tags", ":", "return", "self", "nodes", "=", "[", "]", "for", "node", "in", "self", ".", "nodes", ":", "if", "any", "(", "tag", "in", "node", ".", "extra", "[", "'tags'", "]", "for", "tag", "in", "tags", ")", ":", "nodes", ".", "append", "(", "node", ")", "self", ".", "nodes", "=", "nodes", "return", "self" ]
Filter by tags. :param tags: Tags to filter. :type tags: ``list`` :return: A list of Node objects. :rtype: ``list`` of :class:`Node`
[ "Filter", "by", "tags", "." ]
7e80adc6ae92c6c1332d4c08473bb271fb3b6833
https://github.com/MozillaSecurity/laniakea/blob/7e80adc6ae92c6c1332d4c08473bb271fb3b6833/laniakea/core/providers/gce/manager.py#L31-L47
4,112
MozillaSecurity/laniakea
laniakea/core/providers/gce/manager.py
Filter.state
def state(self, states=None): """Filter by state. :param tags: States to filter. :type tags: ``list`` :return: A list of Node objects. :rtype: ``list`` of :class:`Node` """ if states is None or not states: return self nodes = [] for node in self.nodes: if any(state.lower() == node.state.lower() for state in states): nodes.append(node) self.nodes = nodes return self
python
def state(self, states=None): """Filter by state. :param tags: States to filter. :type tags: ``list`` :return: A list of Node objects. :rtype: ``list`` of :class:`Node` """ if states is None or not states: return self nodes = [] for node in self.nodes: if any(state.lower() == node.state.lower() for state in states): nodes.append(node) self.nodes = nodes return self
[ "def", "state", "(", "self", ",", "states", "=", "None", ")", ":", "if", "states", "is", "None", "or", "not", "states", ":", "return", "self", "nodes", "=", "[", "]", "for", "node", "in", "self", ".", "nodes", ":", "if", "any", "(", "state", ".", "lower", "(", ")", "==", "node", ".", "state", ".", "lower", "(", ")", "for", "state", "in", "states", ")", ":", "nodes", ".", "append", "(", "node", ")", "self", ".", "nodes", "=", "nodes", "return", "self" ]
Filter by state. :param tags: States to filter. :type tags: ``list`` :return: A list of Node objects. :rtype: ``list`` of :class:`Node`
[ "Filter", "by", "state", "." ]
7e80adc6ae92c6c1332d4c08473bb271fb3b6833
https://github.com/MozillaSecurity/laniakea/blob/7e80adc6ae92c6c1332d4c08473bb271fb3b6833/laniakea/core/providers/gce/manager.py#L49-L65
4,113
MozillaSecurity/laniakea
laniakea/core/providers/gce/manager.py
Filter.name
def name(self, names=None): """Filter by node name. :param names: Node names to filter. :type names: ``list`` :return: A list of Node objects. :rtype: ``list`` of :class:`Node` """ if names is None or not names: return self nodes = [] for node in self.nodes: if any(name == node.name for name in names): nodes.append(node) self.nodes = nodes return self
python
def name(self, names=None): """Filter by node name. :param names: Node names to filter. :type names: ``list`` :return: A list of Node objects. :rtype: ``list`` of :class:`Node` """ if names is None or not names: return self nodes = [] for node in self.nodes: if any(name == node.name for name in names): nodes.append(node) self.nodes = nodes return self
[ "def", "name", "(", "self", ",", "names", "=", "None", ")", ":", "if", "names", "is", "None", "or", "not", "names", ":", "return", "self", "nodes", "=", "[", "]", "for", "node", "in", "self", ".", "nodes", ":", "if", "any", "(", "name", "==", "node", ".", "name", "for", "name", "in", "names", ")", ":", "nodes", ".", "append", "(", "node", ")", "self", ".", "nodes", "=", "nodes", "return", "self" ]
Filter by node name. :param names: Node names to filter. :type names: ``list`` :return: A list of Node objects. :rtype: ``list`` of :class:`Node`
[ "Filter", "by", "node", "name", "." ]
7e80adc6ae92c6c1332d4c08473bb271fb3b6833
https://github.com/MozillaSecurity/laniakea/blob/7e80adc6ae92c6c1332d4c08473bb271fb3b6833/laniakea/core/providers/gce/manager.py#L67-L83
4,114
MozillaSecurity/laniakea
laniakea/core/providers/gce/manager.py
Filter.is_preemptible
def is_preemptible(self): """Filter by preemptible scheduling. :return: A list of Node objects. :rtype: ``list`` of :class:`Node` """ nodes = [] for node in self.nodes: if Kurz.is_preemtible(node): nodes.append(node) return self
python
def is_preemptible(self): """Filter by preemptible scheduling. :return: A list of Node objects. :rtype: ``list`` of :class:`Node` """ nodes = [] for node in self.nodes: if Kurz.is_preemtible(node): nodes.append(node) return self
[ "def", "is_preemptible", "(", "self", ")", ":", "nodes", "=", "[", "]", "for", "node", "in", "self", ".", "nodes", ":", "if", "Kurz", ".", "is_preemtible", "(", "node", ")", ":", "nodes", ".", "append", "(", "node", ")", "return", "self" ]
Filter by preemptible scheduling. :return: A list of Node objects. :rtype: ``list`` of :class:`Node`
[ "Filter", "by", "preemptible", "scheduling", "." ]
7e80adc6ae92c6c1332d4c08473bb271fb3b6833
https://github.com/MozillaSecurity/laniakea/blob/7e80adc6ae92c6c1332d4c08473bb271fb3b6833/laniakea/core/providers/gce/manager.py#L85-L95
4,115
MozillaSecurity/laniakea
laniakea/core/providers/gce/manager.py
Filter.expr
def expr(self, callback): """Filter by custom expression. :param callback: Callback for custom expression. :type name: ``function`` :return: A list of Node objects. :rtype: ``list`` of :class:`Node` """ nodes = [] for node in self.nodes: if callback(node): nodes.append(node) self.nodes = nodes return self
python
def expr(self, callback): """Filter by custom expression. :param callback: Callback for custom expression. :type name: ``function`` :return: A list of Node objects. :rtype: ``list`` of :class:`Node` """ nodes = [] for node in self.nodes: if callback(node): nodes.append(node) self.nodes = nodes return self
[ "def", "expr", "(", "self", ",", "callback", ")", ":", "nodes", "=", "[", "]", "for", "node", "in", "self", ".", "nodes", ":", "if", "callback", "(", "node", ")", ":", "nodes", ".", "append", "(", "node", ")", "self", ".", "nodes", "=", "nodes", "return", "self" ]
Filter by custom expression. :param callback: Callback for custom expression. :type name: ``function`` :return: A list of Node objects. :rtype: ``list`` of :class:`Node`
[ "Filter", "by", "custom", "expression", "." ]
7e80adc6ae92c6c1332d4c08473bb271fb3b6833
https://github.com/MozillaSecurity/laniakea/blob/7e80adc6ae92c6c1332d4c08473bb271fb3b6833/laniakea/core/providers/gce/manager.py#L97-L111
4,116
MozillaSecurity/laniakea
laniakea/core/providers/gce/manager.py
ComputeEngineManager.connect
def connect(self, **kwargs): """Connect to Google Compute Engine. """ try: self.gce = get_driver(Provider.GCE)( self.user_id, self.key, project=self.project, **kwargs) except: raise ComputeEngineManagerException("Unable to connect to Google Compute Engine.")
python
def connect(self, **kwargs): """Connect to Google Compute Engine. """ try: self.gce = get_driver(Provider.GCE)( self.user_id, self.key, project=self.project, **kwargs) except: raise ComputeEngineManagerException("Unable to connect to Google Compute Engine.")
[ "def", "connect", "(", "self", ",", "*", "*", "kwargs", ")", ":", "try", ":", "self", ".", "gce", "=", "get_driver", "(", "Provider", ".", "GCE", ")", "(", "self", ".", "user_id", ",", "self", ".", "key", ",", "project", "=", "self", ".", "project", ",", "*", "*", "kwargs", ")", "except", ":", "raise", "ComputeEngineManagerException", "(", "\"Unable to connect to Google Compute Engine.\"", ")" ]
Connect to Google Compute Engine.
[ "Connect", "to", "Google", "Compute", "Engine", "." ]
7e80adc6ae92c6c1332d4c08473bb271fb3b6833
https://github.com/MozillaSecurity/laniakea/blob/7e80adc6ae92c6c1332d4c08473bb271fb3b6833/laniakea/core/providers/gce/manager.py#L160-L170
4,117
MozillaSecurity/laniakea
laniakea/core/providers/gce/manager.py
ComputeEngineManager.is_connected
def is_connected(self, attempts=3): """Try to reconnect if neccessary. :param attempts: The amount of tries to reconnect if neccessary. :type attempts: ``int`` """ if self.gce is None: while attempts > 0: self.logger.info("Attempting to connect ...") try: self.connect() except ComputeEngineManagerException: attempts -= 1 continue self.logger.info("Connection established.") return True self.logger.error("Unable to connect to Google Compute Engine.") return False return True
python
def is_connected(self, attempts=3): """Try to reconnect if neccessary. :param attempts: The amount of tries to reconnect if neccessary. :type attempts: ``int`` """ if self.gce is None: while attempts > 0: self.logger.info("Attempting to connect ...") try: self.connect() except ComputeEngineManagerException: attempts -= 1 continue self.logger.info("Connection established.") return True self.logger.error("Unable to connect to Google Compute Engine.") return False return True
[ "def", "is_connected", "(", "self", ",", "attempts", "=", "3", ")", ":", "if", "self", ".", "gce", "is", "None", ":", "while", "attempts", ">", "0", ":", "self", ".", "logger", ".", "info", "(", "\"Attempting to connect ...\"", ")", "try", ":", "self", ".", "connect", "(", ")", "except", "ComputeEngineManagerException", ":", "attempts", "-=", "1", "continue", "self", ".", "logger", ".", "info", "(", "\"Connection established.\"", ")", "return", "True", "self", ".", "logger", ".", "error", "(", "\"Unable to connect to Google Compute Engine.\"", ")", "return", "False", "return", "True" ]
Try to reconnect if neccessary. :param attempts: The amount of tries to reconnect if neccessary. :type attempts: ``int``
[ "Try", "to", "reconnect", "if", "neccessary", "." ]
7e80adc6ae92c6c1332d4c08473bb271fb3b6833
https://github.com/MozillaSecurity/laniakea/blob/7e80adc6ae92c6c1332d4c08473bb271fb3b6833/laniakea/core/providers/gce/manager.py#L172-L191
4,118
MozillaSecurity/laniakea
laniakea/core/providers/gce/manager.py
ComputeEngineManager.create
def create(self, size, number, meta, name=None, image=None, attempts=3): """Create container VM nodes. Uses a container declaration which is undocumented. :param size: The machine type to use. :type size: ``str`` or :class:`GCENodeSize` :param number: Amount of nodes to be spawned. :type number: ``int`` :param meta: Metadata dictionary for the nodes. :type meta: ``dict`` or ``None`` :param name: The name of the node to create. :type name: ``str`` :param image: The image used to create the disk - optional for multiple nodes. :type image: ``str`` or :class:`GCENodeImage` or ``None`` :param attempts: The amount of tries to perform in case nodes fail to create. :type attempts: ``int`` :return: A list of newly created Node objects for the new nodes. :rtype: ``list`` of :class:`Node` """ if name is None: name = Common.get_random_hostname() if image is None and number == 1: raise ComputeEngineManagerException("Base image not provided.") successful = 0 nodes = [] while number - successful > 0 and attempts > 0: if number == 1: # Used because of suffix naming scheme in ex_create_multiple_nodes() for a single node. nodes = [self.gce.create_node(name, size, image, **meta)] else: nodes = self.gce.ex_create_multiple_nodes(name, size, None, number - successful, ignore_errors=False, poll_interval=1, **meta) for node in nodes: if isinstance(node, GCEFailedNode): self.logger.error("Node failed to create, code %s error: %s", node.code, node.error) continue successful += 1 self.nodes.append(node) attempts -= 1 if number != successful: self.logger.error("We tried but %d nodes failed to create.", number - successful) return nodes
python
def create(self, size, number, meta, name=None, image=None, attempts=3): """Create container VM nodes. Uses a container declaration which is undocumented. :param size: The machine type to use. :type size: ``str`` or :class:`GCENodeSize` :param number: Amount of nodes to be spawned. :type number: ``int`` :param meta: Metadata dictionary for the nodes. :type meta: ``dict`` or ``None`` :param name: The name of the node to create. :type name: ``str`` :param image: The image used to create the disk - optional for multiple nodes. :type image: ``str`` or :class:`GCENodeImage` or ``None`` :param attempts: The amount of tries to perform in case nodes fail to create. :type attempts: ``int`` :return: A list of newly created Node objects for the new nodes. :rtype: ``list`` of :class:`Node` """ if name is None: name = Common.get_random_hostname() if image is None and number == 1: raise ComputeEngineManagerException("Base image not provided.") successful = 0 nodes = [] while number - successful > 0 and attempts > 0: if number == 1: # Used because of suffix naming scheme in ex_create_multiple_nodes() for a single node. nodes = [self.gce.create_node(name, size, image, **meta)] else: nodes = self.gce.ex_create_multiple_nodes(name, size, None, number - successful, ignore_errors=False, poll_interval=1, **meta) for node in nodes: if isinstance(node, GCEFailedNode): self.logger.error("Node failed to create, code %s error: %s", node.code, node.error) continue successful += 1 self.nodes.append(node) attempts -= 1 if number != successful: self.logger.error("We tried but %d nodes failed to create.", number - successful) return nodes
[ "def", "create", "(", "self", ",", "size", ",", "number", ",", "meta", ",", "name", "=", "None", ",", "image", "=", "None", ",", "attempts", "=", "3", ")", ":", "if", "name", "is", "None", ":", "name", "=", "Common", ".", "get_random_hostname", "(", ")", "if", "image", "is", "None", "and", "number", "==", "1", ":", "raise", "ComputeEngineManagerException", "(", "\"Base image not provided.\"", ")", "successful", "=", "0", "nodes", "=", "[", "]", "while", "number", "-", "successful", ">", "0", "and", "attempts", ">", "0", ":", "if", "number", "==", "1", ":", "# Used because of suffix naming scheme in ex_create_multiple_nodes() for a single node.", "nodes", "=", "[", "self", ".", "gce", ".", "create_node", "(", "name", ",", "size", ",", "image", ",", "*", "*", "meta", ")", "]", "else", ":", "nodes", "=", "self", ".", "gce", ".", "ex_create_multiple_nodes", "(", "name", ",", "size", ",", "None", ",", "number", "-", "successful", ",", "ignore_errors", "=", "False", ",", "poll_interval", "=", "1", ",", "*", "*", "meta", ")", "for", "node", "in", "nodes", ":", "if", "isinstance", "(", "node", ",", "GCEFailedNode", ")", ":", "self", ".", "logger", ".", "error", "(", "\"Node failed to create, code %s error: %s\"", ",", "node", ".", "code", ",", "node", ".", "error", ")", "continue", "successful", "+=", "1", "self", ".", "nodes", ".", "append", "(", "node", ")", "attempts", "-=", "1", "if", "number", "!=", "successful", ":", "self", ".", "logger", ".", "error", "(", "\"We tried but %d nodes failed to create.\"", ",", "number", "-", "successful", ")", "return", "nodes" ]
Create container VM nodes. Uses a container declaration which is undocumented. :param size: The machine type to use. :type size: ``str`` or :class:`GCENodeSize` :param number: Amount of nodes to be spawned. :type number: ``int`` :param meta: Metadata dictionary for the nodes. :type meta: ``dict`` or ``None`` :param name: The name of the node to create. :type name: ``str`` :param image: The image used to create the disk - optional for multiple nodes. :type image: ``str`` or :class:`GCENodeImage` or ``None`` :param attempts: The amount of tries to perform in case nodes fail to create. :type attempts: ``int`` :return: A list of newly created Node objects for the new nodes. :rtype: ``list`` of :class:`Node`
[ "Create", "container", "VM", "nodes", ".", "Uses", "a", "container", "declaration", "which", "is", "undocumented", "." ]
7e80adc6ae92c6c1332d4c08473bb271fb3b6833
https://github.com/MozillaSecurity/laniakea/blob/7e80adc6ae92c6c1332d4c08473bb271fb3b6833/laniakea/core/providers/gce/manager.py#L193-L247
4,119
MozillaSecurity/laniakea
laniakea/core/providers/gce/manager.py
ComputeEngineManager.stop
def stop(self, nodes=None): """Stop one or many nodes. :param nodes: Nodes to be stopped. :type nodes: ``list`` """ if not self.is_connected(): return None nodes = nodes or self.nodes result = [] for node in nodes: if node.state == 'stopped': logging.warning('Node %s is already "stopped".', node.name) continue try: status = self.gce.ex_stop_node(node) if status: result.append(node) except InvalidRequestError as err: raise ComputeEngineManagerException(err) return result
python
def stop(self, nodes=None): """Stop one or many nodes. :param nodes: Nodes to be stopped. :type nodes: ``list`` """ if not self.is_connected(): return None nodes = nodes or self.nodes result = [] for node in nodes: if node.state == 'stopped': logging.warning('Node %s is already "stopped".', node.name) continue try: status = self.gce.ex_stop_node(node) if status: result.append(node) except InvalidRequestError as err: raise ComputeEngineManagerException(err) return result
[ "def", "stop", "(", "self", ",", "nodes", "=", "None", ")", ":", "if", "not", "self", ".", "is_connected", "(", ")", ":", "return", "None", "nodes", "=", "nodes", "or", "self", ".", "nodes", "result", "=", "[", "]", "for", "node", "in", "nodes", ":", "if", "node", ".", "state", "==", "'stopped'", ":", "logging", ".", "warning", "(", "'Node %s is already \"stopped\".'", ",", "node", ".", "name", ")", "continue", "try", ":", "status", "=", "self", ".", "gce", ".", "ex_stop_node", "(", "node", ")", "if", "status", ":", "result", ".", "append", "(", "node", ")", "except", "InvalidRequestError", "as", "err", ":", "raise", "ComputeEngineManagerException", "(", "err", ")", "return", "result" ]
Stop one or many nodes. :param nodes: Nodes to be stopped. :type nodes: ``list``
[ "Stop", "one", "or", "many", "nodes", "." ]
7e80adc6ae92c6c1332d4c08473bb271fb3b6833
https://github.com/MozillaSecurity/laniakea/blob/7e80adc6ae92c6c1332d4c08473bb271fb3b6833/laniakea/core/providers/gce/manager.py#L249-L272
4,120
MozillaSecurity/laniakea
laniakea/core/providers/gce/manager.py
ComputeEngineManager.start
def start(self, nodes=None): """Start one or many nodes. :param nodes: Nodes to be started. :type nodes: ``list`` """ if not self.is_connected(): return None nodes = nodes or self.nodes result = [] for node in nodes: if node.state == 'running': logging.warning('Node %s is already "running".', node.name) continue try: status = self.gce.ex_start_node(node) if status: result.append(node) except InvalidRequestError as err: raise ComputeEngineManagerException(err) return result
python
def start(self, nodes=None): """Start one or many nodes. :param nodes: Nodes to be started. :type nodes: ``list`` """ if not self.is_connected(): return None nodes = nodes or self.nodes result = [] for node in nodes: if node.state == 'running': logging.warning('Node %s is already "running".', node.name) continue try: status = self.gce.ex_start_node(node) if status: result.append(node) except InvalidRequestError as err: raise ComputeEngineManagerException(err) return result
[ "def", "start", "(", "self", ",", "nodes", "=", "None", ")", ":", "if", "not", "self", ".", "is_connected", "(", ")", ":", "return", "None", "nodes", "=", "nodes", "or", "self", ".", "nodes", "result", "=", "[", "]", "for", "node", "in", "nodes", ":", "if", "node", ".", "state", "==", "'running'", ":", "logging", ".", "warning", "(", "'Node %s is already \"running\".'", ",", "node", ".", "name", ")", "continue", "try", ":", "status", "=", "self", ".", "gce", ".", "ex_start_node", "(", "node", ")", "if", "status", ":", "result", ".", "append", "(", "node", ")", "except", "InvalidRequestError", "as", "err", ":", "raise", "ComputeEngineManagerException", "(", "err", ")", "return", "result" ]
Start one or many nodes. :param nodes: Nodes to be started. :type nodes: ``list``
[ "Start", "one", "or", "many", "nodes", "." ]
7e80adc6ae92c6c1332d4c08473bb271fb3b6833
https://github.com/MozillaSecurity/laniakea/blob/7e80adc6ae92c6c1332d4c08473bb271fb3b6833/laniakea/core/providers/gce/manager.py#L274-L297
4,121
MozillaSecurity/laniakea
laniakea/core/providers/gce/manager.py
ComputeEngineManager.reboot
def reboot(self, nodes=None): """Reboot one or many nodes. :param nodes: Nodes to be rebooted. :type nodes: ``list`` """ if not self.is_connected(): return None nodes = nodes or self.nodes result = [] for node in nodes: if node.state == 'stopped': logging.warning('Node %s is "stopped" and can not be rebooted.', node.name) continue try: status = self.gce.reboot_node(node) if status: result.append(node) except InvalidRequestError as err: raise ComputeEngineManagerException(err) return result
python
def reboot(self, nodes=None): """Reboot one or many nodes. :param nodes: Nodes to be rebooted. :type nodes: ``list`` """ if not self.is_connected(): return None nodes = nodes or self.nodes result = [] for node in nodes: if node.state == 'stopped': logging.warning('Node %s is "stopped" and can not be rebooted.', node.name) continue try: status = self.gce.reboot_node(node) if status: result.append(node) except InvalidRequestError as err: raise ComputeEngineManagerException(err) return result
[ "def", "reboot", "(", "self", ",", "nodes", "=", "None", ")", ":", "if", "not", "self", ".", "is_connected", "(", ")", ":", "return", "None", "nodes", "=", "nodes", "or", "self", ".", "nodes", "result", "=", "[", "]", "for", "node", "in", "nodes", ":", "if", "node", ".", "state", "==", "'stopped'", ":", "logging", ".", "warning", "(", "'Node %s is \"stopped\" and can not be rebooted.'", ",", "node", ".", "name", ")", "continue", "try", ":", "status", "=", "self", ".", "gce", ".", "reboot_node", "(", "node", ")", "if", "status", ":", "result", ".", "append", "(", "node", ")", "except", "InvalidRequestError", "as", "err", ":", "raise", "ComputeEngineManagerException", "(", "err", ")", "return", "result" ]
Reboot one or many nodes. :param nodes: Nodes to be rebooted. :type nodes: ``list``
[ "Reboot", "one", "or", "many", "nodes", "." ]
7e80adc6ae92c6c1332d4c08473bb271fb3b6833
https://github.com/MozillaSecurity/laniakea/blob/7e80adc6ae92c6c1332d4c08473bb271fb3b6833/laniakea/core/providers/gce/manager.py#L299-L322
4,122
MozillaSecurity/laniakea
laniakea/core/providers/gce/manager.py
ComputeEngineManager.terminate
def terminate(self, nodes=None): """Destroy one or many nodes. :param nodes: Nodes to be destroyed. :type nodes: ``list`` :return: List of nodes which failed to terminate. :rtype: ``list`` """ if not self.is_connected(): return None nodes = nodes or self.nodes failed_kill = [] result = self.gce.ex_destroy_multiple_nodes(nodes, poll_interval=1, ignore_errors=False) # Verify whether all instances have been terminated. for i, success in enumerate(result): if success: logging.info('Successfully destroyed: %s', nodes[i].name) else: logging.error('Failed to destroy: %s', nodes[i].name) failed_kill.append(nodes[i]) return failed_kill
python
def terminate(self, nodes=None): """Destroy one or many nodes. :param nodes: Nodes to be destroyed. :type nodes: ``list`` :return: List of nodes which failed to terminate. :rtype: ``list`` """ if not self.is_connected(): return None nodes = nodes or self.nodes failed_kill = [] result = self.gce.ex_destroy_multiple_nodes(nodes, poll_interval=1, ignore_errors=False) # Verify whether all instances have been terminated. for i, success in enumerate(result): if success: logging.info('Successfully destroyed: %s', nodes[i].name) else: logging.error('Failed to destroy: %s', nodes[i].name) failed_kill.append(nodes[i]) return failed_kill
[ "def", "terminate", "(", "self", ",", "nodes", "=", "None", ")", ":", "if", "not", "self", ".", "is_connected", "(", ")", ":", "return", "None", "nodes", "=", "nodes", "or", "self", ".", "nodes", "failed_kill", "=", "[", "]", "result", "=", "self", ".", "gce", ".", "ex_destroy_multiple_nodes", "(", "nodes", ",", "poll_interval", "=", "1", ",", "ignore_errors", "=", "False", ")", "# Verify whether all instances have been terminated.", "for", "i", ",", "success", "in", "enumerate", "(", "result", ")", ":", "if", "success", ":", "logging", ".", "info", "(", "'Successfully destroyed: %s'", ",", "nodes", "[", "i", "]", ".", "name", ")", "else", ":", "logging", ".", "error", "(", "'Failed to destroy: %s'", ",", "nodes", "[", "i", "]", ".", "name", ")", "failed_kill", ".", "append", "(", "nodes", "[", "i", "]", ")", "return", "failed_kill" ]
Destroy one or many nodes. :param nodes: Nodes to be destroyed. :type nodes: ``list`` :return: List of nodes which failed to terminate. :rtype: ``list``
[ "Destroy", "one", "or", "many", "nodes", "." ]
7e80adc6ae92c6c1332d4c08473bb271fb3b6833
https://github.com/MozillaSecurity/laniakea/blob/7e80adc6ae92c6c1332d4c08473bb271fb3b6833/laniakea/core/providers/gce/manager.py#L324-L349
4,123
MozillaSecurity/laniakea
laniakea/core/providers/gce/manager.py
ComputeEngineManager.terminate_with_threads
def terminate_with_threads(self, nodes=None): """Destroy one or many nodes threaded. :param nodes: Nodes to be destroyed. :type nodes: ``list`` :return: List of nodes which failed to terminate. :rtype: ``list`` """ if not self.is_connected(): return None nodes = nodes or self.nodes failed_kill = [] def worker(gce, node): self.logger.info("Terminating node: %s", node.name) terminated = gce.destroy_node(node) if not terminated: failed_kill.append(node) threads = [] for node in nodes: thread = threading.Thread(target=worker, args=(self.gce, node)) threads.append(thread) thread.start() self.logger.info("Waiting for nodes to shut down ...") for thread in threads: thread.join() return failed_kill
python
def terminate_with_threads(self, nodes=None): """Destroy one or many nodes threaded. :param nodes: Nodes to be destroyed. :type nodes: ``list`` :return: List of nodes which failed to terminate. :rtype: ``list`` """ if not self.is_connected(): return None nodes = nodes or self.nodes failed_kill = [] def worker(gce, node): self.logger.info("Terminating node: %s", node.name) terminated = gce.destroy_node(node) if not terminated: failed_kill.append(node) threads = [] for node in nodes: thread = threading.Thread(target=worker, args=(self.gce, node)) threads.append(thread) thread.start() self.logger.info("Waiting for nodes to shut down ...") for thread in threads: thread.join() return failed_kill
[ "def", "terminate_with_threads", "(", "self", ",", "nodes", "=", "None", ")", ":", "if", "not", "self", ".", "is_connected", "(", ")", ":", "return", "None", "nodes", "=", "nodes", "or", "self", ".", "nodes", "failed_kill", "=", "[", "]", "def", "worker", "(", "gce", ",", "node", ")", ":", "self", ".", "logger", ".", "info", "(", "\"Terminating node: %s\"", ",", "node", ".", "name", ")", "terminated", "=", "gce", ".", "destroy_node", "(", "node", ")", "if", "not", "terminated", ":", "failed_kill", ".", "append", "(", "node", ")", "threads", "=", "[", "]", "for", "node", "in", "nodes", ":", "thread", "=", "threading", ".", "Thread", "(", "target", "=", "worker", ",", "args", "=", "(", "self", ".", "gce", ",", "node", ")", ")", "threads", ".", "append", "(", "thread", ")", "thread", ".", "start", "(", ")", "self", ".", "logger", ".", "info", "(", "\"Waiting for nodes to shut down ...\"", ")", "for", "thread", "in", "threads", ":", "thread", ".", "join", "(", ")", "return", "failed_kill" ]
Destroy one or many nodes threaded. :param nodes: Nodes to be destroyed. :type nodes: ``list`` :return: List of nodes which failed to terminate. :rtype: ``list``
[ "Destroy", "one", "or", "many", "nodes", "threaded", "." ]
7e80adc6ae92c6c1332d4c08473bb271fb3b6833
https://github.com/MozillaSecurity/laniakea/blob/7e80adc6ae92c6c1332d4c08473bb271fb3b6833/laniakea/core/providers/gce/manager.py#L351-L382
4,124
MozillaSecurity/laniakea
laniakea/core/providers/gce/manager.py
ComputeEngineManager.terminate_ex
def terminate_ex(self, nodes, threads=False, attempts=3): """Wrapper method for terminate. :param nodes: Nodes to be destroyed. :type nodes: ``list`` :param attempts: The amount of attempts for retrying to terminate failed instances. :type attempts: ``int`` :param threads: Whether to use the threaded approach or not. :type threads: ``bool`` """ while nodes and attempts > 0: if threads: nodes = self.terminate_with_threads(nodes) else: nodes = self.terminate(nodes) if nodes: logger.info("Attempt to terminate the remaining instances once more.") attempts -= 1 return nodes
python
def terminate_ex(self, nodes, threads=False, attempts=3): """Wrapper method for terminate. :param nodes: Nodes to be destroyed. :type nodes: ``list`` :param attempts: The amount of attempts for retrying to terminate failed instances. :type attempts: ``int`` :param threads: Whether to use the threaded approach or not. :type threads: ``bool`` """ while nodes and attempts > 0: if threads: nodes = self.terminate_with_threads(nodes) else: nodes = self.terminate(nodes) if nodes: logger.info("Attempt to terminate the remaining instances once more.") attempts -= 1 return nodes
[ "def", "terminate_ex", "(", "self", ",", "nodes", ",", "threads", "=", "False", ",", "attempts", "=", "3", ")", ":", "while", "nodes", "and", "attempts", ">", "0", ":", "if", "threads", ":", "nodes", "=", "self", ".", "terminate_with_threads", "(", "nodes", ")", "else", ":", "nodes", "=", "self", ".", "terminate", "(", "nodes", ")", "if", "nodes", ":", "logger", ".", "info", "(", "\"Attempt to terminate the remaining instances once more.\"", ")", "attempts", "-=", "1", "return", "nodes" ]
Wrapper method for terminate. :param nodes: Nodes to be destroyed. :type nodes: ``list`` :param attempts: The amount of attempts for retrying to terminate failed instances. :type attempts: ``int`` :param threads: Whether to use the threaded approach or not. :type threads: ``bool``
[ "Wrapper", "method", "for", "terminate", "." ]
7e80adc6ae92c6c1332d4c08473bb271fb3b6833
https://github.com/MozillaSecurity/laniakea/blob/7e80adc6ae92c6c1332d4c08473bb271fb3b6833/laniakea/core/providers/gce/manager.py#L384-L405
4,125
MozillaSecurity/laniakea
laniakea/core/providers/gce/manager.py
ComputeEngineManager.build_bootdisk
def build_bootdisk(self, image, size=10, auto_delete=True): """Buid a disk struct. :param image: Base image name. :type image: ``str`` :param size: Persistent disk size. :type size: ``int`` :param auto_delete: Wether to auto delete disk on instance termination. :type auto_delete: ``bool`` """ if image is None: raise ComputeEngineManagerException("Image must not be None.") return { 'boot': True, 'autoDelete': auto_delete, 'initializeParams': { 'sourceImage': "projects/cos-cloud/global/images/{}".format(image), 'diskSizeGb': size, } }
python
def build_bootdisk(self, image, size=10, auto_delete=True): """Buid a disk struct. :param image: Base image name. :type image: ``str`` :param size: Persistent disk size. :type size: ``int`` :param auto_delete: Wether to auto delete disk on instance termination. :type auto_delete: ``bool`` """ if image is None: raise ComputeEngineManagerException("Image must not be None.") return { 'boot': True, 'autoDelete': auto_delete, 'initializeParams': { 'sourceImage': "projects/cos-cloud/global/images/{}".format(image), 'diskSizeGb': size, } }
[ "def", "build_bootdisk", "(", "self", ",", "image", ",", "size", "=", "10", ",", "auto_delete", "=", "True", ")", ":", "if", "image", "is", "None", ":", "raise", "ComputeEngineManagerException", "(", "\"Image must not be None.\"", ")", "return", "{", "'boot'", ":", "True", ",", "'autoDelete'", ":", "auto_delete", ",", "'initializeParams'", ":", "{", "'sourceImage'", ":", "\"projects/cos-cloud/global/images/{}\"", ".", "format", "(", "image", ")", ",", "'diskSizeGb'", ":", "size", ",", "}", "}" ]
Buid a disk struct. :param image: Base image name. :type image: ``str`` :param size: Persistent disk size. :type size: ``int`` :param auto_delete: Wether to auto delete disk on instance termination. :type auto_delete: ``bool``
[ "Buid", "a", "disk", "struct", "." ]
7e80adc6ae92c6c1332d4c08473bb271fb3b6833
https://github.com/MozillaSecurity/laniakea/blob/7e80adc6ae92c6c1332d4c08473bb271fb3b6833/laniakea/core/providers/gce/manager.py#L407-L428
4,126
MozillaSecurity/laniakea
laniakea/core/providers/gce/manager.py
ComputeEngineManager.build_container_vm
def build_container_vm(self, container, disk, zone="us-east1-b", tags=None, preemptible=True): """Build kwargs for a container VM. :param container: Container declaration. :type container: ``dict`` :param disk: Disk definition structure. :type disk: ``dict`` :param zone: The zone in which the instance should run. :type zone: ``str`` :param tags: Tags associated with the instance. :type tags: ``dict`` :param preemptible: Wether the instance is a preemtible or not. :type preemptible: ``bool`` """ if tags is None: tags = [] if container is None: raise ComputeEngineManagerException("Container declaration must not be None.") if disk is None: raise ComputeEngineManagerException("Disk structure must not be None.") return { 'ex_metadata': { "gce-container-declaration": container, "google-logging-enabled": "true" }, 'location': zone, 'ex_tags': tags, 'ex_disks_gce_struct': [disk], 'ex_preemptible': preemptible }
python
def build_container_vm(self, container, disk, zone="us-east1-b", tags=None, preemptible=True): """Build kwargs for a container VM. :param container: Container declaration. :type container: ``dict`` :param disk: Disk definition structure. :type disk: ``dict`` :param zone: The zone in which the instance should run. :type zone: ``str`` :param tags: Tags associated with the instance. :type tags: ``dict`` :param preemptible: Wether the instance is a preemtible or not. :type preemptible: ``bool`` """ if tags is None: tags = [] if container is None: raise ComputeEngineManagerException("Container declaration must not be None.") if disk is None: raise ComputeEngineManagerException("Disk structure must not be None.") return { 'ex_metadata': { "gce-container-declaration": container, "google-logging-enabled": "true" }, 'location': zone, 'ex_tags': tags, 'ex_disks_gce_struct': [disk], 'ex_preemptible': preemptible }
[ "def", "build_container_vm", "(", "self", ",", "container", ",", "disk", ",", "zone", "=", "\"us-east1-b\"", ",", "tags", "=", "None", ",", "preemptible", "=", "True", ")", ":", "if", "tags", "is", "None", ":", "tags", "=", "[", "]", "if", "container", "is", "None", ":", "raise", "ComputeEngineManagerException", "(", "\"Container declaration must not be None.\"", ")", "if", "disk", "is", "None", ":", "raise", "ComputeEngineManagerException", "(", "\"Disk structure must not be None.\"", ")", "return", "{", "'ex_metadata'", ":", "{", "\"gce-container-declaration\"", ":", "container", ",", "\"google-logging-enabled\"", ":", "\"true\"", "}", ",", "'location'", ":", "zone", ",", "'ex_tags'", ":", "tags", ",", "'ex_disks_gce_struct'", ":", "[", "disk", "]", ",", "'ex_preemptible'", ":", "preemptible", "}" ]
Build kwargs for a container VM. :param container: Container declaration. :type container: ``dict`` :param disk: Disk definition structure. :type disk: ``dict`` :param zone: The zone in which the instance should run. :type zone: ``str`` :param tags: Tags associated with the instance. :type tags: ``dict`` :param preemptible: Wether the instance is a preemtible or not. :type preemptible: ``bool``
[ "Build", "kwargs", "for", "a", "container", "VM", "." ]
7e80adc6ae92c6c1332d4c08473bb271fb3b6833
https://github.com/MozillaSecurity/laniakea/blob/7e80adc6ae92c6c1332d4c08473bb271fb3b6833/laniakea/core/providers/gce/manager.py#L430-L463
4,127
MozillaSecurity/laniakea
laniakea/core/providers/gce/manager.py
ComputeEngineManager.filter
def filter(self, zone='all'): """Filter nodes by their attributes. :param zone: A zone containing nodes. :type zone: ``str`` :return: A chainable filter object. :rtype: ``object`` of :class:`Filter` """ if not self.is_connected(): return None nodes = self.gce.list_nodes(zone) return Filter(nodes)
python
def filter(self, zone='all'): """Filter nodes by their attributes. :param zone: A zone containing nodes. :type zone: ``str`` :return: A chainable filter object. :rtype: ``object`` of :class:`Filter` """ if not self.is_connected(): return None nodes = self.gce.list_nodes(zone) return Filter(nodes)
[ "def", "filter", "(", "self", ",", "zone", "=", "'all'", ")", ":", "if", "not", "self", ".", "is_connected", "(", ")", ":", "return", "None", "nodes", "=", "self", ".", "gce", ".", "list_nodes", "(", "zone", ")", "return", "Filter", "(", "nodes", ")" ]
Filter nodes by their attributes. :param zone: A zone containing nodes. :type zone: ``str`` :return: A chainable filter object. :rtype: ``object`` of :class:`Filter`
[ "Filter", "nodes", "by", "their", "attributes", "." ]
7e80adc6ae92c6c1332d4c08473bb271fb3b6833
https://github.com/MozillaSecurity/laniakea/blob/7e80adc6ae92c6c1332d4c08473bb271fb3b6833/laniakea/core/providers/gce/manager.py#L465-L478
4,128
scivision/pymap3d
pymap3d/enu.py
enu2aer
def enu2aer(e: np.ndarray, n: np.ndarray, u: np.ndarray, deg: bool = True) -> Tuple[float, float, float]: """ ENU to Azimuth, Elevation, Range Parameters ---------- e : float or np.ndarray of float ENU East coordinate (meters) n : float or np.ndarray of float ENU North coordinate (meters) u : float or np.ndarray of float ENU Up coordinate (meters) deg : bool, optional degrees input/output (False: radians in/out) Results ------- azimuth : float or np.ndarray of float azimuth to rarget elevation : float or np.ndarray of float elevation to target srange : float or np.ndarray of float slant range [meters] """ # 1 millimeter precision for singularity e = np.asarray(e) n = np.asarray(n) u = np.asarray(u) with np.errstate(invalid='ignore'): e[abs(e) < 1e-3] = 0. n[abs(n) < 1e-3] = 0. u[abs(u) < 1e-3] = 0. r = hypot(e, n) slantRange = hypot(r, u) elev = arctan2(u, r) az = arctan2(e, n) % tau if deg: az = degrees(az) elev = degrees(elev) return az, elev, slantRange
python
def enu2aer(e: np.ndarray, n: np.ndarray, u: np.ndarray, deg: bool = True) -> Tuple[float, float, float]: """ ENU to Azimuth, Elevation, Range Parameters ---------- e : float or np.ndarray of float ENU East coordinate (meters) n : float or np.ndarray of float ENU North coordinate (meters) u : float or np.ndarray of float ENU Up coordinate (meters) deg : bool, optional degrees input/output (False: radians in/out) Results ------- azimuth : float or np.ndarray of float azimuth to rarget elevation : float or np.ndarray of float elevation to target srange : float or np.ndarray of float slant range [meters] """ # 1 millimeter precision for singularity e = np.asarray(e) n = np.asarray(n) u = np.asarray(u) with np.errstate(invalid='ignore'): e[abs(e) < 1e-3] = 0. n[abs(n) < 1e-3] = 0. u[abs(u) < 1e-3] = 0. r = hypot(e, n) slantRange = hypot(r, u) elev = arctan2(u, r) az = arctan2(e, n) % tau if deg: az = degrees(az) elev = degrees(elev) return az, elev, slantRange
[ "def", "enu2aer", "(", "e", ":", "np", ".", "ndarray", ",", "n", ":", "np", ".", "ndarray", ",", "u", ":", "np", ".", "ndarray", ",", "deg", ":", "bool", "=", "True", ")", "->", "Tuple", "[", "float", ",", "float", ",", "float", "]", ":", "# 1 millimeter precision for singularity", "e", "=", "np", ".", "asarray", "(", "e", ")", "n", "=", "np", ".", "asarray", "(", "n", ")", "u", "=", "np", ".", "asarray", "(", "u", ")", "with", "np", ".", "errstate", "(", "invalid", "=", "'ignore'", ")", ":", "e", "[", "abs", "(", "e", ")", "<", "1e-3", "]", "=", "0.", "n", "[", "abs", "(", "n", ")", "<", "1e-3", "]", "=", "0.", "u", "[", "abs", "(", "u", ")", "<", "1e-3", "]", "=", "0.", "r", "=", "hypot", "(", "e", ",", "n", ")", "slantRange", "=", "hypot", "(", "r", ",", "u", ")", "elev", "=", "arctan2", "(", "u", ",", "r", ")", "az", "=", "arctan2", "(", "e", ",", "n", ")", "%", "tau", "if", "deg", ":", "az", "=", "degrees", "(", "az", ")", "elev", "=", "degrees", "(", "elev", ")", "return", "az", ",", "elev", ",", "slantRange" ]
ENU to Azimuth, Elevation, Range Parameters ---------- e : float or np.ndarray of float ENU East coordinate (meters) n : float or np.ndarray of float ENU North coordinate (meters) u : float or np.ndarray of float ENU Up coordinate (meters) deg : bool, optional degrees input/output (False: radians in/out) Results ------- azimuth : float or np.ndarray of float azimuth to rarget elevation : float or np.ndarray of float elevation to target srange : float or np.ndarray of float slant range [meters]
[ "ENU", "to", "Azimuth", "Elevation", "Range" ]
c9cf676594611cdb52ff7e0eca6388c80ed4f63f
https://github.com/scivision/pymap3d/blob/c9cf676594611cdb52ff7e0eca6388c80ed4f63f/pymap3d/enu.py#L16-L62
4,129
scivision/pymap3d
pymap3d/enu.py
aer2enu
def aer2enu(az: float, el: float, srange: float, deg: bool = True) -> Tuple[float, float, float]: """ Azimuth, Elevation, Slant range to target to East, north, Up Parameters ---------- azimuth : float or np.ndarray of float azimuth clockwise from north (degrees) elevation : float or np.ndarray of float elevation angle above horizon, neglecting aberattions (degrees) srange : float or np.ndarray of float slant range [meters] deg : bool, optional degrees input/output (False: radians in/out) Returns -------- e : float or np.ndarray of float East ENU coordinate (meters) n : float or np.ndarray of float North ENU coordinate (meters) u : float or np.ndarray of float Up ENU coordinate (meters) """ if deg: el = radians(el) az = radians(az) with np.errstate(invalid='ignore'): if (np.asarray(srange) < 0).any(): raise ValueError('Slant range [0, Infinity)') r = srange * cos(el) return r * sin(az), r * cos(az), srange * sin(el)
python
def aer2enu(az: float, el: float, srange: float, deg: bool = True) -> Tuple[float, float, float]: """ Azimuth, Elevation, Slant range to target to East, north, Up Parameters ---------- azimuth : float or np.ndarray of float azimuth clockwise from north (degrees) elevation : float or np.ndarray of float elevation angle above horizon, neglecting aberattions (degrees) srange : float or np.ndarray of float slant range [meters] deg : bool, optional degrees input/output (False: radians in/out) Returns -------- e : float or np.ndarray of float East ENU coordinate (meters) n : float or np.ndarray of float North ENU coordinate (meters) u : float or np.ndarray of float Up ENU coordinate (meters) """ if deg: el = radians(el) az = radians(az) with np.errstate(invalid='ignore'): if (np.asarray(srange) < 0).any(): raise ValueError('Slant range [0, Infinity)') r = srange * cos(el) return r * sin(az), r * cos(az), srange * sin(el)
[ "def", "aer2enu", "(", "az", ":", "float", ",", "el", ":", "float", ",", "srange", ":", "float", ",", "deg", ":", "bool", "=", "True", ")", "->", "Tuple", "[", "float", ",", "float", ",", "float", "]", ":", "if", "deg", ":", "el", "=", "radians", "(", "el", ")", "az", "=", "radians", "(", "az", ")", "with", "np", ".", "errstate", "(", "invalid", "=", "'ignore'", ")", ":", "if", "(", "np", ".", "asarray", "(", "srange", ")", "<", "0", ")", ".", "any", "(", ")", ":", "raise", "ValueError", "(", "'Slant range [0, Infinity)'", ")", "r", "=", "srange", "*", "cos", "(", "el", ")", "return", "r", "*", "sin", "(", "az", ")", ",", "r", "*", "cos", "(", "az", ")", ",", "srange", "*", "sin", "(", "el", ")" ]
Azimuth, Elevation, Slant range to target to East, north, Up Parameters ---------- azimuth : float or np.ndarray of float azimuth clockwise from north (degrees) elevation : float or np.ndarray of float elevation angle above horizon, neglecting aberattions (degrees) srange : float or np.ndarray of float slant range [meters] deg : bool, optional degrees input/output (False: radians in/out) Returns -------- e : float or np.ndarray of float East ENU coordinate (meters) n : float or np.ndarray of float North ENU coordinate (meters) u : float or np.ndarray of float Up ENU coordinate (meters)
[ "Azimuth", "Elevation", "Slant", "range", "to", "target", "to", "East", "north", "Up" ]
c9cf676594611cdb52ff7e0eca6388c80ed4f63f
https://github.com/scivision/pymap3d/blob/c9cf676594611cdb52ff7e0eca6388c80ed4f63f/pymap3d/enu.py#L65-L99
4,130
scivision/pymap3d
pymap3d/enu.py
enu2geodetic
def enu2geodetic(e: float, n: float, u: float, lat0: float, lon0: float, h0: float, ell=None, deg: bool = True) -> Tuple[float, float, float]: """ East, North, Up to target to geodetic coordinates Parameters ---------- e : float or np.ndarray of float East ENU coordinate (meters) n : float or np.ndarray of float North ENU coordinate (meters) u : float or np.ndarray of float Up ENU coordinate (meters) lat0 : float Observer geodetic latitude lon0 : float Observer geodetic longitude h0 : float observer altitude above geodetic ellipsoid (meters) ell : Ellipsoid, optional reference ellipsoid deg : bool, optional degrees input/output (False: radians in/out) Results ------- lat : float or np.ndarray of float geodetic latitude lon : float or np.ndarray of float geodetic longitude alt : float or np.ndarray of float altitude above ellipsoid (meters) """ x, y, z = enu2ecef(e, n, u, lat0, lon0, h0, ell, deg=deg) return ecef2geodetic(x, y, z, ell, deg=deg)
python
def enu2geodetic(e: float, n: float, u: float, lat0: float, lon0: float, h0: float, ell=None, deg: bool = True) -> Tuple[float, float, float]: """ East, North, Up to target to geodetic coordinates Parameters ---------- e : float or np.ndarray of float East ENU coordinate (meters) n : float or np.ndarray of float North ENU coordinate (meters) u : float or np.ndarray of float Up ENU coordinate (meters) lat0 : float Observer geodetic latitude lon0 : float Observer geodetic longitude h0 : float observer altitude above geodetic ellipsoid (meters) ell : Ellipsoid, optional reference ellipsoid deg : bool, optional degrees input/output (False: radians in/out) Results ------- lat : float or np.ndarray of float geodetic latitude lon : float or np.ndarray of float geodetic longitude alt : float or np.ndarray of float altitude above ellipsoid (meters) """ x, y, z = enu2ecef(e, n, u, lat0, lon0, h0, ell, deg=deg) return ecef2geodetic(x, y, z, ell, deg=deg)
[ "def", "enu2geodetic", "(", "e", ":", "float", ",", "n", ":", "float", ",", "u", ":", "float", ",", "lat0", ":", "float", ",", "lon0", ":", "float", ",", "h0", ":", "float", ",", "ell", "=", "None", ",", "deg", ":", "bool", "=", "True", ")", "->", "Tuple", "[", "float", ",", "float", ",", "float", "]", ":", "x", ",", "y", ",", "z", "=", "enu2ecef", "(", "e", ",", "n", ",", "u", ",", "lat0", ",", "lon0", ",", "h0", ",", "ell", ",", "deg", "=", "deg", ")", "return", "ecef2geodetic", "(", "x", ",", "y", ",", "z", ",", "ell", ",", "deg", "=", "deg", ")" ]
East, North, Up to target to geodetic coordinates Parameters ---------- e : float or np.ndarray of float East ENU coordinate (meters) n : float or np.ndarray of float North ENU coordinate (meters) u : float or np.ndarray of float Up ENU coordinate (meters) lat0 : float Observer geodetic latitude lon0 : float Observer geodetic longitude h0 : float observer altitude above geodetic ellipsoid (meters) ell : Ellipsoid, optional reference ellipsoid deg : bool, optional degrees input/output (False: radians in/out) Results ------- lat : float or np.ndarray of float geodetic latitude lon : float or np.ndarray of float geodetic longitude alt : float or np.ndarray of float altitude above ellipsoid (meters)
[ "East", "North", "Up", "to", "target", "to", "geodetic", "coordinates" ]
c9cf676594611cdb52ff7e0eca6388c80ed4f63f
https://github.com/scivision/pymap3d/blob/c9cf676594611cdb52ff7e0eca6388c80ed4f63f/pymap3d/enu.py#L102-L140
4,131
scivision/pymap3d
pymap3d/vincenty.py
track2
def track2(lat1: float, lon1: float, lat2: float, lon2: float, ell: Ellipsoid = None, npts: int = 100, deg: bool = True): """ computes great circle tracks starting at the point lat1, lon1 and ending at lat2, lon2 Parameters ---------- Lat1 : float or numpy.ndarray of float Geodetic latitude of first point (degrees) Lon1 : float or numpy.ndarray of float Geodetic longitude of first point (degrees) Lat2 : float or numpy.ndarray of float Geodetic latitude of second point (degrees) Lon2 : float or numpy.ndarray of float Geodetic longitude of second point (degrees) ell : Ellipsoid, optional reference ellipsoid npts : int, optional number of points (default is 100) deg : bool, optional degrees input/output (False: radians in/out) Results ------- lats : numpy.ndarray of float latitudes of points along track lons : numpy.ndarray of float longitudes of points along track Based on code posted to the GMT mailing list in Dec 1999 by Jim Levens and by Jeff Whitaker <[email protected]> """ if ell is None: ell = Ellipsoid() if npts <= 1: raise ValueError('npts must be greater than 1') if npts == 2: return [lat1, lat2], [lon1, lon2] if deg is True: rlat1, rlon1, rlat2, rlon2 = np.radians([lat1, lon1, lat2, lon2]) else: rlat1, rlon1, rlat2, rlon2 = lat1, lon1, lat2, lon2 gcarclen = 2. * np.arcsin(np.sqrt((np.sin((rlat1 - rlat2) / 2))**2 + np.cos(rlat1) * np.cos(rlat2) * (np.sin((rlon1 - rlon2) / 2))**2)) # check to see if points are antipodal (if so, route is undefined). if np.allclose(gcarclen, pi): raise ValueError('cannot compute intermediate points on a great circle whose endpoints are antipodal') distance, azimuth, _ = vdist(lat1, lon1, lat2, lon2) incdist = distance / (npts - 1) latpt = lat1 lonpt = lon1 lons = [lonpt] lats = [latpt] for n in range(npts - 2): latptnew, lonptnew, _ = vreckon(latpt, lonpt, incdist, azimuth) _, azimuth, _ = vdist(latptnew, lonptnew, lat2, lon2, ell=ell) lats.append(latptnew) lons.append(lonptnew) latpt = latptnew lonpt = lonptnew lons.append(lon2) lats.append(lat2) if not deg: lats = np.radians(lats) lons = np.radians(lons) return lats, lons
python
def track2(lat1: float, lon1: float, lat2: float, lon2: float, ell: Ellipsoid = None, npts: int = 100, deg: bool = True): """ computes great circle tracks starting at the point lat1, lon1 and ending at lat2, lon2 Parameters ---------- Lat1 : float or numpy.ndarray of float Geodetic latitude of first point (degrees) Lon1 : float or numpy.ndarray of float Geodetic longitude of first point (degrees) Lat2 : float or numpy.ndarray of float Geodetic latitude of second point (degrees) Lon2 : float or numpy.ndarray of float Geodetic longitude of second point (degrees) ell : Ellipsoid, optional reference ellipsoid npts : int, optional number of points (default is 100) deg : bool, optional degrees input/output (False: radians in/out) Results ------- lats : numpy.ndarray of float latitudes of points along track lons : numpy.ndarray of float longitudes of points along track Based on code posted to the GMT mailing list in Dec 1999 by Jim Levens and by Jeff Whitaker <[email protected]> """ if ell is None: ell = Ellipsoid() if npts <= 1: raise ValueError('npts must be greater than 1') if npts == 2: return [lat1, lat2], [lon1, lon2] if deg is True: rlat1, rlon1, rlat2, rlon2 = np.radians([lat1, lon1, lat2, lon2]) else: rlat1, rlon1, rlat2, rlon2 = lat1, lon1, lat2, lon2 gcarclen = 2. * np.arcsin(np.sqrt((np.sin((rlat1 - rlat2) / 2))**2 + np.cos(rlat1) * np.cos(rlat2) * (np.sin((rlon1 - rlon2) / 2))**2)) # check to see if points are antipodal (if so, route is undefined). if np.allclose(gcarclen, pi): raise ValueError('cannot compute intermediate points on a great circle whose endpoints are antipodal') distance, azimuth, _ = vdist(lat1, lon1, lat2, lon2) incdist = distance / (npts - 1) latpt = lat1 lonpt = lon1 lons = [lonpt] lats = [latpt] for n in range(npts - 2): latptnew, lonptnew, _ = vreckon(latpt, lonpt, incdist, azimuth) _, azimuth, _ = vdist(latptnew, lonptnew, lat2, lon2, ell=ell) lats.append(latptnew) lons.append(lonptnew) latpt = latptnew lonpt = lonptnew lons.append(lon2) lats.append(lat2) if not deg: lats = np.radians(lats) lons = np.radians(lons) return lats, lons
[ "def", "track2", "(", "lat1", ":", "float", ",", "lon1", ":", "float", ",", "lat2", ":", "float", ",", "lon2", ":", "float", ",", "ell", ":", "Ellipsoid", "=", "None", ",", "npts", ":", "int", "=", "100", ",", "deg", ":", "bool", "=", "True", ")", ":", "if", "ell", "is", "None", ":", "ell", "=", "Ellipsoid", "(", ")", "if", "npts", "<=", "1", ":", "raise", "ValueError", "(", "'npts must be greater than 1'", ")", "if", "npts", "==", "2", ":", "return", "[", "lat1", ",", "lat2", "]", ",", "[", "lon1", ",", "lon2", "]", "if", "deg", "is", "True", ":", "rlat1", ",", "rlon1", ",", "rlat2", ",", "rlon2", "=", "np", ".", "radians", "(", "[", "lat1", ",", "lon1", ",", "lat2", ",", "lon2", "]", ")", "else", ":", "rlat1", ",", "rlon1", ",", "rlat2", ",", "rlon2", "=", "lat1", ",", "lon1", ",", "lat2", ",", "lon2", "gcarclen", "=", "2.", "*", "np", ".", "arcsin", "(", "np", ".", "sqrt", "(", "(", "np", ".", "sin", "(", "(", "rlat1", "-", "rlat2", ")", "/", "2", ")", ")", "**", "2", "+", "np", ".", "cos", "(", "rlat1", ")", "*", "np", ".", "cos", "(", "rlat2", ")", "*", "(", "np", ".", "sin", "(", "(", "rlon1", "-", "rlon2", ")", "/", "2", ")", ")", "**", "2", ")", ")", "# check to see if points are antipodal (if so, route is undefined).", "if", "np", ".", "allclose", "(", "gcarclen", ",", "pi", ")", ":", "raise", "ValueError", "(", "'cannot compute intermediate points on a great circle whose endpoints are antipodal'", ")", "distance", ",", "azimuth", ",", "_", "=", "vdist", "(", "lat1", ",", "lon1", ",", "lat2", ",", "lon2", ")", "incdist", "=", "distance", "/", "(", "npts", "-", "1", ")", "latpt", "=", "lat1", "lonpt", "=", "lon1", "lons", "=", "[", "lonpt", "]", "lats", "=", "[", "latpt", "]", "for", "n", "in", "range", "(", "npts", "-", "2", ")", ":", "latptnew", ",", "lonptnew", ",", "_", "=", "vreckon", "(", "latpt", ",", "lonpt", ",", "incdist", ",", "azimuth", ")", "_", ",", "azimuth", ",", "_", "=", "vdist", "(", "latptnew", ",", "lonptnew", ",", "lat2", ",", "lon2", ",", "ell", "=", "ell", ")", "lats", ".", "append", "(", "latptnew", ")", "lons", ".", "append", "(", "lonptnew", ")", "latpt", "=", "latptnew", "lonpt", "=", "lonptnew", "lons", ".", "append", "(", "lon2", ")", "lats", ".", "append", "(", "lat2", ")", "if", "not", "deg", ":", "lats", "=", "np", ".", "radians", "(", "lats", ")", "lons", "=", "np", ".", "radians", "(", "lons", ")", "return", "lats", ",", "lons" ]
computes great circle tracks starting at the point lat1, lon1 and ending at lat2, lon2 Parameters ---------- Lat1 : float or numpy.ndarray of float Geodetic latitude of first point (degrees) Lon1 : float or numpy.ndarray of float Geodetic longitude of first point (degrees) Lat2 : float or numpy.ndarray of float Geodetic latitude of second point (degrees) Lon2 : float or numpy.ndarray of float Geodetic longitude of second point (degrees) ell : Ellipsoid, optional reference ellipsoid npts : int, optional number of points (default is 100) deg : bool, optional degrees input/output (False: radians in/out) Results ------- lats : numpy.ndarray of float latitudes of points along track lons : numpy.ndarray of float longitudes of points along track Based on code posted to the GMT mailing list in Dec 1999 by Jim Levens and by Jeff Whitaker <[email protected]>
[ "computes", "great", "circle", "tracks", "starting", "at", "the", "point", "lat1", "lon1", "and", "ending", "at", "lat2", "lon2" ]
c9cf676594611cdb52ff7e0eca6388c80ed4f63f
https://github.com/scivision/pymap3d/blob/c9cf676594611cdb52ff7e0eca6388c80ed4f63f/pymap3d/vincenty.py#L416-L491
4,132
scivision/pymap3d
pymap3d/sidereal.py
datetime2sidereal
def datetime2sidereal(time: datetime, lon_radians: float, usevallado: bool = True) -> float: """ Convert ``datetime`` to sidereal time from D. Vallado "Fundamentals of Astrodynamics and Applications" time : datetime.datetime time to convert lon_radians : float longitude (radians) usevallado : bool, optional use vallado instead of AstroPy (default is Vallado) Results ------- tsr : float Sidereal time """ usevallado = usevallado or Time is None if usevallado: jd = juliandate(str2dt(time)) # %% Greenwich Sidereal time RADIANS gst = julian2sidereal(jd) # %% Algorithm 15 p. 188 rotate GST to LOCAL SIDEREAL TIME tsr = gst + lon_radians else: tsr = Time(time).sidereal_time(kind='apparent', longitude=Longitude(lon_radians, unit=u.radian)).radian return tsr
python
def datetime2sidereal(time: datetime, lon_radians: float, usevallado: bool = True) -> float: """ Convert ``datetime`` to sidereal time from D. Vallado "Fundamentals of Astrodynamics and Applications" time : datetime.datetime time to convert lon_radians : float longitude (radians) usevallado : bool, optional use vallado instead of AstroPy (default is Vallado) Results ------- tsr : float Sidereal time """ usevallado = usevallado or Time is None if usevallado: jd = juliandate(str2dt(time)) # %% Greenwich Sidereal time RADIANS gst = julian2sidereal(jd) # %% Algorithm 15 p. 188 rotate GST to LOCAL SIDEREAL TIME tsr = gst + lon_radians else: tsr = Time(time).sidereal_time(kind='apparent', longitude=Longitude(lon_radians, unit=u.radian)).radian return tsr
[ "def", "datetime2sidereal", "(", "time", ":", "datetime", ",", "lon_radians", ":", "float", ",", "usevallado", ":", "bool", "=", "True", ")", "->", "float", ":", "usevallado", "=", "usevallado", "or", "Time", "is", "None", "if", "usevallado", ":", "jd", "=", "juliandate", "(", "str2dt", "(", "time", ")", ")", "# %% Greenwich Sidereal time RADIANS", "gst", "=", "julian2sidereal", "(", "jd", ")", "# %% Algorithm 15 p. 188 rotate GST to LOCAL SIDEREAL TIME", "tsr", "=", "gst", "+", "lon_radians", "else", ":", "tsr", "=", "Time", "(", "time", ")", ".", "sidereal_time", "(", "kind", "=", "'apparent'", ",", "longitude", "=", "Longitude", "(", "lon_radians", ",", "unit", "=", "u", ".", "radian", ")", ")", ".", "radian", "return", "tsr" ]
Convert ``datetime`` to sidereal time from D. Vallado "Fundamentals of Astrodynamics and Applications" time : datetime.datetime time to convert lon_radians : float longitude (radians) usevallado : bool, optional use vallado instead of AstroPy (default is Vallado) Results ------- tsr : float Sidereal time
[ "Convert", "datetime", "to", "sidereal", "time" ]
c9cf676594611cdb52ff7e0eca6388c80ed4f63f
https://github.com/scivision/pymap3d/blob/c9cf676594611cdb52ff7e0eca6388c80ed4f63f/pymap3d/sidereal.py#L22-L55
4,133
scivision/pymap3d
pymap3d/sidereal.py
juliandate
def juliandate(time: datetime) -> float: """ Python datetime to Julian time from D.Vallado Fundamentals of Astrodynamics and Applications p.187 and J. Meeus Astronomical Algorithms 1991 Eqn. 7.1 pg. 61 Parameters ---------- time : datetime.datetime time to convert Results ------- jd : float Julian date """ times = np.atleast_1d(time) assert times.ndim == 1 jd = np.empty(times.size) for i, t in enumerate(times): if t.month < 3: year = t.year - 1 month = t.month + 12 else: year = t.year month = t.month A = int(year / 100.0) B = 2 - A + int(A / 4.) C = ((t.second / 60. + t.minute) / 60. + t.hour) / 24. jd[i] = (int(365.25 * (year + 4716)) + int(30.6001 * (month + 1)) + t.day + B - 1524.5 + C) return jd.squeeze()
python
def juliandate(time: datetime) -> float: """ Python datetime to Julian time from D.Vallado Fundamentals of Astrodynamics and Applications p.187 and J. Meeus Astronomical Algorithms 1991 Eqn. 7.1 pg. 61 Parameters ---------- time : datetime.datetime time to convert Results ------- jd : float Julian date """ times = np.atleast_1d(time) assert times.ndim == 1 jd = np.empty(times.size) for i, t in enumerate(times): if t.month < 3: year = t.year - 1 month = t.month + 12 else: year = t.year month = t.month A = int(year / 100.0) B = 2 - A + int(A / 4.) C = ((t.second / 60. + t.minute) / 60. + t.hour) / 24. jd[i] = (int(365.25 * (year + 4716)) + int(30.6001 * (month + 1)) + t.day + B - 1524.5 + C) return jd.squeeze()
[ "def", "juliandate", "(", "time", ":", "datetime", ")", "->", "float", ":", "times", "=", "np", ".", "atleast_1d", "(", "time", ")", "assert", "times", ".", "ndim", "==", "1", "jd", "=", "np", ".", "empty", "(", "times", ".", "size", ")", "for", "i", ",", "t", "in", "enumerate", "(", "times", ")", ":", "if", "t", ".", "month", "<", "3", ":", "year", "=", "t", ".", "year", "-", "1", "month", "=", "t", ".", "month", "+", "12", "else", ":", "year", "=", "t", ".", "year", "month", "=", "t", ".", "month", "A", "=", "int", "(", "year", "/", "100.0", ")", "B", "=", "2", "-", "A", "+", "int", "(", "A", "/", "4.", ")", "C", "=", "(", "(", "t", ".", "second", "/", "60.", "+", "t", ".", "minute", ")", "/", "60.", "+", "t", ".", "hour", ")", "/", "24.", "jd", "[", "i", "]", "=", "(", "int", "(", "365.25", "*", "(", "year", "+", "4716", ")", ")", "+", "int", "(", "30.6001", "*", "(", "month", "+", "1", ")", ")", "+", "t", ".", "day", "+", "B", "-", "1524.5", "+", "C", ")", "return", "jd", ".", "squeeze", "(", ")" ]
Python datetime to Julian time from D.Vallado Fundamentals of Astrodynamics and Applications p.187 and J. Meeus Astronomical Algorithms 1991 Eqn. 7.1 pg. 61 Parameters ---------- time : datetime.datetime time to convert Results ------- jd : float Julian date
[ "Python", "datetime", "to", "Julian", "time" ]
c9cf676594611cdb52ff7e0eca6388c80ed4f63f
https://github.com/scivision/pymap3d/blob/c9cf676594611cdb52ff7e0eca6388c80ed4f63f/pymap3d/sidereal.py#L58-L97
4,134
scivision/pymap3d
pymap3d/sidereal.py
julian2sidereal
def julian2sidereal(Jdate: float) -> float: """ Convert Julian time to sidereal time D. Vallado Ed. 4 Parameters ---------- Jdate: float Julian centuries from J2000.0 Results ------- tsr : float Sidereal time """ jdate = np.atleast_1d(Jdate) assert jdate.ndim == 1 tsr = np.empty(jdate.size) for i, jd in enumerate(jdate): # %% Vallado Eq. 3-42 p. 184, Seidelmann 3.311-1 tUT1 = (jd - 2451545.0) / 36525. # Eqn. 3-47 p. 188 gmst_sec = (67310.54841 + (876600 * 3600 + 8640184.812866) * tUT1 + 0.093104 * tUT1**2 - 6.2e-6 * tUT1**3) # 1/86400 and %(2*pi) implied by units of radians tsr[i] = gmst_sec * (2 * pi) / 86400. % (2 * pi) return tsr.squeeze()
python
def julian2sidereal(Jdate: float) -> float: """ Convert Julian time to sidereal time D. Vallado Ed. 4 Parameters ---------- Jdate: float Julian centuries from J2000.0 Results ------- tsr : float Sidereal time """ jdate = np.atleast_1d(Jdate) assert jdate.ndim == 1 tsr = np.empty(jdate.size) for i, jd in enumerate(jdate): # %% Vallado Eq. 3-42 p. 184, Seidelmann 3.311-1 tUT1 = (jd - 2451545.0) / 36525. # Eqn. 3-47 p. 188 gmst_sec = (67310.54841 + (876600 * 3600 + 8640184.812866) * tUT1 + 0.093104 * tUT1**2 - 6.2e-6 * tUT1**3) # 1/86400 and %(2*pi) implied by units of radians tsr[i] = gmst_sec * (2 * pi) / 86400. % (2 * pi) return tsr.squeeze()
[ "def", "julian2sidereal", "(", "Jdate", ":", "float", ")", "->", "float", ":", "jdate", "=", "np", ".", "atleast_1d", "(", "Jdate", ")", "assert", "jdate", ".", "ndim", "==", "1", "tsr", "=", "np", ".", "empty", "(", "jdate", ".", "size", ")", "for", "i", ",", "jd", "in", "enumerate", "(", "jdate", ")", ":", "# %% Vallado Eq. 3-42 p. 184, Seidelmann 3.311-1", "tUT1", "=", "(", "jd", "-", "2451545.0", ")", "/", "36525.", "# Eqn. 3-47 p. 188", "gmst_sec", "=", "(", "67310.54841", "+", "(", "876600", "*", "3600", "+", "8640184.812866", ")", "*", "tUT1", "+", "0.093104", "*", "tUT1", "**", "2", "-", "6.2e-6", "*", "tUT1", "**", "3", ")", "# 1/86400 and %(2*pi) implied by units of radians", "tsr", "[", "i", "]", "=", "gmst_sec", "*", "(", "2", "*", "pi", ")", "/", "86400.", "%", "(", "2", "*", "pi", ")", "return", "tsr", ".", "squeeze", "(", ")" ]
Convert Julian time to sidereal time D. Vallado Ed. 4 Parameters ---------- Jdate: float Julian centuries from J2000.0 Results ------- tsr : float Sidereal time
[ "Convert", "Julian", "time", "to", "sidereal", "time" ]
c9cf676594611cdb52ff7e0eca6388c80ed4f63f
https://github.com/scivision/pymap3d/blob/c9cf676594611cdb52ff7e0eca6388c80ed4f63f/pymap3d/sidereal.py#L100-L135
4,135
scivision/pymap3d
pymap3d/ecef.py
get_radius_normal
def get_radius_normal(lat_radians: float, ell: Ellipsoid = None) -> float: """ Compute normal radius of planetary body Parameters ---------- lat_radians : float latitude in radians ell : Ellipsoid, optional reference ellipsoid Returns ------- radius : float normal radius (meters) """ if ell is None: ell = Ellipsoid() a = ell.a b = ell.b return a**2 / sqrt(a**2 * cos(lat_radians)**2 + b**2 * sin(lat_radians)**2)
python
def get_radius_normal(lat_radians: float, ell: Ellipsoid = None) -> float: """ Compute normal radius of planetary body Parameters ---------- lat_radians : float latitude in radians ell : Ellipsoid, optional reference ellipsoid Returns ------- radius : float normal radius (meters) """ if ell is None: ell = Ellipsoid() a = ell.a b = ell.b return a**2 / sqrt(a**2 * cos(lat_radians)**2 + b**2 * sin(lat_radians)**2)
[ "def", "get_radius_normal", "(", "lat_radians", ":", "float", ",", "ell", ":", "Ellipsoid", "=", "None", ")", "->", "float", ":", "if", "ell", "is", "None", ":", "ell", "=", "Ellipsoid", "(", ")", "a", "=", "ell", ".", "a", "b", "=", "ell", ".", "b", "return", "a", "**", "2", "/", "sqrt", "(", "a", "**", "2", "*", "cos", "(", "lat_radians", ")", "**", "2", "+", "b", "**", "2", "*", "sin", "(", "lat_radians", ")", "**", "2", ")" ]
Compute normal radius of planetary body Parameters ---------- lat_radians : float latitude in radians ell : Ellipsoid, optional reference ellipsoid Returns ------- radius : float normal radius (meters)
[ "Compute", "normal", "radius", "of", "planetary", "body" ]
c9cf676594611cdb52ff7e0eca6388c80ed4f63f
https://github.com/scivision/pymap3d/blob/c9cf676594611cdb52ff7e0eca6388c80ed4f63f/pymap3d/ecef.py#L70-L94
4,136
scivision/pymap3d
pymap3d/ecef.py
ecef2enuv
def ecef2enuv(u: float, v: float, w: float, lat0: float, lon0: float, deg: bool = True) -> Tuple[float, float, float]: """ VECTOR from observer to target ECEF => ENU Parameters ---------- u : float or numpy.ndarray of float target x ECEF coordinate (meters) v : float or numpy.ndarray of float target y ECEF coordinate (meters) w : float or numpy.ndarray of float target z ECEF coordinate (meters) lat0 : float Observer geodetic latitude lon0 : float Observer geodetic longitude h0 : float observer altitude above geodetic ellipsoid (meters) deg : bool, optional degrees input/output (False: radians in/out) Returns ------- uEast : float or numpy.ndarray of float target east ENU coordinate (meters) vNorth : float or numpy.ndarray of float target north ENU coordinate (meters) wUp : float or numpy.ndarray of float target up ENU coordinate (meters) """ if deg: lat0 = radians(lat0) lon0 = radians(lon0) t = cos(lon0) * u + sin(lon0) * v uEast = -sin(lon0) * u + cos(lon0) * v wUp = cos(lat0) * t + sin(lat0) * w vNorth = -sin(lat0) * t + cos(lat0) * w return uEast, vNorth, wUp
python
def ecef2enuv(u: float, v: float, w: float, lat0: float, lon0: float, deg: bool = True) -> Tuple[float, float, float]: """ VECTOR from observer to target ECEF => ENU Parameters ---------- u : float or numpy.ndarray of float target x ECEF coordinate (meters) v : float or numpy.ndarray of float target y ECEF coordinate (meters) w : float or numpy.ndarray of float target z ECEF coordinate (meters) lat0 : float Observer geodetic latitude lon0 : float Observer geodetic longitude h0 : float observer altitude above geodetic ellipsoid (meters) deg : bool, optional degrees input/output (False: radians in/out) Returns ------- uEast : float or numpy.ndarray of float target east ENU coordinate (meters) vNorth : float or numpy.ndarray of float target north ENU coordinate (meters) wUp : float or numpy.ndarray of float target up ENU coordinate (meters) """ if deg: lat0 = radians(lat0) lon0 = radians(lon0) t = cos(lon0) * u + sin(lon0) * v uEast = -sin(lon0) * u + cos(lon0) * v wUp = cos(lat0) * t + sin(lat0) * w vNorth = -sin(lat0) * t + cos(lat0) * w return uEast, vNorth, wUp
[ "def", "ecef2enuv", "(", "u", ":", "float", ",", "v", ":", "float", ",", "w", ":", "float", ",", "lat0", ":", "float", ",", "lon0", ":", "float", ",", "deg", ":", "bool", "=", "True", ")", "->", "Tuple", "[", "float", ",", "float", ",", "float", "]", ":", "if", "deg", ":", "lat0", "=", "radians", "(", "lat0", ")", "lon0", "=", "radians", "(", "lon0", ")", "t", "=", "cos", "(", "lon0", ")", "*", "u", "+", "sin", "(", "lon0", ")", "*", "v", "uEast", "=", "-", "sin", "(", "lon0", ")", "*", "u", "+", "cos", "(", "lon0", ")", "*", "v", "wUp", "=", "cos", "(", "lat0", ")", "*", "t", "+", "sin", "(", "lat0", ")", "*", "w", "vNorth", "=", "-", "sin", "(", "lat0", ")", "*", "t", "+", "cos", "(", "lat0", ")", "*", "w", "return", "uEast", ",", "vNorth", ",", "wUp" ]
VECTOR from observer to target ECEF => ENU Parameters ---------- u : float or numpy.ndarray of float target x ECEF coordinate (meters) v : float or numpy.ndarray of float target y ECEF coordinate (meters) w : float or numpy.ndarray of float target z ECEF coordinate (meters) lat0 : float Observer geodetic latitude lon0 : float Observer geodetic longitude h0 : float observer altitude above geodetic ellipsoid (meters) deg : bool, optional degrees input/output (False: radians in/out) Returns ------- uEast : float or numpy.ndarray of float target east ENU coordinate (meters) vNorth : float or numpy.ndarray of float target north ENU coordinate (meters) wUp : float or numpy.ndarray of float target up ENU coordinate (meters)
[ "VECTOR", "from", "observer", "to", "target", "ECEF", "=", ">", "ENU" ]
c9cf676594611cdb52ff7e0eca6388c80ed4f63f
https://github.com/scivision/pymap3d/blob/c9cf676594611cdb52ff7e0eca6388c80ed4f63f/pymap3d/ecef.py#L233-L274
4,137
scivision/pymap3d
pymap3d/ecef.py
ecef2enu
def ecef2enu(x: float, y: float, z: float, lat0: float, lon0: float, h0: float, ell: Ellipsoid = None, deg: bool = True) -> Tuple[float, float, float]: """ from observer to target, ECEF => ENU Parameters ---------- x : float or numpy.ndarray of float target x ECEF coordinate (meters) y : float or numpy.ndarray of float target y ECEF coordinate (meters) z : float or numpy.ndarray of float target z ECEF coordinate (meters) lat0 : float Observer geodetic latitude lon0 : float Observer geodetic longitude h0 : float observer altitude above geodetic ellipsoid (meters) ell : Ellipsoid, optional reference ellipsoid deg : bool, optional degrees input/output (False: radians in/out) Returns ------- East : float or numpy.ndarray of float target east ENU coordinate (meters) North : float or numpy.ndarray of float target north ENU coordinate (meters) Up : float or numpy.ndarray of float target up ENU coordinate (meters) """ x0, y0, z0 = geodetic2ecef(lat0, lon0, h0, ell, deg=deg) return uvw2enu(x - x0, y - y0, z - z0, lat0, lon0, deg=deg)
python
def ecef2enu(x: float, y: float, z: float, lat0: float, lon0: float, h0: float, ell: Ellipsoid = None, deg: bool = True) -> Tuple[float, float, float]: """ from observer to target, ECEF => ENU Parameters ---------- x : float or numpy.ndarray of float target x ECEF coordinate (meters) y : float or numpy.ndarray of float target y ECEF coordinate (meters) z : float or numpy.ndarray of float target z ECEF coordinate (meters) lat0 : float Observer geodetic latitude lon0 : float Observer geodetic longitude h0 : float observer altitude above geodetic ellipsoid (meters) ell : Ellipsoid, optional reference ellipsoid deg : bool, optional degrees input/output (False: radians in/out) Returns ------- East : float or numpy.ndarray of float target east ENU coordinate (meters) North : float or numpy.ndarray of float target north ENU coordinate (meters) Up : float or numpy.ndarray of float target up ENU coordinate (meters) """ x0, y0, z0 = geodetic2ecef(lat0, lon0, h0, ell, deg=deg) return uvw2enu(x - x0, y - y0, z - z0, lat0, lon0, deg=deg)
[ "def", "ecef2enu", "(", "x", ":", "float", ",", "y", ":", "float", ",", "z", ":", "float", ",", "lat0", ":", "float", ",", "lon0", ":", "float", ",", "h0", ":", "float", ",", "ell", ":", "Ellipsoid", "=", "None", ",", "deg", ":", "bool", "=", "True", ")", "->", "Tuple", "[", "float", ",", "float", ",", "float", "]", ":", "x0", ",", "y0", ",", "z0", "=", "geodetic2ecef", "(", "lat0", ",", "lon0", ",", "h0", ",", "ell", ",", "deg", "=", "deg", ")", "return", "uvw2enu", "(", "x", "-", "x0", ",", "y", "-", "y0", ",", "z", "-", "z0", ",", "lat0", ",", "lon0", ",", "deg", "=", "deg", ")" ]
from observer to target, ECEF => ENU Parameters ---------- x : float or numpy.ndarray of float target x ECEF coordinate (meters) y : float or numpy.ndarray of float target y ECEF coordinate (meters) z : float or numpy.ndarray of float target z ECEF coordinate (meters) lat0 : float Observer geodetic latitude lon0 : float Observer geodetic longitude h0 : float observer altitude above geodetic ellipsoid (meters) ell : Ellipsoid, optional reference ellipsoid deg : bool, optional degrees input/output (False: radians in/out) Returns ------- East : float or numpy.ndarray of float target east ENU coordinate (meters) North : float or numpy.ndarray of float target north ENU coordinate (meters) Up : float or numpy.ndarray of float target up ENU coordinate (meters)
[ "from", "observer", "to", "target", "ECEF", "=", ">", "ENU" ]
c9cf676594611cdb52ff7e0eca6388c80ed4f63f
https://github.com/scivision/pymap3d/blob/c9cf676594611cdb52ff7e0eca6388c80ed4f63f/pymap3d/ecef.py#L277-L314
4,138
scivision/pymap3d
pymap3d/ecef.py
eci2geodetic
def eci2geodetic(eci: np.ndarray, t: datetime, useastropy: bool = True) -> Tuple[float, float, float]: """ convert ECI to geodetic coordinates Parameters ---------- eci : tuple of float [meters] Nx3 target ECI location (x,y,z) t : datetime.datetime, float length N vector of datetime OR greenwich sidereal time angle [radians]. Results ------- lat : float geodetic latitude lon : float geodetic longitude alt : float altitude above ellipsoid (meters) Notes ----- Conversion is idealized: doesn't consider nutations, perterbations, etc. like the IAU-76/FK5 or IAU-2000/2006 model-based conversions from ECI to ECEF eci2geodetic() a.k.a. eci2lla() """ ecef = np.atleast_2d(eci2ecef(eci, t, useastropy=useastropy)) return np.asarray(ecef2geodetic(ecef[:, 0], ecef[:, 1], ecef[:, 2])).squeeze()
python
def eci2geodetic(eci: np.ndarray, t: datetime, useastropy: bool = True) -> Tuple[float, float, float]: """ convert ECI to geodetic coordinates Parameters ---------- eci : tuple of float [meters] Nx3 target ECI location (x,y,z) t : datetime.datetime, float length N vector of datetime OR greenwich sidereal time angle [radians]. Results ------- lat : float geodetic latitude lon : float geodetic longitude alt : float altitude above ellipsoid (meters) Notes ----- Conversion is idealized: doesn't consider nutations, perterbations, etc. like the IAU-76/FK5 or IAU-2000/2006 model-based conversions from ECI to ECEF eci2geodetic() a.k.a. eci2lla() """ ecef = np.atleast_2d(eci2ecef(eci, t, useastropy=useastropy)) return np.asarray(ecef2geodetic(ecef[:, 0], ecef[:, 1], ecef[:, 2])).squeeze()
[ "def", "eci2geodetic", "(", "eci", ":", "np", ".", "ndarray", ",", "t", ":", "datetime", ",", "useastropy", ":", "bool", "=", "True", ")", "->", "Tuple", "[", "float", ",", "float", ",", "float", "]", ":", "ecef", "=", "np", ".", "atleast_2d", "(", "eci2ecef", "(", "eci", ",", "t", ",", "useastropy", "=", "useastropy", ")", ")", "return", "np", ".", "asarray", "(", "ecef2geodetic", "(", "ecef", "[", ":", ",", "0", "]", ",", "ecef", "[", ":", ",", "1", "]", ",", "ecef", "[", ":", ",", "2", "]", ")", ")", ".", "squeeze", "(", ")" ]
convert ECI to geodetic coordinates Parameters ---------- eci : tuple of float [meters] Nx3 target ECI location (x,y,z) t : datetime.datetime, float length N vector of datetime OR greenwich sidereal time angle [radians]. Results ------- lat : float geodetic latitude lon : float geodetic longitude alt : float altitude above ellipsoid (meters) Notes ----- Conversion is idealized: doesn't consider nutations, perterbations, etc. like the IAU-76/FK5 or IAU-2000/2006 model-based conversions from ECI to ECEF eci2geodetic() a.k.a. eci2lla()
[ "convert", "ECI", "to", "geodetic", "coordinates" ]
c9cf676594611cdb52ff7e0eca6388c80ed4f63f
https://github.com/scivision/pymap3d/blob/c9cf676594611cdb52ff7e0eca6388c80ed4f63f/pymap3d/ecef.py#L384-L416
4,139
scivision/pymap3d
pymap3d/ecef.py
enu2ecef
def enu2ecef(e1: float, n1: float, u1: float, lat0: float, lon0: float, h0: float, ell: Ellipsoid = None, deg: bool = True) -> Tuple[float, float, float]: """ ENU to ECEF Parameters ---------- e1 : float or numpy.ndarray of float target east ENU coordinate (meters) n1 : float or numpy.ndarray of float target north ENU coordinate (meters) u1 : float or numpy.ndarray of float target up ENU coordinate (meters) lat0 : float Observer geodetic latitude lon0 : float Observer geodetic longitude h0 : float observer altitude above geodetic ellipsoid (meters) ell : Ellipsoid, optional reference ellipsoid deg : bool, optional degrees input/output (False: radians in/out) Results ------- x : float or numpy.ndarray of float target x ECEF coordinate (meters) y : float or numpy.ndarray of float target y ECEF coordinate (meters) z : float or numpy.ndarray of float target z ECEF coordinate (meters) """ x0, y0, z0 = geodetic2ecef(lat0, lon0, h0, ell, deg=deg) dx, dy, dz = enu2uvw(e1, n1, u1, lat0, lon0, deg=deg) return x0 + dx, y0 + dy, z0 + dz
python
def enu2ecef(e1: float, n1: float, u1: float, lat0: float, lon0: float, h0: float, ell: Ellipsoid = None, deg: bool = True) -> Tuple[float, float, float]: """ ENU to ECEF Parameters ---------- e1 : float or numpy.ndarray of float target east ENU coordinate (meters) n1 : float or numpy.ndarray of float target north ENU coordinate (meters) u1 : float or numpy.ndarray of float target up ENU coordinate (meters) lat0 : float Observer geodetic latitude lon0 : float Observer geodetic longitude h0 : float observer altitude above geodetic ellipsoid (meters) ell : Ellipsoid, optional reference ellipsoid deg : bool, optional degrees input/output (False: radians in/out) Results ------- x : float or numpy.ndarray of float target x ECEF coordinate (meters) y : float or numpy.ndarray of float target y ECEF coordinate (meters) z : float or numpy.ndarray of float target z ECEF coordinate (meters) """ x0, y0, z0 = geodetic2ecef(lat0, lon0, h0, ell, deg=deg) dx, dy, dz = enu2uvw(e1, n1, u1, lat0, lon0, deg=deg) return x0 + dx, y0 + dy, z0 + dz
[ "def", "enu2ecef", "(", "e1", ":", "float", ",", "n1", ":", "float", ",", "u1", ":", "float", ",", "lat0", ":", "float", ",", "lon0", ":", "float", ",", "h0", ":", "float", ",", "ell", ":", "Ellipsoid", "=", "None", ",", "deg", ":", "bool", "=", "True", ")", "->", "Tuple", "[", "float", ",", "float", ",", "float", "]", ":", "x0", ",", "y0", ",", "z0", "=", "geodetic2ecef", "(", "lat0", ",", "lon0", ",", "h0", ",", "ell", ",", "deg", "=", "deg", ")", "dx", ",", "dy", ",", "dz", "=", "enu2uvw", "(", "e1", ",", "n1", ",", "u1", ",", "lat0", ",", "lon0", ",", "deg", "=", "deg", ")", "return", "x0", "+", "dx", ",", "y0", "+", "dy", ",", "z0", "+", "dz" ]
ENU to ECEF Parameters ---------- e1 : float or numpy.ndarray of float target east ENU coordinate (meters) n1 : float or numpy.ndarray of float target north ENU coordinate (meters) u1 : float or numpy.ndarray of float target up ENU coordinate (meters) lat0 : float Observer geodetic latitude lon0 : float Observer geodetic longitude h0 : float observer altitude above geodetic ellipsoid (meters) ell : Ellipsoid, optional reference ellipsoid deg : bool, optional degrees input/output (False: radians in/out) Results ------- x : float or numpy.ndarray of float target x ECEF coordinate (meters) y : float or numpy.ndarray of float target y ECEF coordinate (meters) z : float or numpy.ndarray of float target z ECEF coordinate (meters)
[ "ENU", "to", "ECEF" ]
c9cf676594611cdb52ff7e0eca6388c80ed4f63f
https://github.com/scivision/pymap3d/blob/c9cf676594611cdb52ff7e0eca6388c80ed4f63f/pymap3d/ecef.py#L419-L458
4,140
scivision/pymap3d
pymap3d/ned.py
aer2ned
def aer2ned(az: float, elev: float, slantRange: float, deg: bool = True) -> Tuple[float, float, float]: """ converts azimuth, elevation, range to target from observer to North, East, Down Parameters ----------- az : float or numpy.ndarray of float azimuth elev : float or numpy.ndarray of float elevation slantRange : float or numpy.ndarray of float slant range [meters] deg : bool, optional degrees input/output (False: radians in/out) Results ------- n : float or numpy.ndarray of float North NED coordinate (meters) e : float or numpy.ndarray of float East NED coordinate (meters) d : float or numpy.ndarray of float Down NED coordinate (meters) """ e, n, u = aer2enu(az, elev, slantRange, deg=deg) return n, e, -u
python
def aer2ned(az: float, elev: float, slantRange: float, deg: bool = True) -> Tuple[float, float, float]: """ converts azimuth, elevation, range to target from observer to North, East, Down Parameters ----------- az : float or numpy.ndarray of float azimuth elev : float or numpy.ndarray of float elevation slantRange : float or numpy.ndarray of float slant range [meters] deg : bool, optional degrees input/output (False: radians in/out) Results ------- n : float or numpy.ndarray of float North NED coordinate (meters) e : float or numpy.ndarray of float East NED coordinate (meters) d : float or numpy.ndarray of float Down NED coordinate (meters) """ e, n, u = aer2enu(az, elev, slantRange, deg=deg) return n, e, -u
[ "def", "aer2ned", "(", "az", ":", "float", ",", "elev", ":", "float", ",", "slantRange", ":", "float", ",", "deg", ":", "bool", "=", "True", ")", "->", "Tuple", "[", "float", ",", "float", ",", "float", "]", ":", "e", ",", "n", ",", "u", "=", "aer2enu", "(", "az", ",", "elev", ",", "slantRange", ",", "deg", "=", "deg", ")", "return", "n", ",", "e", ",", "-", "u" ]
converts azimuth, elevation, range to target from observer to North, East, Down Parameters ----------- az : float or numpy.ndarray of float azimuth elev : float or numpy.ndarray of float elevation slantRange : float or numpy.ndarray of float slant range [meters] deg : bool, optional degrees input/output (False: radians in/out) Results ------- n : float or numpy.ndarray of float North NED coordinate (meters) e : float or numpy.ndarray of float East NED coordinate (meters) d : float or numpy.ndarray of float Down NED coordinate (meters)
[ "converts", "azimuth", "elevation", "range", "to", "target", "from", "observer", "to", "North", "East", "Down" ]
c9cf676594611cdb52ff7e0eca6388c80ed4f63f
https://github.com/scivision/pymap3d/blob/c9cf676594611cdb52ff7e0eca6388c80ed4f63f/pymap3d/ned.py#L7-L35
4,141
scivision/pymap3d
pymap3d/ned.py
ned2aer
def ned2aer(n: float, e: float, d: float, deg: bool = True) -> Tuple[float, float, float]: """ converts North, East, Down to azimuth, elevation, range Parameters ---------- n : float or numpy.ndarray of float North NED coordinate (meters) e : float or numpy.ndarray of float East NED coordinate (meters) d : float or numpy.ndarray of float Down NED coordinate (meters) deg : bool, optional degrees input/output (False: radians in/out) Results ------- az : float or numpy.ndarray of float azimuth elev : float or numpy.ndarray of float elevation slantRange : float or numpy.ndarray of float slant range [meters] """ return enu2aer(e, n, -d, deg=deg)
python
def ned2aer(n: float, e: float, d: float, deg: bool = True) -> Tuple[float, float, float]: """ converts North, East, Down to azimuth, elevation, range Parameters ---------- n : float or numpy.ndarray of float North NED coordinate (meters) e : float or numpy.ndarray of float East NED coordinate (meters) d : float or numpy.ndarray of float Down NED coordinate (meters) deg : bool, optional degrees input/output (False: radians in/out) Results ------- az : float or numpy.ndarray of float azimuth elev : float or numpy.ndarray of float elevation slantRange : float or numpy.ndarray of float slant range [meters] """ return enu2aer(e, n, -d, deg=deg)
[ "def", "ned2aer", "(", "n", ":", "float", ",", "e", ":", "float", ",", "d", ":", "float", ",", "deg", ":", "bool", "=", "True", ")", "->", "Tuple", "[", "float", ",", "float", ",", "float", "]", ":", "return", "enu2aer", "(", "e", ",", "n", ",", "-", "d", ",", "deg", "=", "deg", ")" ]
converts North, East, Down to azimuth, elevation, range Parameters ---------- n : float or numpy.ndarray of float North NED coordinate (meters) e : float or numpy.ndarray of float East NED coordinate (meters) d : float or numpy.ndarray of float Down NED coordinate (meters) deg : bool, optional degrees input/output (False: radians in/out) Results ------- az : float or numpy.ndarray of float azimuth elev : float or numpy.ndarray of float elevation slantRange : float or numpy.ndarray of float slant range [meters]
[ "converts", "North", "East", "Down", "to", "azimuth", "elevation", "range" ]
c9cf676594611cdb52ff7e0eca6388c80ed4f63f
https://github.com/scivision/pymap3d/blob/c9cf676594611cdb52ff7e0eca6388c80ed4f63f/pymap3d/ned.py#L38-L65
4,142
scivision/pymap3d
pymap3d/ned.py
ned2geodetic
def ned2geodetic(n: float, e: float, d: float, lat0: float, lon0: float, h0: float, ell: Ellipsoid = None, deg: bool = True) -> Tuple[float, float, float]: """ Converts North, East, Down to target latitude, longitude, altitude Parameters ---------- n : float or numpy.ndarray of float North NED coordinate (meters) e : float or numpy.ndarray of float East NED coordinate (meters) d : float or numpy.ndarray of float Down NED coordinate (meters) lat0 : float Observer geodetic latitude lon0 : float Observer geodetic longitude h0 : float observer altitude above geodetic ellipsoid (meters) ell : Ellipsoid, optional reference ellipsoid deg : bool, optional degrees input/output (False: radians in/out) Results ------- lat : float target geodetic latitude lon : float target geodetic longitude h : float target altitude above geodetic ellipsoid (meters) """ x, y, z = enu2ecef(e, n, -d, lat0, lon0, h0, ell, deg=deg) return ecef2geodetic(x, y, z, ell, deg=deg)
python
def ned2geodetic(n: float, e: float, d: float, lat0: float, lon0: float, h0: float, ell: Ellipsoid = None, deg: bool = True) -> Tuple[float, float, float]: """ Converts North, East, Down to target latitude, longitude, altitude Parameters ---------- n : float or numpy.ndarray of float North NED coordinate (meters) e : float or numpy.ndarray of float East NED coordinate (meters) d : float or numpy.ndarray of float Down NED coordinate (meters) lat0 : float Observer geodetic latitude lon0 : float Observer geodetic longitude h0 : float observer altitude above geodetic ellipsoid (meters) ell : Ellipsoid, optional reference ellipsoid deg : bool, optional degrees input/output (False: radians in/out) Results ------- lat : float target geodetic latitude lon : float target geodetic longitude h : float target altitude above geodetic ellipsoid (meters) """ x, y, z = enu2ecef(e, n, -d, lat0, lon0, h0, ell, deg=deg) return ecef2geodetic(x, y, z, ell, deg=deg)
[ "def", "ned2geodetic", "(", "n", ":", "float", ",", "e", ":", "float", ",", "d", ":", "float", ",", "lat0", ":", "float", ",", "lon0", ":", "float", ",", "h0", ":", "float", ",", "ell", ":", "Ellipsoid", "=", "None", ",", "deg", ":", "bool", "=", "True", ")", "->", "Tuple", "[", "float", ",", "float", ",", "float", "]", ":", "x", ",", "y", ",", "z", "=", "enu2ecef", "(", "e", ",", "n", ",", "-", "d", ",", "lat0", ",", "lon0", ",", "h0", ",", "ell", ",", "deg", "=", "deg", ")", "return", "ecef2geodetic", "(", "x", ",", "y", ",", "z", ",", "ell", ",", "deg", "=", "deg", ")" ]
Converts North, East, Down to target latitude, longitude, altitude Parameters ---------- n : float or numpy.ndarray of float North NED coordinate (meters) e : float or numpy.ndarray of float East NED coordinate (meters) d : float or numpy.ndarray of float Down NED coordinate (meters) lat0 : float Observer geodetic latitude lon0 : float Observer geodetic longitude h0 : float observer altitude above geodetic ellipsoid (meters) ell : Ellipsoid, optional reference ellipsoid deg : bool, optional degrees input/output (False: radians in/out) Results ------- lat : float target geodetic latitude lon : float target geodetic longitude h : float target altitude above geodetic ellipsoid (meters)
[ "Converts", "North", "East", "Down", "to", "target", "latitude", "longitude", "altitude" ]
c9cf676594611cdb52ff7e0eca6388c80ed4f63f
https://github.com/scivision/pymap3d/blob/c9cf676594611cdb52ff7e0eca6388c80ed4f63f/pymap3d/ned.py#L68-L107
4,143
scivision/pymap3d
pymap3d/ned.py
ned2ecef
def ned2ecef(n: float, e: float, d: float, lat0: float, lon0: float, h0: float, ell: Ellipsoid = None, deg: bool = True) -> Tuple[float, float, float]: """ North, East, Down to target ECEF coordinates Parameters ---------- n : float or numpy.ndarray of float North NED coordinate (meters) e : float or numpy.ndarray of float East NED coordinate (meters) d : float or numpy.ndarray of float Down NED coordinate (meters) lat0 : float Observer geodetic latitude lon0 : float Observer geodetic longitude h0 : float observer altitude above geodetic ellipsoid (meters) ell : Ellipsoid, optional reference ellipsoid deg : bool, optional degrees input/output (False: radians in/out) Results ------- x : float or numpy.ndarray of float ECEF x coordinate (meters) y : float or numpy.ndarray of float ECEF y coordinate (meters) z : float or numpy.ndarray of float ECEF z coordinate (meters) """ return enu2ecef(e, n, -d, lat0, lon0, h0, ell, deg=deg)
python
def ned2ecef(n: float, e: float, d: float, lat0: float, lon0: float, h0: float, ell: Ellipsoid = None, deg: bool = True) -> Tuple[float, float, float]: """ North, East, Down to target ECEF coordinates Parameters ---------- n : float or numpy.ndarray of float North NED coordinate (meters) e : float or numpy.ndarray of float East NED coordinate (meters) d : float or numpy.ndarray of float Down NED coordinate (meters) lat0 : float Observer geodetic latitude lon0 : float Observer geodetic longitude h0 : float observer altitude above geodetic ellipsoid (meters) ell : Ellipsoid, optional reference ellipsoid deg : bool, optional degrees input/output (False: radians in/out) Results ------- x : float or numpy.ndarray of float ECEF x coordinate (meters) y : float or numpy.ndarray of float ECEF y coordinate (meters) z : float or numpy.ndarray of float ECEF z coordinate (meters) """ return enu2ecef(e, n, -d, lat0, lon0, h0, ell, deg=deg)
[ "def", "ned2ecef", "(", "n", ":", "float", ",", "e", ":", "float", ",", "d", ":", "float", ",", "lat0", ":", "float", ",", "lon0", ":", "float", ",", "h0", ":", "float", ",", "ell", ":", "Ellipsoid", "=", "None", ",", "deg", ":", "bool", "=", "True", ")", "->", "Tuple", "[", "float", ",", "float", ",", "float", "]", ":", "return", "enu2ecef", "(", "e", ",", "n", ",", "-", "d", ",", "lat0", ",", "lon0", ",", "h0", ",", "ell", ",", "deg", "=", "deg", ")" ]
North, East, Down to target ECEF coordinates Parameters ---------- n : float or numpy.ndarray of float North NED coordinate (meters) e : float or numpy.ndarray of float East NED coordinate (meters) d : float or numpy.ndarray of float Down NED coordinate (meters) lat0 : float Observer geodetic latitude lon0 : float Observer geodetic longitude h0 : float observer altitude above geodetic ellipsoid (meters) ell : Ellipsoid, optional reference ellipsoid deg : bool, optional degrees input/output (False: radians in/out) Results ------- x : float or numpy.ndarray of float ECEF x coordinate (meters) y : float or numpy.ndarray of float ECEF y coordinate (meters) z : float or numpy.ndarray of float ECEF z coordinate (meters)
[ "North", "East", "Down", "to", "target", "ECEF", "coordinates" ]
c9cf676594611cdb52ff7e0eca6388c80ed4f63f
https://github.com/scivision/pymap3d/blob/c9cf676594611cdb52ff7e0eca6388c80ed4f63f/pymap3d/ned.py#L110-L146
4,144
scivision/pymap3d
pymap3d/ned.py
ecef2ned
def ecef2ned(x: float, y: float, z: float, lat0: float, lon0: float, h0: float, ell: Ellipsoid = None, deg: bool = True) -> Tuple[float, float, float]: """ Convert ECEF x,y,z to North, East, Down Parameters ---------- x : float or numpy.ndarray of float ECEF x coordinate (meters) y : float or numpy.ndarray of float ECEF y coordinate (meters) z : float or numpy.ndarray of float ECEF z coordinate (meters) lat0 : float Observer geodetic latitude lon0 : float Observer geodetic longitude h0 : float observer altitude above geodetic ellipsoid (meters) ell : Ellipsoid, optional reference ellipsoid deg : bool, optional degrees input/output (False: radians in/out) Results ------- n : float or numpy.ndarray of float North NED coordinate (meters) e : float or numpy.ndarray of float East NED coordinate (meters) d : float or numpy.ndarray of float Down NED coordinate (meters) """ e, n, u = ecef2enu(x, y, z, lat0, lon0, h0, ell, deg=deg) return n, e, -u
python
def ecef2ned(x: float, y: float, z: float, lat0: float, lon0: float, h0: float, ell: Ellipsoid = None, deg: bool = True) -> Tuple[float, float, float]: """ Convert ECEF x,y,z to North, East, Down Parameters ---------- x : float or numpy.ndarray of float ECEF x coordinate (meters) y : float or numpy.ndarray of float ECEF y coordinate (meters) z : float or numpy.ndarray of float ECEF z coordinate (meters) lat0 : float Observer geodetic latitude lon0 : float Observer geodetic longitude h0 : float observer altitude above geodetic ellipsoid (meters) ell : Ellipsoid, optional reference ellipsoid deg : bool, optional degrees input/output (False: radians in/out) Results ------- n : float or numpy.ndarray of float North NED coordinate (meters) e : float or numpy.ndarray of float East NED coordinate (meters) d : float or numpy.ndarray of float Down NED coordinate (meters) """ e, n, u = ecef2enu(x, y, z, lat0, lon0, h0, ell, deg=deg) return n, e, -u
[ "def", "ecef2ned", "(", "x", ":", "float", ",", "y", ":", "float", ",", "z", ":", "float", ",", "lat0", ":", "float", ",", "lon0", ":", "float", ",", "h0", ":", "float", ",", "ell", ":", "Ellipsoid", "=", "None", ",", "deg", ":", "bool", "=", "True", ")", "->", "Tuple", "[", "float", ",", "float", ",", "float", "]", ":", "e", ",", "n", ",", "u", "=", "ecef2enu", "(", "x", ",", "y", ",", "z", ",", "lat0", ",", "lon0", ",", "h0", ",", "ell", ",", "deg", "=", "deg", ")", "return", "n", ",", "e", ",", "-", "u" ]
Convert ECEF x,y,z to North, East, Down Parameters ---------- x : float or numpy.ndarray of float ECEF x coordinate (meters) y : float or numpy.ndarray of float ECEF y coordinate (meters) z : float or numpy.ndarray of float ECEF z coordinate (meters) lat0 : float Observer geodetic latitude lon0 : float Observer geodetic longitude h0 : float observer altitude above geodetic ellipsoid (meters) ell : Ellipsoid, optional reference ellipsoid deg : bool, optional degrees input/output (False: radians in/out) Results ------- n : float or numpy.ndarray of float North NED coordinate (meters) e : float or numpy.ndarray of float East NED coordinate (meters) d : float or numpy.ndarray of float Down NED coordinate (meters)
[ "Convert", "ECEF", "x", "y", "z", "to", "North", "East", "Down" ]
c9cf676594611cdb52ff7e0eca6388c80ed4f63f
https://github.com/scivision/pymap3d/blob/c9cf676594611cdb52ff7e0eca6388c80ed4f63f/pymap3d/ned.py#L149-L188
4,145
scivision/pymap3d
pymap3d/ned.py
ecef2nedv
def ecef2nedv(x: float, y: float, z: float, lat0: float, lon0: float, deg: bool = True) -> Tuple[float, float, float]: """ for VECTOR between two points Parameters ---------- x : float or numpy.ndarray of float ECEF x coordinate (meters) y : float or numpy.ndarray of float ECEF y coordinate (meters) z : float or numpy.ndarray of float ECEF z coordinate (meters) lat0 : float Observer geodetic latitude lon0 : float Observer geodetic longitude deg : bool, optional degrees input/output (False: radians in/out) Results ------- (Vector) n : float or numpy.ndarray of float North NED coordinate (meters) e : float or numpy.ndarray of float East NED coordinate (meters) d : float or numpy.ndarray of float Down NED coordinate (meters) """ e, n, u = ecef2enuv(x, y, z, lat0, lon0, deg=deg) return n, e, -u
python
def ecef2nedv(x: float, y: float, z: float, lat0: float, lon0: float, deg: bool = True) -> Tuple[float, float, float]: """ for VECTOR between two points Parameters ---------- x : float or numpy.ndarray of float ECEF x coordinate (meters) y : float or numpy.ndarray of float ECEF y coordinate (meters) z : float or numpy.ndarray of float ECEF z coordinate (meters) lat0 : float Observer geodetic latitude lon0 : float Observer geodetic longitude deg : bool, optional degrees input/output (False: radians in/out) Results ------- (Vector) n : float or numpy.ndarray of float North NED coordinate (meters) e : float or numpy.ndarray of float East NED coordinate (meters) d : float or numpy.ndarray of float Down NED coordinate (meters) """ e, n, u = ecef2enuv(x, y, z, lat0, lon0, deg=deg) return n, e, -u
[ "def", "ecef2nedv", "(", "x", ":", "float", ",", "y", ":", "float", ",", "z", ":", "float", ",", "lat0", ":", "float", ",", "lon0", ":", "float", ",", "deg", ":", "bool", "=", "True", ")", "->", "Tuple", "[", "float", ",", "float", ",", "float", "]", ":", "e", ",", "n", ",", "u", "=", "ecef2enuv", "(", "x", ",", "y", ",", "z", ",", "lat0", ",", "lon0", ",", "deg", "=", "deg", ")", "return", "n", ",", "e", ",", "-", "u" ]
for VECTOR between two points Parameters ---------- x : float or numpy.ndarray of float ECEF x coordinate (meters) y : float or numpy.ndarray of float ECEF y coordinate (meters) z : float or numpy.ndarray of float ECEF z coordinate (meters) lat0 : float Observer geodetic latitude lon0 : float Observer geodetic longitude deg : bool, optional degrees input/output (False: radians in/out) Results ------- (Vector) n : float or numpy.ndarray of float North NED coordinate (meters) e : float or numpy.ndarray of float East NED coordinate (meters) d : float or numpy.ndarray of float Down NED coordinate (meters)
[ "for", "VECTOR", "between", "two", "points" ]
c9cf676594611cdb52ff7e0eca6388c80ed4f63f
https://github.com/scivision/pymap3d/blob/c9cf676594611cdb52ff7e0eca6388c80ed4f63f/pymap3d/ned.py#L233-L268
4,146
scivision/pymap3d
pymap3d/vallado.py
azel2radec
def azel2radec(az_deg: float, el_deg: float, lat_deg: float, lon_deg: float, time: datetime) -> Tuple[float, float]: """ converts azimuth, elevation to right ascension, declination Parameters ---------- az_deg : float or numpy.ndarray of float azimuth (clockwise) to point [degrees] el_deg : float or numpy.ndarray of float elevation above horizon to point [degrees] lat_deg : float observer WGS84 latitude [degrees] lon_deg : float observer WGS84 longitude [degrees] time : datetime.datetime time of observation Results ------- ra_deg : float or numpy.ndarray of float right ascension to target [degrees] dec_deg : float or numpy.ndarray of float declination of target [degrees] from D.Vallado Fundamentals of Astrodynamics and Applications p.258-259 """ az = atleast_1d(az_deg) el = atleast_1d(el_deg) lat = atleast_1d(lat_deg) lon = atleast_1d(lon_deg) if az.shape != el.shape: raise ValueError('az and el must be same shape ndarray') if not(lat.size == 1 and lon.size == 1): raise ValueError('need one observer and one or more (az,el).') if ((lat < -90) | (lat > 90)).any(): raise ValueError('-90 <= lat <= 90') az = radians(az) el = radians(el) lat = radians(lat) lon = radians(lon) # %% Vallado "algorithm 28" p 268 dec = arcsin(sin(el) * sin(lat) + cos(el) * cos(lat) * cos(az)) lha = arctan2(-(sin(az) * cos(el)) / cos(dec), (sin(el) - sin(lat) * sin(dec)) / (cos(dec) * cos(lat))) lst = datetime2sidereal(time, lon) # lon, ra in RADIANS """ by definition right ascension [0, 360) degrees """ return degrees(lst - lha) % 360, degrees(dec)
python
def azel2radec(az_deg: float, el_deg: float, lat_deg: float, lon_deg: float, time: datetime) -> Tuple[float, float]: """ converts azimuth, elevation to right ascension, declination Parameters ---------- az_deg : float or numpy.ndarray of float azimuth (clockwise) to point [degrees] el_deg : float or numpy.ndarray of float elevation above horizon to point [degrees] lat_deg : float observer WGS84 latitude [degrees] lon_deg : float observer WGS84 longitude [degrees] time : datetime.datetime time of observation Results ------- ra_deg : float or numpy.ndarray of float right ascension to target [degrees] dec_deg : float or numpy.ndarray of float declination of target [degrees] from D.Vallado Fundamentals of Astrodynamics and Applications p.258-259 """ az = atleast_1d(az_deg) el = atleast_1d(el_deg) lat = atleast_1d(lat_deg) lon = atleast_1d(lon_deg) if az.shape != el.shape: raise ValueError('az and el must be same shape ndarray') if not(lat.size == 1 and lon.size == 1): raise ValueError('need one observer and one or more (az,el).') if ((lat < -90) | (lat > 90)).any(): raise ValueError('-90 <= lat <= 90') az = radians(az) el = radians(el) lat = radians(lat) lon = radians(lon) # %% Vallado "algorithm 28" p 268 dec = arcsin(sin(el) * sin(lat) + cos(el) * cos(lat) * cos(az)) lha = arctan2(-(sin(az) * cos(el)) / cos(dec), (sin(el) - sin(lat) * sin(dec)) / (cos(dec) * cos(lat))) lst = datetime2sidereal(time, lon) # lon, ra in RADIANS """ by definition right ascension [0, 360) degrees """ return degrees(lst - lha) % 360, degrees(dec)
[ "def", "azel2radec", "(", "az_deg", ":", "float", ",", "el_deg", ":", "float", ",", "lat_deg", ":", "float", ",", "lon_deg", ":", "float", ",", "time", ":", "datetime", ")", "->", "Tuple", "[", "float", ",", "float", "]", ":", "az", "=", "atleast_1d", "(", "az_deg", ")", "el", "=", "atleast_1d", "(", "el_deg", ")", "lat", "=", "atleast_1d", "(", "lat_deg", ")", "lon", "=", "atleast_1d", "(", "lon_deg", ")", "if", "az", ".", "shape", "!=", "el", ".", "shape", ":", "raise", "ValueError", "(", "'az and el must be same shape ndarray'", ")", "if", "not", "(", "lat", ".", "size", "==", "1", "and", "lon", ".", "size", "==", "1", ")", ":", "raise", "ValueError", "(", "'need one observer and one or more (az,el).'", ")", "if", "(", "(", "lat", "<", "-", "90", ")", "|", "(", "lat", ">", "90", ")", ")", ".", "any", "(", ")", ":", "raise", "ValueError", "(", "'-90 <= lat <= 90'", ")", "az", "=", "radians", "(", "az", ")", "el", "=", "radians", "(", "el", ")", "lat", "=", "radians", "(", "lat", ")", "lon", "=", "radians", "(", "lon", ")", "# %% Vallado \"algorithm 28\" p 268", "dec", "=", "arcsin", "(", "sin", "(", "el", ")", "*", "sin", "(", "lat", ")", "+", "cos", "(", "el", ")", "*", "cos", "(", "lat", ")", "*", "cos", "(", "az", ")", ")", "lha", "=", "arctan2", "(", "-", "(", "sin", "(", "az", ")", "*", "cos", "(", "el", ")", ")", "/", "cos", "(", "dec", ")", ",", "(", "sin", "(", "el", ")", "-", "sin", "(", "lat", ")", "*", "sin", "(", "dec", ")", ")", "/", "(", "cos", "(", "dec", ")", "*", "cos", "(", "lat", ")", ")", ")", "lst", "=", "datetime2sidereal", "(", "time", ",", "lon", ")", "# lon, ra in RADIANS", "\"\"\" by definition right ascension [0, 360) degrees \"\"\"", "return", "degrees", "(", "lst", "-", "lha", ")", "%", "360", ",", "degrees", "(", "dec", ")" ]
converts azimuth, elevation to right ascension, declination Parameters ---------- az_deg : float or numpy.ndarray of float azimuth (clockwise) to point [degrees] el_deg : float or numpy.ndarray of float elevation above horizon to point [degrees] lat_deg : float observer WGS84 latitude [degrees] lon_deg : float observer WGS84 longitude [degrees] time : datetime.datetime time of observation Results ------- ra_deg : float or numpy.ndarray of float right ascension to target [degrees] dec_deg : float or numpy.ndarray of float declination of target [degrees] from D.Vallado Fundamentals of Astrodynamics and Applications p.258-259
[ "converts", "azimuth", "elevation", "to", "right", "ascension", "declination" ]
c9cf676594611cdb52ff7e0eca6388c80ed4f63f
https://github.com/scivision/pymap3d/blob/c9cf676594611cdb52ff7e0eca6388c80ed4f63f/pymap3d/vallado.py#L19-L80
4,147
scivision/pymap3d
pymap3d/vallado.py
radec2azel
def radec2azel(ra_deg: float, dec_deg: float, lat_deg: float, lon_deg: float, time: datetime) -> Tuple[float, float]: """ converts right ascension, declination to azimuth, elevation Parameters ---------- ra_deg : float or numpy.ndarray of float right ascension to target [degrees] dec_deg : float or numpy.ndarray of float declination to target [degrees] lat_deg : float observer WGS84 latitude [degrees] lon_deg : float observer WGS84 longitude [degrees] time : datetime.datetime time of observation Results ------- az_deg : float or numpy.ndarray of float azimuth clockwise from north to point [degrees] el_deg : float or numpy.ndarray of float elevation above horizon to point [degrees] from D. Vallado "Fundamentals of Astrodynamics and Applications " 4th Edition Ch. 4.4 pg. 266-268 """ ra = atleast_1d(ra_deg) dec = atleast_1d(dec_deg) lat = atleast_1d(lat_deg) lon = atleast_1d(lon_deg) if ra.shape != dec.shape: raise ValueError('az and el must be same shape ndarray') if not(lat.size == 1 and lon.size == 1): raise ValueError('need one observer and one or more (az,el).') if ((lat < -90) | (lat > 90)).any(): raise ValueError('-90 <= lat <= 90') ra = radians(ra) dec = radians(dec) lat = radians(lat) lon = radians(lon) lst = datetime2sidereal(time, lon) # RADIANS # %% Eq. 4-11 p. 267 LOCAL HOUR ANGLE lha = lst - ra # %% #Eq. 4-12 p. 267 el = arcsin(sin(lat) * sin(dec) + cos(lat) * cos(dec) * cos(lha)) # %% combine Eq. 4-13 and 4-14 p. 268 az = arctan2(-sin(lha) * cos(dec) / cos(el), (sin(dec) - sin(el) * sin(lat)) / (cos(el) * cos(lat))) return degrees(az) % 360.0, degrees(el)
python
def radec2azel(ra_deg: float, dec_deg: float, lat_deg: float, lon_deg: float, time: datetime) -> Tuple[float, float]: """ converts right ascension, declination to azimuth, elevation Parameters ---------- ra_deg : float or numpy.ndarray of float right ascension to target [degrees] dec_deg : float or numpy.ndarray of float declination to target [degrees] lat_deg : float observer WGS84 latitude [degrees] lon_deg : float observer WGS84 longitude [degrees] time : datetime.datetime time of observation Results ------- az_deg : float or numpy.ndarray of float azimuth clockwise from north to point [degrees] el_deg : float or numpy.ndarray of float elevation above horizon to point [degrees] from D. Vallado "Fundamentals of Astrodynamics and Applications " 4th Edition Ch. 4.4 pg. 266-268 """ ra = atleast_1d(ra_deg) dec = atleast_1d(dec_deg) lat = atleast_1d(lat_deg) lon = atleast_1d(lon_deg) if ra.shape != dec.shape: raise ValueError('az and el must be same shape ndarray') if not(lat.size == 1 and lon.size == 1): raise ValueError('need one observer and one or more (az,el).') if ((lat < -90) | (lat > 90)).any(): raise ValueError('-90 <= lat <= 90') ra = radians(ra) dec = radians(dec) lat = radians(lat) lon = radians(lon) lst = datetime2sidereal(time, lon) # RADIANS # %% Eq. 4-11 p. 267 LOCAL HOUR ANGLE lha = lst - ra # %% #Eq. 4-12 p. 267 el = arcsin(sin(lat) * sin(dec) + cos(lat) * cos(dec) * cos(lha)) # %% combine Eq. 4-13 and 4-14 p. 268 az = arctan2(-sin(lha) * cos(dec) / cos(el), (sin(dec) - sin(el) * sin(lat)) / (cos(el) * cos(lat))) return degrees(az) % 360.0, degrees(el)
[ "def", "radec2azel", "(", "ra_deg", ":", "float", ",", "dec_deg", ":", "float", ",", "lat_deg", ":", "float", ",", "lon_deg", ":", "float", ",", "time", ":", "datetime", ")", "->", "Tuple", "[", "float", ",", "float", "]", ":", "ra", "=", "atleast_1d", "(", "ra_deg", ")", "dec", "=", "atleast_1d", "(", "dec_deg", ")", "lat", "=", "atleast_1d", "(", "lat_deg", ")", "lon", "=", "atleast_1d", "(", "lon_deg", ")", "if", "ra", ".", "shape", "!=", "dec", ".", "shape", ":", "raise", "ValueError", "(", "'az and el must be same shape ndarray'", ")", "if", "not", "(", "lat", ".", "size", "==", "1", "and", "lon", ".", "size", "==", "1", ")", ":", "raise", "ValueError", "(", "'need one observer and one or more (az,el).'", ")", "if", "(", "(", "lat", "<", "-", "90", ")", "|", "(", "lat", ">", "90", ")", ")", ".", "any", "(", ")", ":", "raise", "ValueError", "(", "'-90 <= lat <= 90'", ")", "ra", "=", "radians", "(", "ra", ")", "dec", "=", "radians", "(", "dec", ")", "lat", "=", "radians", "(", "lat", ")", "lon", "=", "radians", "(", "lon", ")", "lst", "=", "datetime2sidereal", "(", "time", ",", "lon", ")", "# RADIANS", "# %% Eq. 4-11 p. 267 LOCAL HOUR ANGLE", "lha", "=", "lst", "-", "ra", "# %% #Eq. 4-12 p. 267", "el", "=", "arcsin", "(", "sin", "(", "lat", ")", "*", "sin", "(", "dec", ")", "+", "cos", "(", "lat", ")", "*", "cos", "(", "dec", ")", "*", "cos", "(", "lha", ")", ")", "# %% combine Eq. 4-13 and 4-14 p. 268", "az", "=", "arctan2", "(", "-", "sin", "(", "lha", ")", "*", "cos", "(", "dec", ")", "/", "cos", "(", "el", ")", ",", "(", "sin", "(", "dec", ")", "-", "sin", "(", "el", ")", "*", "sin", "(", "lat", ")", ")", "/", "(", "cos", "(", "el", ")", "*", "cos", "(", "lat", ")", ")", ")", "return", "degrees", "(", "az", ")", "%", "360.0", ",", "degrees", "(", "el", ")" ]
converts right ascension, declination to azimuth, elevation Parameters ---------- ra_deg : float or numpy.ndarray of float right ascension to target [degrees] dec_deg : float or numpy.ndarray of float declination to target [degrees] lat_deg : float observer WGS84 latitude [degrees] lon_deg : float observer WGS84 longitude [degrees] time : datetime.datetime time of observation Results ------- az_deg : float or numpy.ndarray of float azimuth clockwise from north to point [degrees] el_deg : float or numpy.ndarray of float elevation above horizon to point [degrees] from D. Vallado "Fundamentals of Astrodynamics and Applications " 4th Edition Ch. 4.4 pg. 266-268
[ "converts", "right", "ascension", "declination", "to", "azimuth", "elevation" ]
c9cf676594611cdb52ff7e0eca6388c80ed4f63f
https://github.com/scivision/pymap3d/blob/c9cf676594611cdb52ff7e0eca6388c80ed4f63f/pymap3d/vallado.py#L83-L146
4,148
scivision/pymap3d
pymap3d/aer.py
ecef2aer
def ecef2aer(x: float, y: float, z: float, lat0: float, lon0: float, h0: float, ell=None, deg: bool = True) -> Tuple[float, float, float]: """ gives azimuth, elevation and slant range from an Observer to a Point with ECEF coordinates. ECEF input location is with units of meters Parameters ---------- x : float or numpy.ndarray of float ECEF x coordinate (meters) y : float or numpy.ndarray of float ECEF y coordinate (meters) z : float or numpy.ndarray of float ECEF z coordinate (meters) lat0 : float Observer geodetic latitude lon0 : float Observer geodetic longitude h0 : float observer altitude above geodetic ellipsoid (meters) ell : Ellipsoid, optional reference ellipsoid deg : bool, optional degrees input/output (False: radians in/out) Returns ------- az : float or numpy.ndarray of float azimuth to target el : float or numpy.ndarray of float elevation to target srange : float or numpy.ndarray of float slant range [meters] """ xEast, yNorth, zUp = ecef2enu(x, y, z, lat0, lon0, h0, ell, deg=deg) return enu2aer(xEast, yNorth, zUp, deg=deg)
python
def ecef2aer(x: float, y: float, z: float, lat0: float, lon0: float, h0: float, ell=None, deg: bool = True) -> Tuple[float, float, float]: """ gives azimuth, elevation and slant range from an Observer to a Point with ECEF coordinates. ECEF input location is with units of meters Parameters ---------- x : float or numpy.ndarray of float ECEF x coordinate (meters) y : float or numpy.ndarray of float ECEF y coordinate (meters) z : float or numpy.ndarray of float ECEF z coordinate (meters) lat0 : float Observer geodetic latitude lon0 : float Observer geodetic longitude h0 : float observer altitude above geodetic ellipsoid (meters) ell : Ellipsoid, optional reference ellipsoid deg : bool, optional degrees input/output (False: radians in/out) Returns ------- az : float or numpy.ndarray of float azimuth to target el : float or numpy.ndarray of float elevation to target srange : float or numpy.ndarray of float slant range [meters] """ xEast, yNorth, zUp = ecef2enu(x, y, z, lat0, lon0, h0, ell, deg=deg) return enu2aer(xEast, yNorth, zUp, deg=deg)
[ "def", "ecef2aer", "(", "x", ":", "float", ",", "y", ":", "float", ",", "z", ":", "float", ",", "lat0", ":", "float", ",", "lon0", ":", "float", ",", "h0", ":", "float", ",", "ell", "=", "None", ",", "deg", ":", "bool", "=", "True", ")", "->", "Tuple", "[", "float", ",", "float", ",", "float", "]", ":", "xEast", ",", "yNorth", ",", "zUp", "=", "ecef2enu", "(", "x", ",", "y", ",", "z", ",", "lat0", ",", "lon0", ",", "h0", ",", "ell", ",", "deg", "=", "deg", ")", "return", "enu2aer", "(", "xEast", ",", "yNorth", ",", "zUp", ",", "deg", "=", "deg", ")" ]
gives azimuth, elevation and slant range from an Observer to a Point with ECEF coordinates. ECEF input location is with units of meters Parameters ---------- x : float or numpy.ndarray of float ECEF x coordinate (meters) y : float or numpy.ndarray of float ECEF y coordinate (meters) z : float or numpy.ndarray of float ECEF z coordinate (meters) lat0 : float Observer geodetic latitude lon0 : float Observer geodetic longitude h0 : float observer altitude above geodetic ellipsoid (meters) ell : Ellipsoid, optional reference ellipsoid deg : bool, optional degrees input/output (False: radians in/out) Returns ------- az : float or numpy.ndarray of float azimuth to target el : float or numpy.ndarray of float elevation to target srange : float or numpy.ndarray of float slant range [meters]
[ "gives", "azimuth", "elevation", "and", "slant", "range", "from", "an", "Observer", "to", "a", "Point", "with", "ECEF", "coordinates", "." ]
c9cf676594611cdb52ff7e0eca6388c80ed4f63f
https://github.com/scivision/pymap3d/blob/c9cf676594611cdb52ff7e0eca6388c80ed4f63f/pymap3d/aer.py#L10-L49
4,149
scivision/pymap3d
pymap3d/aer.py
geodetic2aer
def geodetic2aer(lat: float, lon: float, h: float, lat0: float, lon0: float, h0: float, ell=None, deg: bool = True) -> Tuple[float, float, float]: """ gives azimuth, elevation and slant range from an Observer to a Point with geodetic coordinates. Parameters ---------- lat : float or numpy.ndarray of float target geodetic latitude lon : float or numpy.ndarray of float target geodetic longitude h : float or numpy.ndarray of float target altitude above geodetic ellipsoid (meters) lat0 : float Observer geodetic latitude lon0 : float Observer geodetic longitude h0 : float observer altitude above geodetic ellipsoid (meters) ell : Ellipsoid, optional reference ellipsoid deg : bool, optional degrees input/output (False: radians in/out) Returns ------- az : float or numpy.ndarray of float azimuth el : float or numpy.ndarray of float elevation srange : float or numpy.ndarray of float slant range [meters] """ e, n, u = geodetic2enu(lat, lon, h, lat0, lon0, h0, ell, deg=deg) return enu2aer(e, n, u, deg=deg)
python
def geodetic2aer(lat: float, lon: float, h: float, lat0: float, lon0: float, h0: float, ell=None, deg: bool = True) -> Tuple[float, float, float]: """ gives azimuth, elevation and slant range from an Observer to a Point with geodetic coordinates. Parameters ---------- lat : float or numpy.ndarray of float target geodetic latitude lon : float or numpy.ndarray of float target geodetic longitude h : float or numpy.ndarray of float target altitude above geodetic ellipsoid (meters) lat0 : float Observer geodetic latitude lon0 : float Observer geodetic longitude h0 : float observer altitude above geodetic ellipsoid (meters) ell : Ellipsoid, optional reference ellipsoid deg : bool, optional degrees input/output (False: radians in/out) Returns ------- az : float or numpy.ndarray of float azimuth el : float or numpy.ndarray of float elevation srange : float or numpy.ndarray of float slant range [meters] """ e, n, u = geodetic2enu(lat, lon, h, lat0, lon0, h0, ell, deg=deg) return enu2aer(e, n, u, deg=deg)
[ "def", "geodetic2aer", "(", "lat", ":", "float", ",", "lon", ":", "float", ",", "h", ":", "float", ",", "lat0", ":", "float", ",", "lon0", ":", "float", ",", "h0", ":", "float", ",", "ell", "=", "None", ",", "deg", ":", "bool", "=", "True", ")", "->", "Tuple", "[", "float", ",", "float", ",", "float", "]", ":", "e", ",", "n", ",", "u", "=", "geodetic2enu", "(", "lat", ",", "lon", ",", "h", ",", "lat0", ",", "lon0", ",", "h0", ",", "ell", ",", "deg", "=", "deg", ")", "return", "enu2aer", "(", "e", ",", "n", ",", "u", ",", "deg", "=", "deg", ")" ]
gives azimuth, elevation and slant range from an Observer to a Point with geodetic coordinates. Parameters ---------- lat : float or numpy.ndarray of float target geodetic latitude lon : float or numpy.ndarray of float target geodetic longitude h : float or numpy.ndarray of float target altitude above geodetic ellipsoid (meters) lat0 : float Observer geodetic latitude lon0 : float Observer geodetic longitude h0 : float observer altitude above geodetic ellipsoid (meters) ell : Ellipsoid, optional reference ellipsoid deg : bool, optional degrees input/output (False: radians in/out) Returns ------- az : float or numpy.ndarray of float azimuth el : float or numpy.ndarray of float elevation srange : float or numpy.ndarray of float slant range [meters]
[ "gives", "azimuth", "elevation", "and", "slant", "range", "from", "an", "Observer", "to", "a", "Point", "with", "geodetic", "coordinates", "." ]
c9cf676594611cdb52ff7e0eca6388c80ed4f63f
https://github.com/scivision/pymap3d/blob/c9cf676594611cdb52ff7e0eca6388c80ed4f63f/pymap3d/aer.py#L52-L90
4,150
scivision/pymap3d
pymap3d/aer.py
aer2geodetic
def aer2geodetic(az: float, el: float, srange: float, lat0: float, lon0: float, h0: float, ell=None, deg: bool = True) -> Tuple[float, float, float]: """ gives geodetic coordinates of a point with az, el, range from an observer at lat0, lon0, h0 Parameters ---------- az : float or numpy.ndarray of float azimuth to target el : float or numpy.ndarray of float elevation to target srange : float or numpy.ndarray of float slant range [meters] lat0 : float Observer geodetic latitude lon0 : float Observer geodetic longitude h0 : float observer altitude above geodetic ellipsoid (meters) ell : Ellipsoid, optional reference ellipsoid deg : bool, optional degrees input/output (False: radians in/out) Returns ------- In reference ellipsoid system: lat : float or numpy.ndarray of float geodetic latitude lon : float or numpy.ndarray of float geodetic longitude alt : float or numpy.ndarray of float altitude above ellipsoid (meters) """ x, y, z = aer2ecef(az, el, srange, lat0, lon0, h0, ell=ell, deg=deg) return ecef2geodetic(x, y, z, ell=ell, deg=deg)
python
def aer2geodetic(az: float, el: float, srange: float, lat0: float, lon0: float, h0: float, ell=None, deg: bool = True) -> Tuple[float, float, float]: """ gives geodetic coordinates of a point with az, el, range from an observer at lat0, lon0, h0 Parameters ---------- az : float or numpy.ndarray of float azimuth to target el : float or numpy.ndarray of float elevation to target srange : float or numpy.ndarray of float slant range [meters] lat0 : float Observer geodetic latitude lon0 : float Observer geodetic longitude h0 : float observer altitude above geodetic ellipsoid (meters) ell : Ellipsoid, optional reference ellipsoid deg : bool, optional degrees input/output (False: radians in/out) Returns ------- In reference ellipsoid system: lat : float or numpy.ndarray of float geodetic latitude lon : float or numpy.ndarray of float geodetic longitude alt : float or numpy.ndarray of float altitude above ellipsoid (meters) """ x, y, z = aer2ecef(az, el, srange, lat0, lon0, h0, ell=ell, deg=deg) return ecef2geodetic(x, y, z, ell=ell, deg=deg)
[ "def", "aer2geodetic", "(", "az", ":", "float", ",", "el", ":", "float", ",", "srange", ":", "float", ",", "lat0", ":", "float", ",", "lon0", ":", "float", ",", "h0", ":", "float", ",", "ell", "=", "None", ",", "deg", ":", "bool", "=", "True", ")", "->", "Tuple", "[", "float", ",", "float", ",", "float", "]", ":", "x", ",", "y", ",", "z", "=", "aer2ecef", "(", "az", ",", "el", ",", "srange", ",", "lat0", ",", "lon0", ",", "h0", ",", "ell", "=", "ell", ",", "deg", "=", "deg", ")", "return", "ecef2geodetic", "(", "x", ",", "y", ",", "z", ",", "ell", "=", "ell", ",", "deg", "=", "deg", ")" ]
gives geodetic coordinates of a point with az, el, range from an observer at lat0, lon0, h0 Parameters ---------- az : float or numpy.ndarray of float azimuth to target el : float or numpy.ndarray of float elevation to target srange : float or numpy.ndarray of float slant range [meters] lat0 : float Observer geodetic latitude lon0 : float Observer geodetic longitude h0 : float observer altitude above geodetic ellipsoid (meters) ell : Ellipsoid, optional reference ellipsoid deg : bool, optional degrees input/output (False: radians in/out) Returns ------- In reference ellipsoid system: lat : float or numpy.ndarray of float geodetic latitude lon : float or numpy.ndarray of float geodetic longitude alt : float or numpy.ndarray of float altitude above ellipsoid (meters)
[ "gives", "geodetic", "coordinates", "of", "a", "point", "with", "az", "el", "range", "from", "an", "observer", "at", "lat0", "lon0", "h0" ]
c9cf676594611cdb52ff7e0eca6388c80ed4f63f
https://github.com/scivision/pymap3d/blob/c9cf676594611cdb52ff7e0eca6388c80ed4f63f/pymap3d/aer.py#L93-L134
4,151
scivision/pymap3d
pymap3d/aer.py
eci2aer
def eci2aer(eci: Tuple[float, float, float], lat0: float, lon0: float, h0: float, t: datetime, useastropy: bool = True) -> Tuple[float, float, float]: """ takes ECI coordinates of point and gives az, el, slant range from Observer Parameters ---------- eci : tuple [meters] Nx3 target ECI location (x,y,z) lat0 : float Observer geodetic latitude lon0 : float Observer geodetic longitude h0 : float observer altitude above geodetic ellipsoid (meters) t : datetime.datetime Observation time Returns ------- az : float azimuth to target el : float elevation to target srange : float slant range [meters] """ ecef = np.atleast_2d(eci2ecef(eci, t, useastropy)) return ecef2aer(ecef[:, 0], ecef[:, 1], ecef[:, 2], lat0, lon0, h0)
python
def eci2aer(eci: Tuple[float, float, float], lat0: float, lon0: float, h0: float, t: datetime, useastropy: bool = True) -> Tuple[float, float, float]: """ takes ECI coordinates of point and gives az, el, slant range from Observer Parameters ---------- eci : tuple [meters] Nx3 target ECI location (x,y,z) lat0 : float Observer geodetic latitude lon0 : float Observer geodetic longitude h0 : float observer altitude above geodetic ellipsoid (meters) t : datetime.datetime Observation time Returns ------- az : float azimuth to target el : float elevation to target srange : float slant range [meters] """ ecef = np.atleast_2d(eci2ecef(eci, t, useastropy)) return ecef2aer(ecef[:, 0], ecef[:, 1], ecef[:, 2], lat0, lon0, h0)
[ "def", "eci2aer", "(", "eci", ":", "Tuple", "[", "float", ",", "float", ",", "float", "]", ",", "lat0", ":", "float", ",", "lon0", ":", "float", ",", "h0", ":", "float", ",", "t", ":", "datetime", ",", "useastropy", ":", "bool", "=", "True", ")", "->", "Tuple", "[", "float", ",", "float", ",", "float", "]", ":", "ecef", "=", "np", ".", "atleast_2d", "(", "eci2ecef", "(", "eci", ",", "t", ",", "useastropy", ")", ")", "return", "ecef2aer", "(", "ecef", "[", ":", ",", "0", "]", ",", "ecef", "[", ":", ",", "1", "]", ",", "ecef", "[", ":", ",", "2", "]", ",", "lat0", ",", "lon0", ",", "h0", ")" ]
takes ECI coordinates of point and gives az, el, slant range from Observer Parameters ---------- eci : tuple [meters] Nx3 target ECI location (x,y,z) lat0 : float Observer geodetic latitude lon0 : float Observer geodetic longitude h0 : float observer altitude above geodetic ellipsoid (meters) t : datetime.datetime Observation time Returns ------- az : float azimuth to target el : float elevation to target srange : float slant range [meters]
[ "takes", "ECI", "coordinates", "of", "point", "and", "gives", "az", "el", "slant", "range", "from", "Observer" ]
c9cf676594611cdb52ff7e0eca6388c80ed4f63f
https://github.com/scivision/pymap3d/blob/c9cf676594611cdb52ff7e0eca6388c80ed4f63f/pymap3d/aer.py#L137-L170
4,152
scivision/pymap3d
pymap3d/aer.py
aer2eci
def aer2eci(az: float, el: float, srange: float, lat0: float, lon0: float, h0: float, t: datetime, ell=None, deg: bool = True, useastropy: bool = True) -> np.ndarray: """ gives ECI of a point from an observer at az, el, slant range Parameters ---------- az : float or numpy.ndarray of float azimuth to target el : float or numpy.ndarray of float elevation to target srange : float or numpy.ndarray of float slant range [meters] lat0 : float Observer geodetic latitude lon0 : float Observer geodetic longitude h0 : float observer altitude above geodetic ellipsoid (meters) ell : Ellipsoid, optional reference ellipsoid deg : bool, optional degrees input/output (False: radians in/out) t : datetime.datetime Observation time Returns ------- Earth Centered Inertial x,y,z x : float or numpy.ndarray of float ECEF x coordinate (meters) y : float or numpy.ndarray of float ECEF y coordinate (meters) z : float or numpy.ndarray of float ECEF z coordinate (meters) """ x, y, z = aer2ecef(az, el, srange, lat0, lon0, h0, ell, deg) return ecef2eci(np.column_stack((x, y, z)), t, useastropy)
python
def aer2eci(az: float, el: float, srange: float, lat0: float, lon0: float, h0: float, t: datetime, ell=None, deg: bool = True, useastropy: bool = True) -> np.ndarray: """ gives ECI of a point from an observer at az, el, slant range Parameters ---------- az : float or numpy.ndarray of float azimuth to target el : float or numpy.ndarray of float elevation to target srange : float or numpy.ndarray of float slant range [meters] lat0 : float Observer geodetic latitude lon0 : float Observer geodetic longitude h0 : float observer altitude above geodetic ellipsoid (meters) ell : Ellipsoid, optional reference ellipsoid deg : bool, optional degrees input/output (False: radians in/out) t : datetime.datetime Observation time Returns ------- Earth Centered Inertial x,y,z x : float or numpy.ndarray of float ECEF x coordinate (meters) y : float or numpy.ndarray of float ECEF y coordinate (meters) z : float or numpy.ndarray of float ECEF z coordinate (meters) """ x, y, z = aer2ecef(az, el, srange, lat0, lon0, h0, ell, deg) return ecef2eci(np.column_stack((x, y, z)), t, useastropy)
[ "def", "aer2eci", "(", "az", ":", "float", ",", "el", ":", "float", ",", "srange", ":", "float", ",", "lat0", ":", "float", ",", "lon0", ":", "float", ",", "h0", ":", "float", ",", "t", ":", "datetime", ",", "ell", "=", "None", ",", "deg", ":", "bool", "=", "True", ",", "useastropy", ":", "bool", "=", "True", ")", "->", "np", ".", "ndarray", ":", "x", ",", "y", ",", "z", "=", "aer2ecef", "(", "az", ",", "el", ",", "srange", ",", "lat0", ",", "lon0", ",", "h0", ",", "ell", ",", "deg", ")", "return", "ecef2eci", "(", "np", ".", "column_stack", "(", "(", "x", ",", "y", ",", "z", ")", ")", ",", "t", ",", "useastropy", ")" ]
gives ECI of a point from an observer at az, el, slant range Parameters ---------- az : float or numpy.ndarray of float azimuth to target el : float or numpy.ndarray of float elevation to target srange : float or numpy.ndarray of float slant range [meters] lat0 : float Observer geodetic latitude lon0 : float Observer geodetic longitude h0 : float observer altitude above geodetic ellipsoid (meters) ell : Ellipsoid, optional reference ellipsoid deg : bool, optional degrees input/output (False: radians in/out) t : datetime.datetime Observation time Returns ------- Earth Centered Inertial x,y,z x : float or numpy.ndarray of float ECEF x coordinate (meters) y : float or numpy.ndarray of float ECEF y coordinate (meters) z : float or numpy.ndarray of float ECEF z coordinate (meters)
[ "gives", "ECI", "of", "a", "point", "from", "an", "observer", "at", "az", "el", "slant", "range" ]
c9cf676594611cdb52ff7e0eca6388c80ed4f63f
https://github.com/scivision/pymap3d/blob/c9cf676594611cdb52ff7e0eca6388c80ed4f63f/pymap3d/aer.py#L173-L215
4,153
scivision/pymap3d
pymap3d/aer.py
aer2ecef
def aer2ecef(az: float, el: float, srange: float, lat0: float, lon0: float, alt0: float, ell=None, deg: bool = True) -> Tuple[float, float, float]: """ converts target azimuth, elevation, range from observer at lat0,lon0,alt0 to ECEF coordinates. Parameters ---------- az : float or numpy.ndarray of float azimuth to target el : float or numpy.ndarray of float elevation to target srange : float or numpy.ndarray of float slant range [meters] lat0 : float Observer geodetic latitude lon0 : float Observer geodetic longitude h0 : float observer altitude above geodetic ellipsoid (meters) ell : Ellipsoid, optional reference ellipsoid deg : bool, optional degrees input/output (False: radians in/out) Returns ------- ECEF (Earth centered, Earth fixed) x,y,z x : float or numpy.ndarray of float ECEF x coordinate (meters) y : float or numpy.ndarray of float ECEF y coordinate (meters) z : float or numpy.ndarray of float ECEF z coordinate (meters) Notes ------ if srange==NaN, z=NaN """ # Origin of the local system in geocentric coordinates. x0, y0, z0 = geodetic2ecef(lat0, lon0, alt0, ell, deg=deg) # Convert Local Spherical AER to ENU e1, n1, u1 = aer2enu(az, el, srange, deg=deg) # Rotating ENU to ECEF dx, dy, dz = enu2uvw(e1, n1, u1, lat0, lon0, deg=deg) # Origin + offset from origin equals position in ECEF return x0 + dx, y0 + dy, z0 + dz
python
def aer2ecef(az: float, el: float, srange: float, lat0: float, lon0: float, alt0: float, ell=None, deg: bool = True) -> Tuple[float, float, float]: """ converts target azimuth, elevation, range from observer at lat0,lon0,alt0 to ECEF coordinates. Parameters ---------- az : float or numpy.ndarray of float azimuth to target el : float or numpy.ndarray of float elevation to target srange : float or numpy.ndarray of float slant range [meters] lat0 : float Observer geodetic latitude lon0 : float Observer geodetic longitude h0 : float observer altitude above geodetic ellipsoid (meters) ell : Ellipsoid, optional reference ellipsoid deg : bool, optional degrees input/output (False: radians in/out) Returns ------- ECEF (Earth centered, Earth fixed) x,y,z x : float or numpy.ndarray of float ECEF x coordinate (meters) y : float or numpy.ndarray of float ECEF y coordinate (meters) z : float or numpy.ndarray of float ECEF z coordinate (meters) Notes ------ if srange==NaN, z=NaN """ # Origin of the local system in geocentric coordinates. x0, y0, z0 = geodetic2ecef(lat0, lon0, alt0, ell, deg=deg) # Convert Local Spherical AER to ENU e1, n1, u1 = aer2enu(az, el, srange, deg=deg) # Rotating ENU to ECEF dx, dy, dz = enu2uvw(e1, n1, u1, lat0, lon0, deg=deg) # Origin + offset from origin equals position in ECEF return x0 + dx, y0 + dy, z0 + dz
[ "def", "aer2ecef", "(", "az", ":", "float", ",", "el", ":", "float", ",", "srange", ":", "float", ",", "lat0", ":", "float", ",", "lon0", ":", "float", ",", "alt0", ":", "float", ",", "ell", "=", "None", ",", "deg", ":", "bool", "=", "True", ")", "->", "Tuple", "[", "float", ",", "float", ",", "float", "]", ":", "# Origin of the local system in geocentric coordinates.", "x0", ",", "y0", ",", "z0", "=", "geodetic2ecef", "(", "lat0", ",", "lon0", ",", "alt0", ",", "ell", ",", "deg", "=", "deg", ")", "# Convert Local Spherical AER to ENU", "e1", ",", "n1", ",", "u1", "=", "aer2enu", "(", "az", ",", "el", ",", "srange", ",", "deg", "=", "deg", ")", "# Rotating ENU to ECEF", "dx", ",", "dy", ",", "dz", "=", "enu2uvw", "(", "e1", ",", "n1", ",", "u1", ",", "lat0", ",", "lon0", ",", "deg", "=", "deg", ")", "# Origin + offset from origin equals position in ECEF", "return", "x0", "+", "dx", ",", "y0", "+", "dy", ",", "z0", "+", "dz" ]
converts target azimuth, elevation, range from observer at lat0,lon0,alt0 to ECEF coordinates. Parameters ---------- az : float or numpy.ndarray of float azimuth to target el : float or numpy.ndarray of float elevation to target srange : float or numpy.ndarray of float slant range [meters] lat0 : float Observer geodetic latitude lon0 : float Observer geodetic longitude h0 : float observer altitude above geodetic ellipsoid (meters) ell : Ellipsoid, optional reference ellipsoid deg : bool, optional degrees input/output (False: radians in/out) Returns ------- ECEF (Earth centered, Earth fixed) x,y,z x : float or numpy.ndarray of float ECEF x coordinate (meters) y : float or numpy.ndarray of float ECEF y coordinate (meters) z : float or numpy.ndarray of float ECEF z coordinate (meters) Notes ------ if srange==NaN, z=NaN
[ "converts", "target", "azimuth", "elevation", "range", "from", "observer", "at", "lat0", "lon0", "alt0", "to", "ECEF", "coordinates", "." ]
c9cf676594611cdb52ff7e0eca6388c80ed4f63f
https://github.com/scivision/pymap3d/blob/c9cf676594611cdb52ff7e0eca6388c80ed4f63f/pymap3d/aer.py#L218-L267
4,154
scivision/pymap3d
pymap3d/lox.py
isometric
def isometric(lat: float, ell: Ellipsoid = None, deg: bool = True): """ computes isometric latitude of a point on an ellipsoid Parameters ---------- lat : float or numpy.ndarray of float geodetic latitude ell : Ellipsoid, optional reference ellipsoid (default WGS84) deg : bool, optional degrees input/output (False: radians in/out) Returns ------- isolat : float or numpy.ndarray of float isometric latiude Notes ----- Isometric latitude is an auxiliary latitude proportional to the spacing of parallels of latitude on an ellipsoidal mercator projection. Based on Deakin, R.E., 2010, 'The Loxodrome on an Ellipsoid', Lecture Notes, School of Mathematical and Geospatial Sciences, RMIT University, January 2010 """ if ell is None: ell = Ellipsoid() f = ell.f # flattening of ellipsoid if deg is True: lat = np.deg2rad(lat) e2 = f * (2 - f) # eccentricity-squared e = np.sqrt(e2) # eccentricity of ellipsoid x = e * np.sin(lat) y = (1 - x) / (1 + x) z = np.pi / 4 + lat / 2 # calculate the isometric latitude isolat = np.log(np.tan(z) * (y**(e / 2))) if deg is True: isolat = np.degrees(isolat) return isolat
python
def isometric(lat: float, ell: Ellipsoid = None, deg: bool = True): """ computes isometric latitude of a point on an ellipsoid Parameters ---------- lat : float or numpy.ndarray of float geodetic latitude ell : Ellipsoid, optional reference ellipsoid (default WGS84) deg : bool, optional degrees input/output (False: radians in/out) Returns ------- isolat : float or numpy.ndarray of float isometric latiude Notes ----- Isometric latitude is an auxiliary latitude proportional to the spacing of parallels of latitude on an ellipsoidal mercator projection. Based on Deakin, R.E., 2010, 'The Loxodrome on an Ellipsoid', Lecture Notes, School of Mathematical and Geospatial Sciences, RMIT University, January 2010 """ if ell is None: ell = Ellipsoid() f = ell.f # flattening of ellipsoid if deg is True: lat = np.deg2rad(lat) e2 = f * (2 - f) # eccentricity-squared e = np.sqrt(e2) # eccentricity of ellipsoid x = e * np.sin(lat) y = (1 - x) / (1 + x) z = np.pi / 4 + lat / 2 # calculate the isometric latitude isolat = np.log(np.tan(z) * (y**(e / 2))) if deg is True: isolat = np.degrees(isolat) return isolat
[ "def", "isometric", "(", "lat", ":", "float", ",", "ell", ":", "Ellipsoid", "=", "None", ",", "deg", ":", "bool", "=", "True", ")", ":", "if", "ell", "is", "None", ":", "ell", "=", "Ellipsoid", "(", ")", "f", "=", "ell", ".", "f", "# flattening of ellipsoid", "if", "deg", "is", "True", ":", "lat", "=", "np", ".", "deg2rad", "(", "lat", ")", "e2", "=", "f", "*", "(", "2", "-", "f", ")", "# eccentricity-squared", "e", "=", "np", ".", "sqrt", "(", "e2", ")", "# eccentricity of ellipsoid", "x", "=", "e", "*", "np", ".", "sin", "(", "lat", ")", "y", "=", "(", "1", "-", "x", ")", "/", "(", "1", "+", "x", ")", "z", "=", "np", ".", "pi", "/", "4", "+", "lat", "/", "2", "# calculate the isometric latitude", "isolat", "=", "np", ".", "log", "(", "np", ".", "tan", "(", "z", ")", "*", "(", "y", "**", "(", "e", "/", "2", ")", ")", ")", "if", "deg", "is", "True", ":", "isolat", "=", "np", ".", "degrees", "(", "isolat", ")", "return", "isolat" ]
computes isometric latitude of a point on an ellipsoid Parameters ---------- lat : float or numpy.ndarray of float geodetic latitude ell : Ellipsoid, optional reference ellipsoid (default WGS84) deg : bool, optional degrees input/output (False: radians in/out) Returns ------- isolat : float or numpy.ndarray of float isometric latiude Notes ----- Isometric latitude is an auxiliary latitude proportional to the spacing of parallels of latitude on an ellipsoidal mercator projection. Based on Deakin, R.E., 2010, 'The Loxodrome on an Ellipsoid', Lecture Notes, School of Mathematical and Geospatial Sciences, RMIT University, January 2010
[ "computes", "isometric", "latitude", "of", "a", "point", "on", "an", "ellipsoid" ]
c9cf676594611cdb52ff7e0eca6388c80ed4f63f
https://github.com/scivision/pymap3d/blob/c9cf676594611cdb52ff7e0eca6388c80ed4f63f/pymap3d/lox.py#L6-L58
4,155
scivision/pymap3d
pymap3d/lox.py
loxodrome_inverse
def loxodrome_inverse(lat1: float, lon1: float, lat2: float, lon2: float, ell: Ellipsoid = None, deg: bool = True): """ computes the arc length and azimuth of the loxodrome between two points on the surface of the reference ellipsoid Parameters ---------- lat1 : float or numpy.ndarray of float geodetic latitude of first point lon1 : float or numpy.ndarray of float geodetic longitude of first point lat2 : float or numpy.ndarray of float geodetic latitude of second point lon2 : float or numpy.ndarray of float geodetic longitude of second point ell : Ellipsoid, optional reference ellipsoid (default WGS84) deg : bool, optional degrees input/output (False: radians in/out) Results ------- lox_s : float or numpy.ndarray of float distance along loxodrome az12 : float or numpy.ndarray of float azimuth of loxodrome (degrees/radians) Based on Deakin, R.E., 2010, 'The Loxodrome on an Ellipsoid', Lecture Notes, School of Mathematical and Geospatial Sciences, RMIT University, January 2010 [1] Bowring, B.R., 1985, 'The geometry of the loxodrome on the ellipsoid', The Canadian Surveyor, Vol. 39, No. 3, Autumn 1985, pp.223-230. [2] Snyder, J.P., 1987, Map Projections-A Working Manual. U.S. Geological Survey Professional Paper 1395. Washington, DC: U.S. Government Printing Office, pp.15-16 and pp. 44-45. [3] Thomas, P.D., 1952, Conformal Projections in Geodesy and Cartography, Special Publication No. 251, Coast and Geodetic Survey, U.S. Department of Commerce, Washington, DC: U.S. Government Printing Office, p. 66. """ # set ellipsoid parameters if ell is None: ell = Ellipsoid() if deg is True: lat1, lon1, lat2, lon2 = np.radians([lat1, lon1, lat2, lon2]) # compute isometric latitude of P1 and P2 isolat1 = isometric(lat1, deg=False, ell=ell) isolat2 = isometric(lat2, deg=False, ell=ell) # compute changes in isometric latitude and longitude between points disolat = isolat2 - isolat1 dlon = lon2 - lon1 # compute azimuth az12 = np.arctan2(dlon, disolat) # compute distance along loxodromic curve m1 = meridian_dist(lat1, deg=False, ell=ell) m2 = meridian_dist(lat2, deg=False, ell=ell) dm = m2 - m1 lox_s = dm / np.cos(az12) if deg is True: az12 = np.degrees(az12) % 360. return lox_s, az12
python
def loxodrome_inverse(lat1: float, lon1: float, lat2: float, lon2: float, ell: Ellipsoid = None, deg: bool = True): """ computes the arc length and azimuth of the loxodrome between two points on the surface of the reference ellipsoid Parameters ---------- lat1 : float or numpy.ndarray of float geodetic latitude of first point lon1 : float or numpy.ndarray of float geodetic longitude of first point lat2 : float or numpy.ndarray of float geodetic latitude of second point lon2 : float or numpy.ndarray of float geodetic longitude of second point ell : Ellipsoid, optional reference ellipsoid (default WGS84) deg : bool, optional degrees input/output (False: radians in/out) Results ------- lox_s : float or numpy.ndarray of float distance along loxodrome az12 : float or numpy.ndarray of float azimuth of loxodrome (degrees/radians) Based on Deakin, R.E., 2010, 'The Loxodrome on an Ellipsoid', Lecture Notes, School of Mathematical and Geospatial Sciences, RMIT University, January 2010 [1] Bowring, B.R., 1985, 'The geometry of the loxodrome on the ellipsoid', The Canadian Surveyor, Vol. 39, No. 3, Autumn 1985, pp.223-230. [2] Snyder, J.P., 1987, Map Projections-A Working Manual. U.S. Geological Survey Professional Paper 1395. Washington, DC: U.S. Government Printing Office, pp.15-16 and pp. 44-45. [3] Thomas, P.D., 1952, Conformal Projections in Geodesy and Cartography, Special Publication No. 251, Coast and Geodetic Survey, U.S. Department of Commerce, Washington, DC: U.S. Government Printing Office, p. 66. """ # set ellipsoid parameters if ell is None: ell = Ellipsoid() if deg is True: lat1, lon1, lat2, lon2 = np.radians([lat1, lon1, lat2, lon2]) # compute isometric latitude of P1 and P2 isolat1 = isometric(lat1, deg=False, ell=ell) isolat2 = isometric(lat2, deg=False, ell=ell) # compute changes in isometric latitude and longitude between points disolat = isolat2 - isolat1 dlon = lon2 - lon1 # compute azimuth az12 = np.arctan2(dlon, disolat) # compute distance along loxodromic curve m1 = meridian_dist(lat1, deg=False, ell=ell) m2 = meridian_dist(lat2, deg=False, ell=ell) dm = m2 - m1 lox_s = dm / np.cos(az12) if deg is True: az12 = np.degrees(az12) % 360. return lox_s, az12
[ "def", "loxodrome_inverse", "(", "lat1", ":", "float", ",", "lon1", ":", "float", ",", "lat2", ":", "float", ",", "lon2", ":", "float", ",", "ell", ":", "Ellipsoid", "=", "None", ",", "deg", ":", "bool", "=", "True", ")", ":", "# set ellipsoid parameters", "if", "ell", "is", "None", ":", "ell", "=", "Ellipsoid", "(", ")", "if", "deg", "is", "True", ":", "lat1", ",", "lon1", ",", "lat2", ",", "lon2", "=", "np", ".", "radians", "(", "[", "lat1", ",", "lon1", ",", "lat2", ",", "lon2", "]", ")", "# compute isometric latitude of P1 and P2", "isolat1", "=", "isometric", "(", "lat1", ",", "deg", "=", "False", ",", "ell", "=", "ell", ")", "isolat2", "=", "isometric", "(", "lat2", ",", "deg", "=", "False", ",", "ell", "=", "ell", ")", "# compute changes in isometric latitude and longitude between points", "disolat", "=", "isolat2", "-", "isolat1", "dlon", "=", "lon2", "-", "lon1", "# compute azimuth", "az12", "=", "np", ".", "arctan2", "(", "dlon", ",", "disolat", ")", "# compute distance along loxodromic curve", "m1", "=", "meridian_dist", "(", "lat1", ",", "deg", "=", "False", ",", "ell", "=", "ell", ")", "m2", "=", "meridian_dist", "(", "lat2", ",", "deg", "=", "False", ",", "ell", "=", "ell", ")", "dm", "=", "m2", "-", "m1", "lox_s", "=", "dm", "/", "np", ".", "cos", "(", "az12", ")", "if", "deg", "is", "True", ":", "az12", "=", "np", ".", "degrees", "(", "az12", ")", "%", "360.", "return", "lox_s", ",", "az12" ]
computes the arc length and azimuth of the loxodrome between two points on the surface of the reference ellipsoid Parameters ---------- lat1 : float or numpy.ndarray of float geodetic latitude of first point lon1 : float or numpy.ndarray of float geodetic longitude of first point lat2 : float or numpy.ndarray of float geodetic latitude of second point lon2 : float or numpy.ndarray of float geodetic longitude of second point ell : Ellipsoid, optional reference ellipsoid (default WGS84) deg : bool, optional degrees input/output (False: radians in/out) Results ------- lox_s : float or numpy.ndarray of float distance along loxodrome az12 : float or numpy.ndarray of float azimuth of loxodrome (degrees/radians) Based on Deakin, R.E., 2010, 'The Loxodrome on an Ellipsoid', Lecture Notes, School of Mathematical and Geospatial Sciences, RMIT University, January 2010 [1] Bowring, B.R., 1985, 'The geometry of the loxodrome on the ellipsoid', The Canadian Surveyor, Vol. 39, No. 3, Autumn 1985, pp.223-230. [2] Snyder, J.P., 1987, Map Projections-A Working Manual. U.S. Geological Survey Professional Paper 1395. Washington, DC: U.S. Government Printing Office, pp.15-16 and pp. 44-45. [3] Thomas, P.D., 1952, Conformal Projections in Geodesy and Cartography, Special Publication No. 251, Coast and Geodetic Survey, U.S. Department of Commerce, Washington, DC: U.S. Government Printing Office, p. 66.
[ "computes", "the", "arc", "length", "and", "azimuth", "of", "the", "loxodrome", "between", "two", "points", "on", "the", "surface", "of", "the", "reference", "ellipsoid" ]
c9cf676594611cdb52ff7e0eca6388c80ed4f63f
https://github.com/scivision/pymap3d/blob/c9cf676594611cdb52ff7e0eca6388c80ed4f63f/pymap3d/lox.py#L130-L202
4,156
scivision/pymap3d
pymap3d/eci.py
eci2ecef
def eci2ecef(eci: np.ndarray, time: datetime, useastropy: bool = True) -> np.ndarray: """ Observer => Point ECI => ECEF Parameters ---------- eci : tuple of float Nx3 target ECI location (x,y,z) [meters] time : datetime.datetime time of obsevation (UTC) useastropy : bool, optional use AstroPy for conversion Results ------- x : float target x ECEF coordinate y : float target y ECEF coordinate z : float target z ECEF coordinate """ useastropy = useastropy and Time if useastropy: gst = Time(time).sidereal_time('apparent', 'greenwich').radian else: gst = datetime2sidereal(time, 0.) gst = np.atleast_1d(gst) assert gst.ndim == 1 and isinstance(gst[0], float) # must be in radians! eci = np.atleast_2d(eci) assert eci.shape[0] == gst.size, 'length of time does not match number of ECI positions' N, trip = eci.shape if eci.ndim > 2 or trip != 3: raise ValueError('eci triplets must be shape (N,3)') ecef = np.empty_like(eci) for i in range(N): ecef[i, :] = _rottrip(gst[i]) @ eci[i, :] return ecef.squeeze()
python
def eci2ecef(eci: np.ndarray, time: datetime, useastropy: bool = True) -> np.ndarray: """ Observer => Point ECI => ECEF Parameters ---------- eci : tuple of float Nx3 target ECI location (x,y,z) [meters] time : datetime.datetime time of obsevation (UTC) useastropy : bool, optional use AstroPy for conversion Results ------- x : float target x ECEF coordinate y : float target y ECEF coordinate z : float target z ECEF coordinate """ useastropy = useastropy and Time if useastropy: gst = Time(time).sidereal_time('apparent', 'greenwich').radian else: gst = datetime2sidereal(time, 0.) gst = np.atleast_1d(gst) assert gst.ndim == 1 and isinstance(gst[0], float) # must be in radians! eci = np.atleast_2d(eci) assert eci.shape[0] == gst.size, 'length of time does not match number of ECI positions' N, trip = eci.shape if eci.ndim > 2 or trip != 3: raise ValueError('eci triplets must be shape (N,3)') ecef = np.empty_like(eci) for i in range(N): ecef[i, :] = _rottrip(gst[i]) @ eci[i, :] return ecef.squeeze()
[ "def", "eci2ecef", "(", "eci", ":", "np", ".", "ndarray", ",", "time", ":", "datetime", ",", "useastropy", ":", "bool", "=", "True", ")", "->", "np", ".", "ndarray", ":", "useastropy", "=", "useastropy", "and", "Time", "if", "useastropy", ":", "gst", "=", "Time", "(", "time", ")", ".", "sidereal_time", "(", "'apparent'", ",", "'greenwich'", ")", ".", "radian", "else", ":", "gst", "=", "datetime2sidereal", "(", "time", ",", "0.", ")", "gst", "=", "np", ".", "atleast_1d", "(", "gst", ")", "assert", "gst", ".", "ndim", "==", "1", "and", "isinstance", "(", "gst", "[", "0", "]", ",", "float", ")", "# must be in radians!", "eci", "=", "np", ".", "atleast_2d", "(", "eci", ")", "assert", "eci", ".", "shape", "[", "0", "]", "==", "gst", ".", "size", ",", "'length of time does not match number of ECI positions'", "N", ",", "trip", "=", "eci", ".", "shape", "if", "eci", ".", "ndim", ">", "2", "or", "trip", "!=", "3", ":", "raise", "ValueError", "(", "'eci triplets must be shape (N,3)'", ")", "ecef", "=", "np", ".", "empty_like", "(", "eci", ")", "for", "i", "in", "range", "(", "N", ")", ":", "ecef", "[", "i", ",", ":", "]", "=", "_rottrip", "(", "gst", "[", "i", "]", ")", "@", "eci", "[", "i", ",", ":", "]", "return", "ecef", ".", "squeeze", "(", ")" ]
Observer => Point ECI => ECEF Parameters ---------- eci : tuple of float Nx3 target ECI location (x,y,z) [meters] time : datetime.datetime time of obsevation (UTC) useastropy : bool, optional use AstroPy for conversion Results ------- x : float target x ECEF coordinate y : float target y ECEF coordinate z : float target z ECEF coordinate
[ "Observer", "=", ">", "Point", "ECI", "=", ">", "ECEF" ]
c9cf676594611cdb52ff7e0eca6388c80ed4f63f
https://github.com/scivision/pymap3d/blob/c9cf676594611cdb52ff7e0eca6388c80ed4f63f/pymap3d/eci.py#L12-L58
4,157
Netflix-Skunkworks/historical
historical/vpc/collector.py
describe_vpc
def describe_vpc(record): """Attempts to describe vpc ids.""" account_id = record['account'] vpc_name = cloudwatch.filter_request_parameters('vpcName', record) vpc_id = cloudwatch.filter_request_parameters('vpcId', record) try: if vpc_id and vpc_name: # pylint: disable=R1705 return describe_vpcs( account_number=account_id, assume_role=HISTORICAL_ROLE, region=CURRENT_REGION, Filters=[ { 'Name': 'vpc-id', 'Values': [vpc_id] } ] ) elif vpc_id: return describe_vpcs( account_number=account_id, assume_role=HISTORICAL_ROLE, region=CURRENT_REGION, VpcIds=[vpc_id] ) else: raise Exception('[X] Describe requires VpcId.') except ClientError as exc: if exc.response['Error']['Code'] == 'InvalidVpc.NotFound': return [] raise exc
python
def describe_vpc(record): """Attempts to describe vpc ids.""" account_id = record['account'] vpc_name = cloudwatch.filter_request_parameters('vpcName', record) vpc_id = cloudwatch.filter_request_parameters('vpcId', record) try: if vpc_id and vpc_name: # pylint: disable=R1705 return describe_vpcs( account_number=account_id, assume_role=HISTORICAL_ROLE, region=CURRENT_REGION, Filters=[ { 'Name': 'vpc-id', 'Values': [vpc_id] } ] ) elif vpc_id: return describe_vpcs( account_number=account_id, assume_role=HISTORICAL_ROLE, region=CURRENT_REGION, VpcIds=[vpc_id] ) else: raise Exception('[X] Describe requires VpcId.') except ClientError as exc: if exc.response['Error']['Code'] == 'InvalidVpc.NotFound': return [] raise exc
[ "def", "describe_vpc", "(", "record", ")", ":", "account_id", "=", "record", "[", "'account'", "]", "vpc_name", "=", "cloudwatch", ".", "filter_request_parameters", "(", "'vpcName'", ",", "record", ")", "vpc_id", "=", "cloudwatch", ".", "filter_request_parameters", "(", "'vpcId'", ",", "record", ")", "try", ":", "if", "vpc_id", "and", "vpc_name", ":", "# pylint: disable=R1705", "return", "describe_vpcs", "(", "account_number", "=", "account_id", ",", "assume_role", "=", "HISTORICAL_ROLE", ",", "region", "=", "CURRENT_REGION", ",", "Filters", "=", "[", "{", "'Name'", ":", "'vpc-id'", ",", "'Values'", ":", "[", "vpc_id", "]", "}", "]", ")", "elif", "vpc_id", ":", "return", "describe_vpcs", "(", "account_number", "=", "account_id", ",", "assume_role", "=", "HISTORICAL_ROLE", ",", "region", "=", "CURRENT_REGION", ",", "VpcIds", "=", "[", "vpc_id", "]", ")", "else", ":", "raise", "Exception", "(", "'[X] Describe requires VpcId.'", ")", "except", "ClientError", "as", "exc", ":", "if", "exc", ".", "response", "[", "'Error'", "]", "[", "'Code'", "]", "==", "'InvalidVpc.NotFound'", ":", "return", "[", "]", "raise", "exc" ]
Attempts to describe vpc ids.
[ "Attempts", "to", "describe", "vpc", "ids", "." ]
c3ebaa8388a3fe67e23a6c9c6b04c3e618497c4a
https://github.com/Netflix-Skunkworks/historical/blob/c3ebaa8388a3fe67e23a6c9c6b04c3e618497c4a/historical/vpc/collector.py#L44-L75
4,158
Netflix-Skunkworks/historical
historical/vpc/collector.py
create_delete_model
def create_delete_model(record): """Create a vpc model from a record.""" data = cloudwatch.get_historical_base_info(record) vpc_id = cloudwatch.filter_request_parameters('vpcId', record) arn = get_arn(vpc_id, cloudwatch.get_region(record), record['account']) LOG.debug(F'[-] Deleting Dynamodb Records. Hash Key: {arn}') # tombstone these records so that the deletion event time can be accurately tracked. data.update({ 'configuration': {} }) items = list(CurrentVPCModel.query(arn, limit=1)) if items: model_dict = items[0].__dict__['attribute_values'].copy() model_dict.update(data) model = CurrentVPCModel(**model_dict) model.save() return model return None
python
def create_delete_model(record): """Create a vpc model from a record.""" data = cloudwatch.get_historical_base_info(record) vpc_id = cloudwatch.filter_request_parameters('vpcId', record) arn = get_arn(vpc_id, cloudwatch.get_region(record), record['account']) LOG.debug(F'[-] Deleting Dynamodb Records. Hash Key: {arn}') # tombstone these records so that the deletion event time can be accurately tracked. data.update({ 'configuration': {} }) items = list(CurrentVPCModel.query(arn, limit=1)) if items: model_dict = items[0].__dict__['attribute_values'].copy() model_dict.update(data) model = CurrentVPCModel(**model_dict) model.save() return model return None
[ "def", "create_delete_model", "(", "record", ")", ":", "data", "=", "cloudwatch", ".", "get_historical_base_info", "(", "record", ")", "vpc_id", "=", "cloudwatch", ".", "filter_request_parameters", "(", "'vpcId'", ",", "record", ")", "arn", "=", "get_arn", "(", "vpc_id", ",", "cloudwatch", ".", "get_region", "(", "record", ")", ",", "record", "[", "'account'", "]", ")", "LOG", ".", "debug", "(", "F'[-] Deleting Dynamodb Records. Hash Key: {arn}'", ")", "# tombstone these records so that the deletion event time can be accurately tracked.", "data", ".", "update", "(", "{", "'configuration'", ":", "{", "}", "}", ")", "items", "=", "list", "(", "CurrentVPCModel", ".", "query", "(", "arn", ",", "limit", "=", "1", ")", ")", "if", "items", ":", "model_dict", "=", "items", "[", "0", "]", ".", "__dict__", "[", "'attribute_values'", "]", ".", "copy", "(", ")", "model_dict", ".", "update", "(", "data", ")", "model", "=", "CurrentVPCModel", "(", "*", "*", "model_dict", ")", "model", ".", "save", "(", ")", "return", "model", "return", "None" ]
Create a vpc model from a record.
[ "Create", "a", "vpc", "model", "from", "a", "record", "." ]
c3ebaa8388a3fe67e23a6c9c6b04c3e618497c4a
https://github.com/Netflix-Skunkworks/historical/blob/c3ebaa8388a3fe67e23a6c9c6b04c3e618497c4a/historical/vpc/collector.py#L78-L102
4,159
Netflix-Skunkworks/historical
historical/vpc/collector.py
handler
def handler(event, context): # pylint: disable=W0613 """ Historical vpc event collector. This collector is responsible for processing Cloudwatch events and polling events. """ records = deserialize_records(event['Records']) # Split records into two groups, update and delete. # We don't want to query for deleted records. update_records, delete_records = group_records_by_type(records, UPDATE_EVENTS) capture_delete_records(delete_records) # filter out error events update_records = [e for e in update_records if not e['detail'].get('errorCode')] # pylint: disable=C0103 # group records by account for more efficient processing LOG.debug(f'[@] Update Records: {records}') capture_update_records(update_records)
python
def handler(event, context): # pylint: disable=W0613 """ Historical vpc event collector. This collector is responsible for processing Cloudwatch events and polling events. """ records = deserialize_records(event['Records']) # Split records into two groups, update and delete. # We don't want to query for deleted records. update_records, delete_records = group_records_by_type(records, UPDATE_EVENTS) capture_delete_records(delete_records) # filter out error events update_records = [e for e in update_records if not e['detail'].get('errorCode')] # pylint: disable=C0103 # group records by account for more efficient processing LOG.debug(f'[@] Update Records: {records}') capture_update_records(update_records)
[ "def", "handler", "(", "event", ",", "context", ")", ":", "# pylint: disable=W0613", "records", "=", "deserialize_records", "(", "event", "[", "'Records'", "]", ")", "# Split records into two groups, update and delete.", "# We don't want to query for deleted records.", "update_records", ",", "delete_records", "=", "group_records_by_type", "(", "records", ",", "UPDATE_EVENTS", ")", "capture_delete_records", "(", "delete_records", ")", "# filter out error events", "update_records", "=", "[", "e", "for", "e", "in", "update_records", "if", "not", "e", "[", "'detail'", "]", ".", "get", "(", "'errorCode'", ")", "]", "# pylint: disable=C0103", "# group records by account for more efficient processing", "LOG", ".", "debug", "(", "f'[@] Update Records: {records}'", ")", "capture_update_records", "(", "update_records", ")" ]
Historical vpc event collector. This collector is responsible for processing Cloudwatch events and polling events.
[ "Historical", "vpc", "event", "collector", ".", "This", "collector", "is", "responsible", "for", "processing", "Cloudwatch", "events", "and", "polling", "events", "." ]
c3ebaa8388a3fe67e23a6c9c6b04c3e618497c4a
https://github.com/Netflix-Skunkworks/historical/blob/c3ebaa8388a3fe67e23a6c9c6b04c3e618497c4a/historical/vpc/collector.py#L165-L183
4,160
Netflix-Skunkworks/historical
historical/common/dynamodb.py
default_diff
def default_diff(latest_config, current_config): """Determine if two revisions have actually changed.""" # Pop off the fields we don't care about: pop_no_diff_fields(latest_config, current_config) diff = DeepDiff( latest_config, current_config, ignore_order=True ) return diff
python
def default_diff(latest_config, current_config): """Determine if two revisions have actually changed.""" # Pop off the fields we don't care about: pop_no_diff_fields(latest_config, current_config) diff = DeepDiff( latest_config, current_config, ignore_order=True ) return diff
[ "def", "default_diff", "(", "latest_config", ",", "current_config", ")", ":", "# Pop off the fields we don't care about:", "pop_no_diff_fields", "(", "latest_config", ",", "current_config", ")", "diff", "=", "DeepDiff", "(", "latest_config", ",", "current_config", ",", "ignore_order", "=", "True", ")", "return", "diff" ]
Determine if two revisions have actually changed.
[ "Determine", "if", "two", "revisions", "have", "actually", "changed", "." ]
c3ebaa8388a3fe67e23a6c9c6b04c3e618497c4a
https://github.com/Netflix-Skunkworks/historical/blob/c3ebaa8388a3fe67e23a6c9c6b04c3e618497c4a/historical/common/dynamodb.py#L33-L43
4,161
Netflix-Skunkworks/historical
historical/common/dynamodb.py
pop_no_diff_fields
def pop_no_diff_fields(latest_config, current_config): """Pops off fields that should not be included in the diff.""" for field in ['userIdentity', 'principalId', 'userAgent', 'sourceIpAddress', 'requestParameters', 'eventName']: latest_config.pop(field, None) current_config.pop(field, None)
python
def pop_no_diff_fields(latest_config, current_config): """Pops off fields that should not be included in the diff.""" for field in ['userIdentity', 'principalId', 'userAgent', 'sourceIpAddress', 'requestParameters', 'eventName']: latest_config.pop(field, None) current_config.pop(field, None)
[ "def", "pop_no_diff_fields", "(", "latest_config", ",", "current_config", ")", ":", "for", "field", "in", "[", "'userIdentity'", ",", "'principalId'", ",", "'userAgent'", ",", "'sourceIpAddress'", ",", "'requestParameters'", ",", "'eventName'", "]", ":", "latest_config", ".", "pop", "(", "field", ",", "None", ")", "current_config", ".", "pop", "(", "field", ",", "None", ")" ]
Pops off fields that should not be included in the diff.
[ "Pops", "off", "fields", "that", "should", "not", "be", "included", "in", "the", "diff", "." ]
c3ebaa8388a3fe67e23a6c9c6b04c3e618497c4a
https://github.com/Netflix-Skunkworks/historical/blob/c3ebaa8388a3fe67e23a6c9c6b04c3e618497c4a/historical/common/dynamodb.py#L46-L50
4,162
Netflix-Skunkworks/historical
historical/common/dynamodb.py
modify_record
def modify_record(durable_model, current_revision, arn, event_time, diff_func): """Handles a DynamoDB MODIFY event type.""" # We want the newest items first. # See: http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Query.html items = list(durable_model.query( arn, (durable_model.eventTime <= event_time), scan_index_forward=False, limit=1, consistent_read=True)) if items: latest_revision = items[0] latest_config = latest_revision._get_json()[1]['attributes'] # pylint: disable=W0212 current_config = current_revision._get_json()[1]['attributes'] # pylint: disable=W0212 # Determine if there is truly a difference, disregarding Ephemeral Paths diff = diff_func(latest_config, current_config) if diff: LOG.debug( f'[~] Difference found saving new revision to durable table. Arn: {arn} LatestConfig: {latest_config} ' f'CurrentConfig: {json.dumps(current_config)}') current_revision.save() else: current_revision.save() LOG.info(f'[?] Got modify event but no current revision found. Arn: {arn}')
python
def modify_record(durable_model, current_revision, arn, event_time, diff_func): """Handles a DynamoDB MODIFY event type.""" # We want the newest items first. # See: http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Query.html items = list(durable_model.query( arn, (durable_model.eventTime <= event_time), scan_index_forward=False, limit=1, consistent_read=True)) if items: latest_revision = items[0] latest_config = latest_revision._get_json()[1]['attributes'] # pylint: disable=W0212 current_config = current_revision._get_json()[1]['attributes'] # pylint: disable=W0212 # Determine if there is truly a difference, disregarding Ephemeral Paths diff = diff_func(latest_config, current_config) if diff: LOG.debug( f'[~] Difference found saving new revision to durable table. Arn: {arn} LatestConfig: {latest_config} ' f'CurrentConfig: {json.dumps(current_config)}') current_revision.save() else: current_revision.save() LOG.info(f'[?] Got modify event but no current revision found. Arn: {arn}')
[ "def", "modify_record", "(", "durable_model", ",", "current_revision", ",", "arn", ",", "event_time", ",", "diff_func", ")", ":", "# We want the newest items first.", "# See: http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Query.html", "items", "=", "list", "(", "durable_model", ".", "query", "(", "arn", ",", "(", "durable_model", ".", "eventTime", "<=", "event_time", ")", ",", "scan_index_forward", "=", "False", ",", "limit", "=", "1", ",", "consistent_read", "=", "True", ")", ")", "if", "items", ":", "latest_revision", "=", "items", "[", "0", "]", "latest_config", "=", "latest_revision", ".", "_get_json", "(", ")", "[", "1", "]", "[", "'attributes'", "]", "# pylint: disable=W0212", "current_config", "=", "current_revision", ".", "_get_json", "(", ")", "[", "1", "]", "[", "'attributes'", "]", "# pylint: disable=W0212", "# Determine if there is truly a difference, disregarding Ephemeral Paths", "diff", "=", "diff_func", "(", "latest_config", ",", "current_config", ")", "if", "diff", ":", "LOG", ".", "debug", "(", "f'[~] Difference found saving new revision to durable table. Arn: {arn} LatestConfig: {latest_config} '", "f'CurrentConfig: {json.dumps(current_config)}'", ")", "current_revision", ".", "save", "(", ")", "else", ":", "current_revision", ".", "save", "(", ")", "LOG", ".", "info", "(", "f'[?] Got modify event but no current revision found. Arn: {arn}'", ")" ]
Handles a DynamoDB MODIFY event type.
[ "Handles", "a", "DynamoDB", "MODIFY", "event", "type", "." ]
c3ebaa8388a3fe67e23a6c9c6b04c3e618497c4a
https://github.com/Netflix-Skunkworks/historical/blob/c3ebaa8388a3fe67e23a6c9c6b04c3e618497c4a/historical/common/dynamodb.py#L82-L108
4,163
Netflix-Skunkworks/historical
historical/common/dynamodb.py
deserialize_current_record_to_durable_model
def deserialize_current_record_to_durable_model(record, current_model, durable_model): """ Utility function that will take a dynamo event record and turn it into the proper pynamo object. This will properly deserialize the ugly Dynamo datatypes away. :param record: :param current_model: :param durable_model: :return: """ # Was the item in question too big for SNS? If so, then we need to fetch the item from the current Dynamo table: if record.get(EVENT_TOO_BIG_FLAG): record = get_full_current_object(record['dynamodb']['Keys']['arn']['S'], current_model) if not record: return None serialized = record._serialize() # pylint: disable=W0212 record = { 'dynamodb': { 'NewImage': serialized['attributes'] } } # The ARN isn't added because it's in the HASH key section: record['dynamodb']['NewImage']['arn'] = {'S': serialized['HASH']} new_image = remove_current_specific_fields(record['dynamodb']['NewImage']) data = {} for item, value in new_image.items(): # This could end up as loss of precision data[item] = DESER.deserialize(value) return durable_model(**data)
python
def deserialize_current_record_to_durable_model(record, current_model, durable_model): """ Utility function that will take a dynamo event record and turn it into the proper pynamo object. This will properly deserialize the ugly Dynamo datatypes away. :param record: :param current_model: :param durable_model: :return: """ # Was the item in question too big for SNS? If so, then we need to fetch the item from the current Dynamo table: if record.get(EVENT_TOO_BIG_FLAG): record = get_full_current_object(record['dynamodb']['Keys']['arn']['S'], current_model) if not record: return None serialized = record._serialize() # pylint: disable=W0212 record = { 'dynamodb': { 'NewImage': serialized['attributes'] } } # The ARN isn't added because it's in the HASH key section: record['dynamodb']['NewImage']['arn'] = {'S': serialized['HASH']} new_image = remove_current_specific_fields(record['dynamodb']['NewImage']) data = {} for item, value in new_image.items(): # This could end up as loss of precision data[item] = DESER.deserialize(value) return durable_model(**data)
[ "def", "deserialize_current_record_to_durable_model", "(", "record", ",", "current_model", ",", "durable_model", ")", ":", "# Was the item in question too big for SNS? If so, then we need to fetch the item from the current Dynamo table:", "if", "record", ".", "get", "(", "EVENT_TOO_BIG_FLAG", ")", ":", "record", "=", "get_full_current_object", "(", "record", "[", "'dynamodb'", "]", "[", "'Keys'", "]", "[", "'arn'", "]", "[", "'S'", "]", ",", "current_model", ")", "if", "not", "record", ":", "return", "None", "serialized", "=", "record", ".", "_serialize", "(", ")", "# pylint: disable=W0212", "record", "=", "{", "'dynamodb'", ":", "{", "'NewImage'", ":", "serialized", "[", "'attributes'", "]", "}", "}", "# The ARN isn't added because it's in the HASH key section:", "record", "[", "'dynamodb'", "]", "[", "'NewImage'", "]", "[", "'arn'", "]", "=", "{", "'S'", ":", "serialized", "[", "'HASH'", "]", "}", "new_image", "=", "remove_current_specific_fields", "(", "record", "[", "'dynamodb'", "]", "[", "'NewImage'", "]", ")", "data", "=", "{", "}", "for", "item", ",", "value", "in", "new_image", ".", "items", "(", ")", ":", "# This could end up as loss of precision", "data", "[", "item", "]", "=", "DESER", ".", "deserialize", "(", "value", ")", "return", "durable_model", "(", "*", "*", "data", ")" ]
Utility function that will take a dynamo event record and turn it into the proper pynamo object. This will properly deserialize the ugly Dynamo datatypes away. :param record: :param current_model: :param durable_model: :return:
[ "Utility", "function", "that", "will", "take", "a", "dynamo", "event", "record", "and", "turn", "it", "into", "the", "proper", "pynamo", "object", "." ]
c3ebaa8388a3fe67e23a6c9c6b04c3e618497c4a
https://github.com/Netflix-Skunkworks/historical/blob/c3ebaa8388a3fe67e23a6c9c6b04c3e618497c4a/historical/common/dynamodb.py#L168-L203
4,164
Netflix-Skunkworks/historical
historical/common/dynamodb.py
deserialize_current_record_to_current_model
def deserialize_current_record_to_current_model(record, current_model): """ Utility function that will take a Dynamo event record and turn it into the proper Current Dynamo object. This will remove the "current table" specific fields, and properly deserialize the ugly Dynamo datatypes away. :param record: :param current_model: :return: """ # Was the item in question too big for SNS? If so, then we need to fetch the item from the current Dynamo table: if record.get(EVENT_TOO_BIG_FLAG): return get_full_current_object(record['dynamodb']['Keys']['arn']['S'], current_model) new_image = remove_global_dynamo_specific_fields(record['dynamodb']['NewImage']) data = {} for item, value in new_image.items(): # This could end up as loss of precision data[item] = DESER.deserialize(value) return current_model(**data)
python
def deserialize_current_record_to_current_model(record, current_model): """ Utility function that will take a Dynamo event record and turn it into the proper Current Dynamo object. This will remove the "current table" specific fields, and properly deserialize the ugly Dynamo datatypes away. :param record: :param current_model: :return: """ # Was the item in question too big for SNS? If so, then we need to fetch the item from the current Dynamo table: if record.get(EVENT_TOO_BIG_FLAG): return get_full_current_object(record['dynamodb']['Keys']['arn']['S'], current_model) new_image = remove_global_dynamo_specific_fields(record['dynamodb']['NewImage']) data = {} for item, value in new_image.items(): # This could end up as loss of precision data[item] = DESER.deserialize(value) return current_model(**data)
[ "def", "deserialize_current_record_to_current_model", "(", "record", ",", "current_model", ")", ":", "# Was the item in question too big for SNS? If so, then we need to fetch the item from the current Dynamo table:", "if", "record", ".", "get", "(", "EVENT_TOO_BIG_FLAG", ")", ":", "return", "get_full_current_object", "(", "record", "[", "'dynamodb'", "]", "[", "'Keys'", "]", "[", "'arn'", "]", "[", "'S'", "]", ",", "current_model", ")", "new_image", "=", "remove_global_dynamo_specific_fields", "(", "record", "[", "'dynamodb'", "]", "[", "'NewImage'", "]", ")", "data", "=", "{", "}", "for", "item", ",", "value", "in", "new_image", ".", "items", "(", ")", ":", "# This could end up as loss of precision", "data", "[", "item", "]", "=", "DESER", ".", "deserialize", "(", "value", ")", "return", "current_model", "(", "*", "*", "data", ")" ]
Utility function that will take a Dynamo event record and turn it into the proper Current Dynamo object. This will remove the "current table" specific fields, and properly deserialize the ugly Dynamo datatypes away. :param record: :param current_model: :return:
[ "Utility", "function", "that", "will", "take", "a", "Dynamo", "event", "record", "and", "turn", "it", "into", "the", "proper", "Current", "Dynamo", "object", "." ]
c3ebaa8388a3fe67e23a6c9c6b04c3e618497c4a
https://github.com/Netflix-Skunkworks/historical/blob/c3ebaa8388a3fe67e23a6c9c6b04c3e618497c4a/historical/common/dynamodb.py#L206-L226
4,165
Netflix-Skunkworks/historical
historical/common/dynamodb.py
deserialize_durable_record_to_durable_model
def deserialize_durable_record_to_durable_model(record, durable_model): """ Utility function that will take a Dynamo event record and turn it into the proper Durable Dynamo object. This will properly deserialize the ugly Dynamo datatypes away. :param record: :param durable_model: :return: """ # Was the item in question too big for SNS? If so, then we need to fetch the item from the current Dynamo table: if record.get(EVENT_TOO_BIG_FLAG): return get_full_durable_object(record['dynamodb']['Keys']['arn']['S'], record['dynamodb']['NewImage']['eventTime']['S'], durable_model) new_image = remove_global_dynamo_specific_fields(record['dynamodb']['NewImage']) data = {} for item, value in new_image.items(): # This could end up as loss of precision data[item] = DESER.deserialize(value) return durable_model(**data)
python
def deserialize_durable_record_to_durable_model(record, durable_model): """ Utility function that will take a Dynamo event record and turn it into the proper Durable Dynamo object. This will properly deserialize the ugly Dynamo datatypes away. :param record: :param durable_model: :return: """ # Was the item in question too big for SNS? If so, then we need to fetch the item from the current Dynamo table: if record.get(EVENT_TOO_BIG_FLAG): return get_full_durable_object(record['dynamodb']['Keys']['arn']['S'], record['dynamodb']['NewImage']['eventTime']['S'], durable_model) new_image = remove_global_dynamo_specific_fields(record['dynamodb']['NewImage']) data = {} for item, value in new_image.items(): # This could end up as loss of precision data[item] = DESER.deserialize(value) return durable_model(**data)
[ "def", "deserialize_durable_record_to_durable_model", "(", "record", ",", "durable_model", ")", ":", "# Was the item in question too big for SNS? If so, then we need to fetch the item from the current Dynamo table:", "if", "record", ".", "get", "(", "EVENT_TOO_BIG_FLAG", ")", ":", "return", "get_full_durable_object", "(", "record", "[", "'dynamodb'", "]", "[", "'Keys'", "]", "[", "'arn'", "]", "[", "'S'", "]", ",", "record", "[", "'dynamodb'", "]", "[", "'NewImage'", "]", "[", "'eventTime'", "]", "[", "'S'", "]", ",", "durable_model", ")", "new_image", "=", "remove_global_dynamo_specific_fields", "(", "record", "[", "'dynamodb'", "]", "[", "'NewImage'", "]", ")", "data", "=", "{", "}", "for", "item", ",", "value", "in", "new_image", ".", "items", "(", ")", ":", "# This could end up as loss of precision", "data", "[", "item", "]", "=", "DESER", ".", "deserialize", "(", "value", ")", "return", "durable_model", "(", "*", "*", "data", ")" ]
Utility function that will take a Dynamo event record and turn it into the proper Durable Dynamo object. This will properly deserialize the ugly Dynamo datatypes away. :param record: :param durable_model: :return:
[ "Utility", "function", "that", "will", "take", "a", "Dynamo", "event", "record", "and", "turn", "it", "into", "the", "proper", "Durable", "Dynamo", "object", "." ]
c3ebaa8388a3fe67e23a6c9c6b04c3e618497c4a
https://github.com/Netflix-Skunkworks/historical/blob/c3ebaa8388a3fe67e23a6c9c6b04c3e618497c4a/historical/common/dynamodb.py#L229-L251
4,166
Netflix-Skunkworks/historical
historical/common/dynamodb.py
deserialize_durable_record_to_current_model
def deserialize_durable_record_to_current_model(record, current_model): """ Utility function that will take a Durable Dynamo event record and turn it into the proper Current Dynamo object. This will properly deserialize the ugly Dynamo datatypes away. :param record: :param current_model: :return: """ # Was the item in question too big for SNS? If so, then we need to fetch the item from the current Dynamo table: if record.get(EVENT_TOO_BIG_FLAG): # Try to get the data from the current table vs. grabbing the data from the Durable table: return get_full_current_object(record['dynamodb']['Keys']['arn']['S'], current_model) new_image = remove_durable_specific_fields(record['dynamodb']['NewImage']) data = {} for item, value in new_image.items(): # This could end up as loss of precision data[item] = DESER.deserialize(value) return current_model(**data)
python
def deserialize_durable_record_to_current_model(record, current_model): """ Utility function that will take a Durable Dynamo event record and turn it into the proper Current Dynamo object. This will properly deserialize the ugly Dynamo datatypes away. :param record: :param current_model: :return: """ # Was the item in question too big for SNS? If so, then we need to fetch the item from the current Dynamo table: if record.get(EVENT_TOO_BIG_FLAG): # Try to get the data from the current table vs. grabbing the data from the Durable table: return get_full_current_object(record['dynamodb']['Keys']['arn']['S'], current_model) new_image = remove_durable_specific_fields(record['dynamodb']['NewImage']) data = {} for item, value in new_image.items(): # This could end up as loss of precision data[item] = DESER.deserialize(value) return current_model(**data)
[ "def", "deserialize_durable_record_to_current_model", "(", "record", ",", "current_model", ")", ":", "# Was the item in question too big for SNS? If so, then we need to fetch the item from the current Dynamo table:", "if", "record", ".", "get", "(", "EVENT_TOO_BIG_FLAG", ")", ":", "# Try to get the data from the current table vs. grabbing the data from the Durable table:", "return", "get_full_current_object", "(", "record", "[", "'dynamodb'", "]", "[", "'Keys'", "]", "[", "'arn'", "]", "[", "'S'", "]", ",", "current_model", ")", "new_image", "=", "remove_durable_specific_fields", "(", "record", "[", "'dynamodb'", "]", "[", "'NewImage'", "]", ")", "data", "=", "{", "}", "for", "item", ",", "value", "in", "new_image", ".", "items", "(", ")", ":", "# This could end up as loss of precision", "data", "[", "item", "]", "=", "DESER", ".", "deserialize", "(", "value", ")", "return", "current_model", "(", "*", "*", "data", ")" ]
Utility function that will take a Durable Dynamo event record and turn it into the proper Current Dynamo object. This will properly deserialize the ugly Dynamo datatypes away. :param record: :param current_model: :return:
[ "Utility", "function", "that", "will", "take", "a", "Durable", "Dynamo", "event", "record", "and", "turn", "it", "into", "the", "proper", "Current", "Dynamo", "object", "." ]
c3ebaa8388a3fe67e23a6c9c6b04c3e618497c4a
https://github.com/Netflix-Skunkworks/historical/blob/c3ebaa8388a3fe67e23a6c9c6b04c3e618497c4a/historical/common/dynamodb.py#L254-L275
4,167
Netflix-Skunkworks/historical
historical/models.py
HistoricalPollerTaskEventModel.serialize_me
def serialize_me(self, account_id, region, next_token=None): """Dumps the proper JSON for the schema. :param account_id: :param region: :param next_token: :return: """ payload = { 'account_id': account_id, 'region': region } if next_token: payload['next_token'] = next_token return self.dumps(payload).data
python
def serialize_me(self, account_id, region, next_token=None): """Dumps the proper JSON for the schema. :param account_id: :param region: :param next_token: :return: """ payload = { 'account_id': account_id, 'region': region } if next_token: payload['next_token'] = next_token return self.dumps(payload).data
[ "def", "serialize_me", "(", "self", ",", "account_id", ",", "region", ",", "next_token", "=", "None", ")", ":", "payload", "=", "{", "'account_id'", ":", "account_id", ",", "'region'", ":", "region", "}", "if", "next_token", ":", "payload", "[", "'next_token'", "]", "=", "next_token", "return", "self", ".", "dumps", "(", "payload", ")", ".", "data" ]
Dumps the proper JSON for the schema. :param account_id: :param region: :param next_token: :return:
[ "Dumps", "the", "proper", "JSON", "for", "the", "schema", "." ]
c3ebaa8388a3fe67e23a6c9c6b04c3e618497c4a
https://github.com/Netflix-Skunkworks/historical/blob/c3ebaa8388a3fe67e23a6c9c6b04c3e618497c4a/historical/models.py#L136-L152
4,168
Netflix-Skunkworks/historical
historical/models.py
SimpleDurableSchema.serialize_me
def serialize_me(self, arn, event_time, tech, item=None): """Dumps the proper JSON for the schema. If the event is too big, then don't include the item. :param arn: :param event_time: :param tech: :param item: :return: """ payload = { 'arn': arn, 'event_time': event_time, 'tech': tech } if item: payload['item'] = item else: payload['event_too_big'] = True return self.dumps(payload).data.replace('<empty>', '')
python
def serialize_me(self, arn, event_time, tech, item=None): """Dumps the proper JSON for the schema. If the event is too big, then don't include the item. :param arn: :param event_time: :param tech: :param item: :return: """ payload = { 'arn': arn, 'event_time': event_time, 'tech': tech } if item: payload['item'] = item else: payload['event_too_big'] = True return self.dumps(payload).data.replace('<empty>', '')
[ "def", "serialize_me", "(", "self", ",", "arn", ",", "event_time", ",", "tech", ",", "item", "=", "None", ")", ":", "payload", "=", "{", "'arn'", ":", "arn", ",", "'event_time'", ":", "event_time", ",", "'tech'", ":", "tech", "}", "if", "item", ":", "payload", "[", "'item'", "]", "=", "item", "else", ":", "payload", "[", "'event_too_big'", "]", "=", "True", "return", "self", ".", "dumps", "(", "payload", ")", ".", "data", ".", "replace", "(", "'<empty>'", ",", "''", ")" ]
Dumps the proper JSON for the schema. If the event is too big, then don't include the item. :param arn: :param event_time: :param tech: :param item: :return:
[ "Dumps", "the", "proper", "JSON", "for", "the", "schema", ".", "If", "the", "event", "is", "too", "big", "then", "don", "t", "include", "the", "item", "." ]
c3ebaa8388a3fe67e23a6c9c6b04c3e618497c4a
https://github.com/Netflix-Skunkworks/historical/blob/c3ebaa8388a3fe67e23a6c9c6b04c3e618497c4a/historical/models.py#L169-L190
4,169
Netflix-Skunkworks/historical
historical/attributes.py
fix_decimals
def fix_decimals(obj): """Removes the stupid Decimals See: https://github.com/boto/boto3/issues/369#issuecomment-302137290 """ if isinstance(obj, list): for i in range(len(obj)): obj[i] = fix_decimals(obj[i]) return obj elif isinstance(obj, dict): for key, value in obj.items(): obj[key] = fix_decimals(value) return obj elif isinstance(obj, decimal.Decimal): if obj % 1 == 0: return int(obj) else: return float(obj) else: return obj
python
def fix_decimals(obj): """Removes the stupid Decimals See: https://github.com/boto/boto3/issues/369#issuecomment-302137290 """ if isinstance(obj, list): for i in range(len(obj)): obj[i] = fix_decimals(obj[i]) return obj elif isinstance(obj, dict): for key, value in obj.items(): obj[key] = fix_decimals(value) return obj elif isinstance(obj, decimal.Decimal): if obj % 1 == 0: return int(obj) else: return float(obj) else: return obj
[ "def", "fix_decimals", "(", "obj", ")", ":", "if", "isinstance", "(", "obj", ",", "list", ")", ":", "for", "i", "in", "range", "(", "len", "(", "obj", ")", ")", ":", "obj", "[", "i", "]", "=", "fix_decimals", "(", "obj", "[", "i", "]", ")", "return", "obj", "elif", "isinstance", "(", "obj", ",", "dict", ")", ":", "for", "key", ",", "value", "in", "obj", ".", "items", "(", ")", ":", "obj", "[", "key", "]", "=", "fix_decimals", "(", "value", ")", "return", "obj", "elif", "isinstance", "(", "obj", ",", "decimal", ".", "Decimal", ")", ":", "if", "obj", "%", "1", "==", "0", ":", "return", "int", "(", "obj", ")", "else", ":", "return", "float", "(", "obj", ")", "else", ":", "return", "obj" ]
Removes the stupid Decimals See: https://github.com/boto/boto3/issues/369#issuecomment-302137290
[ "Removes", "the", "stupid", "Decimals" ]
c3ebaa8388a3fe67e23a6c9c6b04c3e618497c4a
https://github.com/Netflix-Skunkworks/historical/blob/c3ebaa8388a3fe67e23a6c9c6b04c3e618497c4a/historical/attributes.py#L62-L84
4,170
Netflix-Skunkworks/historical
historical/attributes.py
EventTimeAttribute.serialize
def serialize(self, value): """Takes a datetime object and returns a string""" if isinstance(value, str): return value return value.strftime(DATETIME_FORMAT)
python
def serialize(self, value): """Takes a datetime object and returns a string""" if isinstance(value, str): return value return value.strftime(DATETIME_FORMAT)
[ "def", "serialize", "(", "self", ",", "value", ")", ":", "if", "isinstance", "(", "value", ",", "str", ")", ":", "return", "value", "return", "value", ".", "strftime", "(", "DATETIME_FORMAT", ")" ]
Takes a datetime object and returns a string
[ "Takes", "a", "datetime", "object", "and", "returns", "a", "string" ]
c3ebaa8388a3fe67e23a6c9c6b04c3e618497c4a
https://github.com/Netflix-Skunkworks/historical/blob/c3ebaa8388a3fe67e23a6c9c6b04c3e618497c4a/historical/attributes.py#L45-L49
4,171
Netflix-Skunkworks/historical
historical/common/util.py
pull_tag_dict
def pull_tag_dict(data): """This will pull out a list of Tag Name-Value objects, and return it as a dictionary. :param data: The dict collected from the collector. :returns dict: A dict of the tag names and their corresponding values. """ # If there are tags, set them to a normal dict, vs. a list of dicts: tags = data.pop('Tags', {}) or {} if tags: proper_tags = {} for tag in tags: proper_tags[tag['Key']] = tag['Value'] tags = proper_tags return tags
python
def pull_tag_dict(data): """This will pull out a list of Tag Name-Value objects, and return it as a dictionary. :param data: The dict collected from the collector. :returns dict: A dict of the tag names and their corresponding values. """ # If there are tags, set them to a normal dict, vs. a list of dicts: tags = data.pop('Tags', {}) or {} if tags: proper_tags = {} for tag in tags: proper_tags[tag['Key']] = tag['Value'] tags = proper_tags return tags
[ "def", "pull_tag_dict", "(", "data", ")", ":", "# If there are tags, set them to a normal dict, vs. a list of dicts:", "tags", "=", "data", ".", "pop", "(", "'Tags'", ",", "{", "}", ")", "or", "{", "}", "if", "tags", ":", "proper_tags", "=", "{", "}", "for", "tag", "in", "tags", ":", "proper_tags", "[", "tag", "[", "'Key'", "]", "]", "=", "tag", "[", "'Value'", "]", "tags", "=", "proper_tags", "return", "tags" ]
This will pull out a list of Tag Name-Value objects, and return it as a dictionary. :param data: The dict collected from the collector. :returns dict: A dict of the tag names and their corresponding values.
[ "This", "will", "pull", "out", "a", "list", "of", "Tag", "Name", "-", "Value", "objects", "and", "return", "it", "as", "a", "dictionary", "." ]
c3ebaa8388a3fe67e23a6c9c6b04c3e618497c4a
https://github.com/Netflix-Skunkworks/historical/blob/c3ebaa8388a3fe67e23a6c9c6b04c3e618497c4a/historical/common/util.py#L39-L54
4,172
Netflix-Skunkworks/historical
historical/s3/collector.py
create_delete_model
def create_delete_model(record): """Create an S3 model from a record.""" arn = f"arn:aws:s3:::{cloudwatch.filter_request_parameters('bucketName', record)}" LOG.debug(f'[-] Deleting Dynamodb Records. Hash Key: {arn}') data = { 'arn': arn, 'principalId': cloudwatch.get_principal(record), 'userIdentity': cloudwatch.get_user_identity(record), 'accountId': record['account'], 'eventTime': record['detail']['eventTime'], 'BucketName': cloudwatch.filter_request_parameters('bucketName', record), 'Region': cloudwatch.get_region(record), 'Tags': {}, 'configuration': {}, 'eventSource': record['detail']['eventSource'], 'version': VERSION } return CurrentS3Model(**data)
python
def create_delete_model(record): """Create an S3 model from a record.""" arn = f"arn:aws:s3:::{cloudwatch.filter_request_parameters('bucketName', record)}" LOG.debug(f'[-] Deleting Dynamodb Records. Hash Key: {arn}') data = { 'arn': arn, 'principalId': cloudwatch.get_principal(record), 'userIdentity': cloudwatch.get_user_identity(record), 'accountId': record['account'], 'eventTime': record['detail']['eventTime'], 'BucketName': cloudwatch.filter_request_parameters('bucketName', record), 'Region': cloudwatch.get_region(record), 'Tags': {}, 'configuration': {}, 'eventSource': record['detail']['eventSource'], 'version': VERSION } return CurrentS3Model(**data)
[ "def", "create_delete_model", "(", "record", ")", ":", "arn", "=", "f\"arn:aws:s3:::{cloudwatch.filter_request_parameters('bucketName', record)}\"", "LOG", ".", "debug", "(", "f'[-] Deleting Dynamodb Records. Hash Key: {arn}'", ")", "data", "=", "{", "'arn'", ":", "arn", ",", "'principalId'", ":", "cloudwatch", ".", "get_principal", "(", "record", ")", ",", "'userIdentity'", ":", "cloudwatch", ".", "get_user_identity", "(", "record", ")", ",", "'accountId'", ":", "record", "[", "'account'", "]", ",", "'eventTime'", ":", "record", "[", "'detail'", "]", "[", "'eventTime'", "]", ",", "'BucketName'", ":", "cloudwatch", ".", "filter_request_parameters", "(", "'bucketName'", ",", "record", ")", ",", "'Region'", ":", "cloudwatch", ".", "get_region", "(", "record", ")", ",", "'Tags'", ":", "{", "}", ",", "'configuration'", ":", "{", "}", ",", "'eventSource'", ":", "record", "[", "'detail'", "]", "[", "'eventSource'", "]", ",", "'version'", ":", "VERSION", "}", "return", "CurrentS3Model", "(", "*", "*", "data", ")" ]
Create an S3 model from a record.
[ "Create", "an", "S3", "model", "from", "a", "record", "." ]
c3ebaa8388a3fe67e23a6c9c6b04c3e618497c4a
https://github.com/Netflix-Skunkworks/historical/blob/c3ebaa8388a3fe67e23a6c9c6b04c3e618497c4a/historical/s3/collector.py#L55-L74
4,173
Netflix-Skunkworks/historical
historical/s3/collector.py
process_delete_records
def process_delete_records(delete_records): """Process the requests for S3 bucket deletions""" for rec in delete_records: arn = f"arn:aws:s3:::{rec['detail']['requestParameters']['bucketName']}" # Need to check if the event is NEWER than the previous event in case # events are out of order. This could *possibly* happen if something # was deleted, and then quickly re-created. It could be *possible* for the # deletion event to arrive after the creation event. Thus, this will check # if the current event timestamp is newer and will only delete if the deletion # event is newer. try: LOG.debug(f'[-] Deleting bucket: {arn}') model = create_delete_model(rec) model.save(condition=(CurrentS3Model.eventTime <= rec['detail']['eventTime'])) model.delete() except PynamoDBConnectionError as pdce: LOG.warning(f"[?] Unable to delete bucket: {arn}. Either it doesn't exist, or this deletion event is stale " f"(arrived before a NEWER creation/update). The specific exception is: {pdce}")
python
def process_delete_records(delete_records): """Process the requests for S3 bucket deletions""" for rec in delete_records: arn = f"arn:aws:s3:::{rec['detail']['requestParameters']['bucketName']}" # Need to check if the event is NEWER than the previous event in case # events are out of order. This could *possibly* happen if something # was deleted, and then quickly re-created. It could be *possible* for the # deletion event to arrive after the creation event. Thus, this will check # if the current event timestamp is newer and will only delete if the deletion # event is newer. try: LOG.debug(f'[-] Deleting bucket: {arn}') model = create_delete_model(rec) model.save(condition=(CurrentS3Model.eventTime <= rec['detail']['eventTime'])) model.delete() except PynamoDBConnectionError as pdce: LOG.warning(f"[?] Unable to delete bucket: {arn}. Either it doesn't exist, or this deletion event is stale " f"(arrived before a NEWER creation/update). The specific exception is: {pdce}")
[ "def", "process_delete_records", "(", "delete_records", ")", ":", "for", "rec", "in", "delete_records", ":", "arn", "=", "f\"arn:aws:s3:::{rec['detail']['requestParameters']['bucketName']}\"", "# Need to check if the event is NEWER than the previous event in case", "# events are out of order. This could *possibly* happen if something", "# was deleted, and then quickly re-created. It could be *possible* for the", "# deletion event to arrive after the creation event. Thus, this will check", "# if the current event timestamp is newer and will only delete if the deletion", "# event is newer.", "try", ":", "LOG", ".", "debug", "(", "f'[-] Deleting bucket: {arn}'", ")", "model", "=", "create_delete_model", "(", "rec", ")", "model", ".", "save", "(", "condition", "=", "(", "CurrentS3Model", ".", "eventTime", "<=", "rec", "[", "'detail'", "]", "[", "'eventTime'", "]", ")", ")", "model", ".", "delete", "(", ")", "except", "PynamoDBConnectionError", "as", "pdce", ":", "LOG", ".", "warning", "(", "f\"[?] Unable to delete bucket: {arn}. Either it doesn't exist, or this deletion event is stale \"", "f\"(arrived before a NEWER creation/update). The specific exception is: {pdce}\"", ")" ]
Process the requests for S3 bucket deletions
[ "Process", "the", "requests", "for", "S3", "bucket", "deletions" ]
c3ebaa8388a3fe67e23a6c9c6b04c3e618497c4a
https://github.com/Netflix-Skunkworks/historical/blob/c3ebaa8388a3fe67e23a6c9c6b04c3e618497c4a/historical/s3/collector.py#L77-L96
4,174
Netflix-Skunkworks/historical
historical/s3/collector.py
process_update_records
def process_update_records(update_records): """Process the requests for S3 bucket update requests""" events = sorted(update_records, key=lambda x: x['account']) # Group records by account for more efficient processing for account_id, events in groupby(events, lambda x: x['account']): events = list(events) # Grab the bucket names (de-dupe events): buckets = {} for event in events: # If the creation date is present, then use it: bucket_event = buckets.get(event['detail']['requestParameters']['bucketName'], { 'creationDate': event['detail']['requestParameters'].get('creationDate') }) bucket_event.update(event['detail']['requestParameters']) buckets[event['detail']['requestParameters']['bucketName']] = bucket_event buckets[event['detail']['requestParameters']['bucketName']]['eventDetails'] = event # Query AWS for current configuration for b_name, item in buckets.items(): LOG.debug(f'[~] Processing Create/Update for: {b_name}') # If the bucket does not exist, then simply drop the request -- # If this happens, there is likely a Delete event that has occurred and will be processed soon. try: bucket_details = get_bucket(b_name, account_number=account_id, include_created=(item.get('creationDate') is None), assume_role=HISTORICAL_ROLE, region=CURRENT_REGION) if bucket_details.get('Error'): LOG.error(f"[X] Unable to fetch details about bucket: {b_name}. " f"The error details are: {bucket_details['Error']}") continue except ClientError as cerr: if cerr.response['Error']['Code'] == 'NoSuchBucket': LOG.warning(f'[?] Received update request for bucket: {b_name} that does not ' 'currently exist. Skipping.') continue # Catch Access Denied exceptions as well: if cerr.response['Error']['Code'] == 'AccessDenied': LOG.error(f'[X] Unable to fetch details for S3 Bucket: {b_name} in {account_id}. Access is Denied. ' 'Skipping...') continue raise Exception(cerr) # Pull out the fields we want: data = { 'arn': f'arn:aws:s3:::{b_name}', 'principalId': cloudwatch.get_principal(item['eventDetails']), 'userIdentity': cloudwatch.get_user_identity(item['eventDetails']), 'userAgent': item['eventDetails']['detail'].get('userAgent'), 'sourceIpAddress': item['eventDetails']['detail'].get('sourceIPAddress'), 'requestParameters': item['eventDetails']['detail'].get('requestParameters'), 'accountId': account_id, 'eventTime': item['eventDetails']['detail']['eventTime'], 'BucketName': b_name, 'Region': bucket_details.pop('Region'), # Duplicated in top level and configuration for secondary index 'Tags': bucket_details.pop('Tags', {}) or {}, 'eventSource': item['eventDetails']['detail']['eventSource'], 'eventName': item['eventDetails']['detail']['eventName'], 'version': VERSION } # Remove the fields we don't care about: del bucket_details['Arn'] del bucket_details['GrantReferences'] del bucket_details['_version'] del bucket_details['Name'] if not bucket_details.get('CreationDate'): bucket_details['CreationDate'] = item['creationDate'] data['configuration'] = bucket_details current_revision = CurrentS3Model(**data) current_revision.save()
python
def process_update_records(update_records): """Process the requests for S3 bucket update requests""" events = sorted(update_records, key=lambda x: x['account']) # Group records by account for more efficient processing for account_id, events in groupby(events, lambda x: x['account']): events = list(events) # Grab the bucket names (de-dupe events): buckets = {} for event in events: # If the creation date is present, then use it: bucket_event = buckets.get(event['detail']['requestParameters']['bucketName'], { 'creationDate': event['detail']['requestParameters'].get('creationDate') }) bucket_event.update(event['detail']['requestParameters']) buckets[event['detail']['requestParameters']['bucketName']] = bucket_event buckets[event['detail']['requestParameters']['bucketName']]['eventDetails'] = event # Query AWS for current configuration for b_name, item in buckets.items(): LOG.debug(f'[~] Processing Create/Update for: {b_name}') # If the bucket does not exist, then simply drop the request -- # If this happens, there is likely a Delete event that has occurred and will be processed soon. try: bucket_details = get_bucket(b_name, account_number=account_id, include_created=(item.get('creationDate') is None), assume_role=HISTORICAL_ROLE, region=CURRENT_REGION) if bucket_details.get('Error'): LOG.error(f"[X] Unable to fetch details about bucket: {b_name}. " f"The error details are: {bucket_details['Error']}") continue except ClientError as cerr: if cerr.response['Error']['Code'] == 'NoSuchBucket': LOG.warning(f'[?] Received update request for bucket: {b_name} that does not ' 'currently exist. Skipping.') continue # Catch Access Denied exceptions as well: if cerr.response['Error']['Code'] == 'AccessDenied': LOG.error(f'[X] Unable to fetch details for S3 Bucket: {b_name} in {account_id}. Access is Denied. ' 'Skipping...') continue raise Exception(cerr) # Pull out the fields we want: data = { 'arn': f'arn:aws:s3:::{b_name}', 'principalId': cloudwatch.get_principal(item['eventDetails']), 'userIdentity': cloudwatch.get_user_identity(item['eventDetails']), 'userAgent': item['eventDetails']['detail'].get('userAgent'), 'sourceIpAddress': item['eventDetails']['detail'].get('sourceIPAddress'), 'requestParameters': item['eventDetails']['detail'].get('requestParameters'), 'accountId': account_id, 'eventTime': item['eventDetails']['detail']['eventTime'], 'BucketName': b_name, 'Region': bucket_details.pop('Region'), # Duplicated in top level and configuration for secondary index 'Tags': bucket_details.pop('Tags', {}) or {}, 'eventSource': item['eventDetails']['detail']['eventSource'], 'eventName': item['eventDetails']['detail']['eventName'], 'version': VERSION } # Remove the fields we don't care about: del bucket_details['Arn'] del bucket_details['GrantReferences'] del bucket_details['_version'] del bucket_details['Name'] if not bucket_details.get('CreationDate'): bucket_details['CreationDate'] = item['creationDate'] data['configuration'] = bucket_details current_revision = CurrentS3Model(**data) current_revision.save()
[ "def", "process_update_records", "(", "update_records", ")", ":", "events", "=", "sorted", "(", "update_records", ",", "key", "=", "lambda", "x", ":", "x", "[", "'account'", "]", ")", "# Group records by account for more efficient processing", "for", "account_id", ",", "events", "in", "groupby", "(", "events", ",", "lambda", "x", ":", "x", "[", "'account'", "]", ")", ":", "events", "=", "list", "(", "events", ")", "# Grab the bucket names (de-dupe events):", "buckets", "=", "{", "}", "for", "event", "in", "events", ":", "# If the creation date is present, then use it:", "bucket_event", "=", "buckets", ".", "get", "(", "event", "[", "'detail'", "]", "[", "'requestParameters'", "]", "[", "'bucketName'", "]", ",", "{", "'creationDate'", ":", "event", "[", "'detail'", "]", "[", "'requestParameters'", "]", ".", "get", "(", "'creationDate'", ")", "}", ")", "bucket_event", ".", "update", "(", "event", "[", "'detail'", "]", "[", "'requestParameters'", "]", ")", "buckets", "[", "event", "[", "'detail'", "]", "[", "'requestParameters'", "]", "[", "'bucketName'", "]", "]", "=", "bucket_event", "buckets", "[", "event", "[", "'detail'", "]", "[", "'requestParameters'", "]", "[", "'bucketName'", "]", "]", "[", "'eventDetails'", "]", "=", "event", "# Query AWS for current configuration", "for", "b_name", ",", "item", "in", "buckets", ".", "items", "(", ")", ":", "LOG", ".", "debug", "(", "f'[~] Processing Create/Update for: {b_name}'", ")", "# If the bucket does not exist, then simply drop the request --", "# If this happens, there is likely a Delete event that has occurred and will be processed soon.", "try", ":", "bucket_details", "=", "get_bucket", "(", "b_name", ",", "account_number", "=", "account_id", ",", "include_created", "=", "(", "item", ".", "get", "(", "'creationDate'", ")", "is", "None", ")", ",", "assume_role", "=", "HISTORICAL_ROLE", ",", "region", "=", "CURRENT_REGION", ")", "if", "bucket_details", ".", "get", "(", "'Error'", ")", ":", "LOG", ".", "error", "(", "f\"[X] Unable to fetch details about bucket: {b_name}. \"", "f\"The error details are: {bucket_details['Error']}\"", ")", "continue", "except", "ClientError", "as", "cerr", ":", "if", "cerr", ".", "response", "[", "'Error'", "]", "[", "'Code'", "]", "==", "'NoSuchBucket'", ":", "LOG", ".", "warning", "(", "f'[?] Received update request for bucket: {b_name} that does not '", "'currently exist. Skipping.'", ")", "continue", "# Catch Access Denied exceptions as well:", "if", "cerr", ".", "response", "[", "'Error'", "]", "[", "'Code'", "]", "==", "'AccessDenied'", ":", "LOG", ".", "error", "(", "f'[X] Unable to fetch details for S3 Bucket: {b_name} in {account_id}. Access is Denied. '", "'Skipping...'", ")", "continue", "raise", "Exception", "(", "cerr", ")", "# Pull out the fields we want:", "data", "=", "{", "'arn'", ":", "f'arn:aws:s3:::{b_name}'", ",", "'principalId'", ":", "cloudwatch", ".", "get_principal", "(", "item", "[", "'eventDetails'", "]", ")", ",", "'userIdentity'", ":", "cloudwatch", ".", "get_user_identity", "(", "item", "[", "'eventDetails'", "]", ")", ",", "'userAgent'", ":", "item", "[", "'eventDetails'", "]", "[", "'detail'", "]", ".", "get", "(", "'userAgent'", ")", ",", "'sourceIpAddress'", ":", "item", "[", "'eventDetails'", "]", "[", "'detail'", "]", ".", "get", "(", "'sourceIPAddress'", ")", ",", "'requestParameters'", ":", "item", "[", "'eventDetails'", "]", "[", "'detail'", "]", ".", "get", "(", "'requestParameters'", ")", ",", "'accountId'", ":", "account_id", ",", "'eventTime'", ":", "item", "[", "'eventDetails'", "]", "[", "'detail'", "]", "[", "'eventTime'", "]", ",", "'BucketName'", ":", "b_name", ",", "'Region'", ":", "bucket_details", ".", "pop", "(", "'Region'", ")", ",", "# Duplicated in top level and configuration for secondary index", "'Tags'", ":", "bucket_details", ".", "pop", "(", "'Tags'", ",", "{", "}", ")", "or", "{", "}", ",", "'eventSource'", ":", "item", "[", "'eventDetails'", "]", "[", "'detail'", "]", "[", "'eventSource'", "]", ",", "'eventName'", ":", "item", "[", "'eventDetails'", "]", "[", "'detail'", "]", "[", "'eventName'", "]", ",", "'version'", ":", "VERSION", "}", "# Remove the fields we don't care about:", "del", "bucket_details", "[", "'Arn'", "]", "del", "bucket_details", "[", "'GrantReferences'", "]", "del", "bucket_details", "[", "'_version'", "]", "del", "bucket_details", "[", "'Name'", "]", "if", "not", "bucket_details", ".", "get", "(", "'CreationDate'", ")", ":", "bucket_details", "[", "'CreationDate'", "]", "=", "item", "[", "'creationDate'", "]", "data", "[", "'configuration'", "]", "=", "bucket_details", "current_revision", "=", "CurrentS3Model", "(", "*", "*", "data", ")", "current_revision", ".", "save", "(", ")" ]
Process the requests for S3 bucket update requests
[ "Process", "the", "requests", "for", "S3", "bucket", "update", "requests" ]
c3ebaa8388a3fe67e23a6c9c6b04c3e618497c4a
https://github.com/Netflix-Skunkworks/historical/blob/c3ebaa8388a3fe67e23a6c9c6b04c3e618497c4a/historical/s3/collector.py#L99-L179
4,175
Netflix-Skunkworks/historical
historical/s3/collector.py
handler
def handler(event, context): # pylint: disable=W0613 """ Historical S3 event collector. This collector is responsible for processing CloudWatch events and polling events. """ records = deserialize_records(event['Records']) # Split records into two groups, update and delete. # We don't want to query for deleted records. update_records, delete_records = group_records_by_type(records, UPDATE_EVENTS) LOG.debug('[@] Processing update records...') process_update_records(update_records) LOG.debug('[@] Completed processing of update records.') LOG.debug('[@] Processing delete records...') process_delete_records(delete_records) LOG.debug('[@] Completed processing of delete records.') LOG.debug('[@] Successfully updated current Historical table')
python
def handler(event, context): # pylint: disable=W0613 """ Historical S3 event collector. This collector is responsible for processing CloudWatch events and polling events. """ records = deserialize_records(event['Records']) # Split records into two groups, update and delete. # We don't want to query for deleted records. update_records, delete_records = group_records_by_type(records, UPDATE_EVENTS) LOG.debug('[@] Processing update records...') process_update_records(update_records) LOG.debug('[@] Completed processing of update records.') LOG.debug('[@] Processing delete records...') process_delete_records(delete_records) LOG.debug('[@] Completed processing of delete records.') LOG.debug('[@] Successfully updated current Historical table')
[ "def", "handler", "(", "event", ",", "context", ")", ":", "# pylint: disable=W0613", "records", "=", "deserialize_records", "(", "event", "[", "'Records'", "]", ")", "# Split records into two groups, update and delete.", "# We don't want to query for deleted records.", "update_records", ",", "delete_records", "=", "group_records_by_type", "(", "records", ",", "UPDATE_EVENTS", ")", "LOG", ".", "debug", "(", "'[@] Processing update records...'", ")", "process_update_records", "(", "update_records", ")", "LOG", ".", "debug", "(", "'[@] Completed processing of update records.'", ")", "LOG", ".", "debug", "(", "'[@] Processing delete records...'", ")", "process_delete_records", "(", "delete_records", ")", "LOG", ".", "debug", "(", "'[@] Completed processing of delete records.'", ")", "LOG", ".", "debug", "(", "'[@] Successfully updated current Historical table'", ")" ]
Historical S3 event collector. This collector is responsible for processing CloudWatch events and polling events.
[ "Historical", "S3", "event", "collector", "." ]
c3ebaa8388a3fe67e23a6c9c6b04c3e618497c4a
https://github.com/Netflix-Skunkworks/historical/blob/c3ebaa8388a3fe67e23a6c9c6b04c3e618497c4a/historical/s3/collector.py#L183-L203
4,176
Netflix-Skunkworks/historical
historical/common/accounts.py
get_historical_accounts
def get_historical_accounts(): """Fetches valid accounts from SWAG if enabled or a list accounts.""" if os.environ.get('SWAG_BUCKET', False): swag_opts = { 'swag.type': 's3', 'swag.bucket_name': os.environ['SWAG_BUCKET'], 'swag.data_file': os.environ.get('SWAG_DATA_FILE', 'accounts.json'), 'swag.region': os.environ.get('SWAG_REGION', 'us-east-1') } swag = SWAGManager(**parse_swag_config_options(swag_opts)) search_filter = f"[?provider=='aws' && owner=='{os.environ['SWAG_OWNER']}' && account_status!='deleted'" if parse_boolean(os.environ.get('TEST_ACCOUNTS_ONLY')): search_filter += " && environment=='test'" search_filter += ']' accounts = swag.get_service_enabled('historical', search_filter=search_filter) else: accounts = [{'id': account_id} for account_id in os.environ['ENABLED_ACCOUNTS'].split(',')] return accounts
python
def get_historical_accounts(): """Fetches valid accounts from SWAG if enabled or a list accounts.""" if os.environ.get('SWAG_BUCKET', False): swag_opts = { 'swag.type': 's3', 'swag.bucket_name': os.environ['SWAG_BUCKET'], 'swag.data_file': os.environ.get('SWAG_DATA_FILE', 'accounts.json'), 'swag.region': os.environ.get('SWAG_REGION', 'us-east-1') } swag = SWAGManager(**parse_swag_config_options(swag_opts)) search_filter = f"[?provider=='aws' && owner=='{os.environ['SWAG_OWNER']}' && account_status!='deleted'" if parse_boolean(os.environ.get('TEST_ACCOUNTS_ONLY')): search_filter += " && environment=='test'" search_filter += ']' accounts = swag.get_service_enabled('historical', search_filter=search_filter) else: accounts = [{'id': account_id} for account_id in os.environ['ENABLED_ACCOUNTS'].split(',')] return accounts
[ "def", "get_historical_accounts", "(", ")", ":", "if", "os", ".", "environ", ".", "get", "(", "'SWAG_BUCKET'", ",", "False", ")", ":", "swag_opts", "=", "{", "'swag.type'", ":", "'s3'", ",", "'swag.bucket_name'", ":", "os", ".", "environ", "[", "'SWAG_BUCKET'", "]", ",", "'swag.data_file'", ":", "os", ".", "environ", ".", "get", "(", "'SWAG_DATA_FILE'", ",", "'accounts.json'", ")", ",", "'swag.region'", ":", "os", ".", "environ", ".", "get", "(", "'SWAG_REGION'", ",", "'us-east-1'", ")", "}", "swag", "=", "SWAGManager", "(", "*", "*", "parse_swag_config_options", "(", "swag_opts", ")", ")", "search_filter", "=", "f\"[?provider=='aws' && owner=='{os.environ['SWAG_OWNER']}' && account_status!='deleted'\"", "if", "parse_boolean", "(", "os", ".", "environ", ".", "get", "(", "'TEST_ACCOUNTS_ONLY'", ")", ")", ":", "search_filter", "+=", "\" && environment=='test'\"", "search_filter", "+=", "']'", "accounts", "=", "swag", ".", "get_service_enabled", "(", "'historical'", ",", "search_filter", "=", "search_filter", ")", "else", ":", "accounts", "=", "[", "{", "'id'", ":", "account_id", "}", "for", "account_id", "in", "os", ".", "environ", "[", "'ENABLED_ACCOUNTS'", "]", ".", "split", "(", "','", ")", "]", "return", "accounts" ]
Fetches valid accounts from SWAG if enabled or a list accounts.
[ "Fetches", "valid", "accounts", "from", "SWAG", "if", "enabled", "or", "a", "list", "accounts", "." ]
c3ebaa8388a3fe67e23a6c9c6b04c3e618497c4a
https://github.com/Netflix-Skunkworks/historical/blob/c3ebaa8388a3fe67e23a6c9c6b04c3e618497c4a/historical/common/accounts.py#L26-L47
4,177
Netflix-Skunkworks/historical
historical/s3/poller.py
poller_processor_handler
def poller_processor_handler(event, context): # pylint: disable=W0613 """ Historical S3 Poller Processor. This will receive events from the Poller Tasker, and will list all objects of a given technology for an account/region pair. This will generate `polling events` which simulate changes. These polling events contain configuration data such as the account/region defining where the collector should attempt to gather data from. """ LOG.debug('[@] Running Poller...') queue_url = get_queue_url(os.environ.get('POLLER_QUEUE_NAME', 'HistoricalS3Poller')) records = deserialize_records(event['Records']) for record in records: # Skip accounts that have role assumption errors: try: # List all buckets in the account: all_buckets = list_buckets(account_number=record['account_id'], assume_role=HISTORICAL_ROLE, session_name="historical-cloudwatch-s3list", region=record['region'])["Buckets"] events = [S3_POLLING_SCHEMA.serialize_me(record['account_id'], bucket) for bucket in all_buckets] produce_events(events, queue_url, randomize_delay=RANDOMIZE_POLLER) except ClientError as exc: LOG.error(f"[X] Unable to generate events for account. Account Id: {record['account_id']} Reason: {exc}") LOG.debug(f"[@] Finished generating polling events for account: {record['account_id']}. Events Created:" f" {len(record['account_id'])}")
python
def poller_processor_handler(event, context): # pylint: disable=W0613 """ Historical S3 Poller Processor. This will receive events from the Poller Tasker, and will list all objects of a given technology for an account/region pair. This will generate `polling events` which simulate changes. These polling events contain configuration data such as the account/region defining where the collector should attempt to gather data from. """ LOG.debug('[@] Running Poller...') queue_url = get_queue_url(os.environ.get('POLLER_QUEUE_NAME', 'HistoricalS3Poller')) records = deserialize_records(event['Records']) for record in records: # Skip accounts that have role assumption errors: try: # List all buckets in the account: all_buckets = list_buckets(account_number=record['account_id'], assume_role=HISTORICAL_ROLE, session_name="historical-cloudwatch-s3list", region=record['region'])["Buckets"] events = [S3_POLLING_SCHEMA.serialize_me(record['account_id'], bucket) for bucket in all_buckets] produce_events(events, queue_url, randomize_delay=RANDOMIZE_POLLER) except ClientError as exc: LOG.error(f"[X] Unable to generate events for account. Account Id: {record['account_id']} Reason: {exc}") LOG.debug(f"[@] Finished generating polling events for account: {record['account_id']}. Events Created:" f" {len(record['account_id'])}")
[ "def", "poller_processor_handler", "(", "event", ",", "context", ")", ":", "# pylint: disable=W0613", "LOG", ".", "debug", "(", "'[@] Running Poller...'", ")", "queue_url", "=", "get_queue_url", "(", "os", ".", "environ", ".", "get", "(", "'POLLER_QUEUE_NAME'", ",", "'HistoricalS3Poller'", ")", ")", "records", "=", "deserialize_records", "(", "event", "[", "'Records'", "]", ")", "for", "record", "in", "records", ":", "# Skip accounts that have role assumption errors:", "try", ":", "# List all buckets in the account:", "all_buckets", "=", "list_buckets", "(", "account_number", "=", "record", "[", "'account_id'", "]", ",", "assume_role", "=", "HISTORICAL_ROLE", ",", "session_name", "=", "\"historical-cloudwatch-s3list\"", ",", "region", "=", "record", "[", "'region'", "]", ")", "[", "\"Buckets\"", "]", "events", "=", "[", "S3_POLLING_SCHEMA", ".", "serialize_me", "(", "record", "[", "'account_id'", "]", ",", "bucket", ")", "for", "bucket", "in", "all_buckets", "]", "produce_events", "(", "events", ",", "queue_url", ",", "randomize_delay", "=", "RANDOMIZE_POLLER", ")", "except", "ClientError", "as", "exc", ":", "LOG", ".", "error", "(", "f\"[X] Unable to generate events for account. Account Id: {record['account_id']} Reason: {exc}\"", ")", "LOG", ".", "debug", "(", "f\"[@] Finished generating polling events for account: {record['account_id']}. Events Created:\"", "f\" {len(record['account_id'])}\"", ")" ]
Historical S3 Poller Processor. This will receive events from the Poller Tasker, and will list all objects of a given technology for an account/region pair. This will generate `polling events` which simulate changes. These polling events contain configuration data such as the account/region defining where the collector should attempt to gather data from.
[ "Historical", "S3", "Poller", "Processor", "." ]
c3ebaa8388a3fe67e23a6c9c6b04c3e618497c4a
https://github.com/Netflix-Skunkworks/historical/blob/c3ebaa8388a3fe67e23a6c9c6b04c3e618497c4a/historical/s3/poller.py#L58-L87
4,178
Netflix-Skunkworks/historical
historical/common/proxy.py
detect_global_table_updates
def detect_global_table_updates(record): """This will detect DDB Global Table updates that are not relevant to application data updates. These need to be skipped over as they are pure noise. :param record: :return: """ # This only affects MODIFY events. if record['eventName'] == 'MODIFY': # Need to compare the old and new images to check for GT specific changes only (just pop off the GT fields) old_image = remove_global_dynamo_specific_fields(record['dynamodb']['OldImage']) new_image = remove_global_dynamo_specific_fields(record['dynamodb']['NewImage']) if json.dumps(old_image, sort_keys=True) == json.dumps(new_image, sort_keys=True): return True return False
python
def detect_global_table_updates(record): """This will detect DDB Global Table updates that are not relevant to application data updates. These need to be skipped over as they are pure noise. :param record: :return: """ # This only affects MODIFY events. if record['eventName'] == 'MODIFY': # Need to compare the old and new images to check for GT specific changes only (just pop off the GT fields) old_image = remove_global_dynamo_specific_fields(record['dynamodb']['OldImage']) new_image = remove_global_dynamo_specific_fields(record['dynamodb']['NewImage']) if json.dumps(old_image, sort_keys=True) == json.dumps(new_image, sort_keys=True): return True return False
[ "def", "detect_global_table_updates", "(", "record", ")", ":", "# This only affects MODIFY events.", "if", "record", "[", "'eventName'", "]", "==", "'MODIFY'", ":", "# Need to compare the old and new images to check for GT specific changes only (just pop off the GT fields)", "old_image", "=", "remove_global_dynamo_specific_fields", "(", "record", "[", "'dynamodb'", "]", "[", "'OldImage'", "]", ")", "new_image", "=", "remove_global_dynamo_specific_fields", "(", "record", "[", "'dynamodb'", "]", "[", "'NewImage'", "]", ")", "if", "json", ".", "dumps", "(", "old_image", ",", "sort_keys", "=", "True", ")", "==", "json", ".", "dumps", "(", "new_image", ",", "sort_keys", "=", "True", ")", ":", "return", "True", "return", "False" ]
This will detect DDB Global Table updates that are not relevant to application data updates. These need to be skipped over as they are pure noise. :param record: :return:
[ "This", "will", "detect", "DDB", "Global", "Table", "updates", "that", "are", "not", "relevant", "to", "application", "data", "updates", ".", "These", "need", "to", "be", "skipped", "over", "as", "they", "are", "pure", "noise", "." ]
c3ebaa8388a3fe67e23a6c9c6b04c3e618497c4a
https://github.com/Netflix-Skunkworks/historical/blob/c3ebaa8388a3fe67e23a6c9c6b04c3e618497c4a/historical/common/proxy.py#L126-L142
4,179
Netflix-Skunkworks/historical
historical/s3/differ.py
handler
def handler(event, context): # pylint: disable=W0613 """ Historical S3 event differ. Listens to the Historical current table and determines if there are differences that need to be persisted in the historical record. """ # De-serialize the records: records = deserialize_records(event['Records']) for record in records: process_dynamodb_differ_record(record, CurrentS3Model, DurableS3Model)
python
def handler(event, context): # pylint: disable=W0613 """ Historical S3 event differ. Listens to the Historical current table and determines if there are differences that need to be persisted in the historical record. """ # De-serialize the records: records = deserialize_records(event['Records']) for record in records: process_dynamodb_differ_record(record, CurrentS3Model, DurableS3Model)
[ "def", "handler", "(", "event", ",", "context", ")", ":", "# pylint: disable=W0613", "# De-serialize the records:", "records", "=", "deserialize_records", "(", "event", "[", "'Records'", "]", ")", "for", "record", "in", "records", ":", "process_dynamodb_differ_record", "(", "record", ",", "CurrentS3Model", ",", "DurableS3Model", ")" ]
Historical S3 event differ. Listens to the Historical current table and determines if there are differences that need to be persisted in the historical record.
[ "Historical", "S3", "event", "differ", "." ]
c3ebaa8388a3fe67e23a6c9c6b04c3e618497c4a
https://github.com/Netflix-Skunkworks/historical/blob/c3ebaa8388a3fe67e23a6c9c6b04c3e618497c4a/historical/s3/differ.py#L26-L37
4,180
Netflix-Skunkworks/historical
historical/cli.py
new
def new(): """Creates a new historical technology.""" dir_path = os.path.dirname(os.path.realpath(__file__)) cookiecutter(os.path.join(dir_path, 'historical-cookiecutter/'))
python
def new(): """Creates a new historical technology.""" dir_path = os.path.dirname(os.path.realpath(__file__)) cookiecutter(os.path.join(dir_path, 'historical-cookiecutter/'))
[ "def", "new", "(", ")", ":", "dir_path", "=", "os", ".", "path", ".", "dirname", "(", "os", ".", "path", ".", "realpath", "(", "__file__", ")", ")", "cookiecutter", "(", "os", ".", "path", ".", "join", "(", "dir_path", ",", "'historical-cookiecutter/'", ")", ")" ]
Creates a new historical technology.
[ "Creates", "a", "new", "historical", "technology", "." ]
c3ebaa8388a3fe67e23a6c9c6b04c3e618497c4a
https://github.com/Netflix-Skunkworks/historical/blob/c3ebaa8388a3fe67e23a6c9c6b04c3e618497c4a/historical/cli.py#L30-L33
4,181
Netflix-Skunkworks/historical
historical/vpc/poller.py
poller_tasker_handler
def poller_tasker_handler(event, context): # pylint: disable=W0613 """ Historical VPC Poller Tasker. The Poller is run at a set interval in order to ensure that changes do not go undetected by Historical. Historical pollers generate `polling events` which simulate changes. These polling events contain configuration data such as the account/region defining where the collector should attempt to gather data from. This is the entry point. This will task subsequent Poller lambdas to list all of a given resource in a select few AWS accounts. """ LOG.debug('[@] Running Poller Tasker...') queue_url = get_queue_url(os.environ.get('POLLER_TASKER_QUEUE_NAME', 'HistoricalVPCPollerTasker')) poller_task_schema = HistoricalPollerTaskEventModel() events = [] for account in get_historical_accounts(): for region in POLL_REGIONS: events.append(poller_task_schema.serialize_me(account['id'], region)) try: produce_events(events, queue_url, randomize_delay=RANDOMIZE_POLLER) except ClientError as exc: LOG.error(f'[X] Unable to generate poller tasker events! Reason: {exc}') LOG.debug('[@] Finished tasking the pollers.')
python
def poller_tasker_handler(event, context): # pylint: disable=W0613 """ Historical VPC Poller Tasker. The Poller is run at a set interval in order to ensure that changes do not go undetected by Historical. Historical pollers generate `polling events` which simulate changes. These polling events contain configuration data such as the account/region defining where the collector should attempt to gather data from. This is the entry point. This will task subsequent Poller lambdas to list all of a given resource in a select few AWS accounts. """ LOG.debug('[@] Running Poller Tasker...') queue_url = get_queue_url(os.environ.get('POLLER_TASKER_QUEUE_NAME', 'HistoricalVPCPollerTasker')) poller_task_schema = HistoricalPollerTaskEventModel() events = [] for account in get_historical_accounts(): for region in POLL_REGIONS: events.append(poller_task_schema.serialize_me(account['id'], region)) try: produce_events(events, queue_url, randomize_delay=RANDOMIZE_POLLER) except ClientError as exc: LOG.error(f'[X] Unable to generate poller tasker events! Reason: {exc}') LOG.debug('[@] Finished tasking the pollers.')
[ "def", "poller_tasker_handler", "(", "event", ",", "context", ")", ":", "# pylint: disable=W0613", "LOG", ".", "debug", "(", "'[@] Running Poller Tasker...'", ")", "queue_url", "=", "get_queue_url", "(", "os", ".", "environ", ".", "get", "(", "'POLLER_TASKER_QUEUE_NAME'", ",", "'HistoricalVPCPollerTasker'", ")", ")", "poller_task_schema", "=", "HistoricalPollerTaskEventModel", "(", ")", "events", "=", "[", "]", "for", "account", "in", "get_historical_accounts", "(", ")", ":", "for", "region", "in", "POLL_REGIONS", ":", "events", ".", "append", "(", "poller_task_schema", ".", "serialize_me", "(", "account", "[", "'id'", "]", ",", "region", ")", ")", "try", ":", "produce_events", "(", "events", ",", "queue_url", ",", "randomize_delay", "=", "RANDOMIZE_POLLER", ")", "except", "ClientError", "as", "exc", ":", "LOG", ".", "error", "(", "f'[X] Unable to generate poller tasker events! Reason: {exc}'", ")", "LOG", ".", "debug", "(", "'[@] Finished tasking the pollers.'", ")" ]
Historical VPC Poller Tasker. The Poller is run at a set interval in order to ensure that changes do not go undetected by Historical. Historical pollers generate `polling events` which simulate changes. These polling events contain configuration data such as the account/region defining where the collector should attempt to gather data from. This is the entry point. This will task subsequent Poller lambdas to list all of a given resource in a select few AWS accounts.
[ "Historical", "VPC", "Poller", "Tasker", "." ]
c3ebaa8388a3fe67e23a6c9c6b04c3e618497c4a
https://github.com/Netflix-Skunkworks/historical/blob/c3ebaa8388a3fe67e23a6c9c6b04c3e618497c4a/historical/vpc/poller.py#L30-L57
4,182
Netflix-Skunkworks/historical
historical/common/sqs.py
chunks
def chunks(event_list, chunk_size): """Yield successive n-sized chunks from the event list.""" for i in range(0, len(event_list), chunk_size): yield event_list[i:i + chunk_size]
python
def chunks(event_list, chunk_size): """Yield successive n-sized chunks from the event list.""" for i in range(0, len(event_list), chunk_size): yield event_list[i:i + chunk_size]
[ "def", "chunks", "(", "event_list", ",", "chunk_size", ")", ":", "for", "i", "in", "range", "(", "0", ",", "len", "(", "event_list", ")", ",", "chunk_size", ")", ":", "yield", "event_list", "[", "i", ":", "i", "+", "chunk_size", "]" ]
Yield successive n-sized chunks from the event list.
[ "Yield", "successive", "n", "-", "sized", "chunks", "from", "the", "event", "list", "." ]
c3ebaa8388a3fe67e23a6c9c6b04c3e618497c4a
https://github.com/Netflix-Skunkworks/historical/blob/c3ebaa8388a3fe67e23a6c9c6b04c3e618497c4a/historical/common/sqs.py#L21-L24
4,183
Netflix-Skunkworks/historical
historical/common/sqs.py
get_queue_url
def get_queue_url(queue_name): """Get the URL of the SQS queue to send events to.""" client = boto3.client("sqs", CURRENT_REGION) queue = client.get_queue_url(QueueName=queue_name) return queue["QueueUrl"]
python
def get_queue_url(queue_name): """Get the URL of the SQS queue to send events to.""" client = boto3.client("sqs", CURRENT_REGION) queue = client.get_queue_url(QueueName=queue_name) return queue["QueueUrl"]
[ "def", "get_queue_url", "(", "queue_name", ")", ":", "client", "=", "boto3", ".", "client", "(", "\"sqs\"", ",", "CURRENT_REGION", ")", "queue", "=", "client", ".", "get_queue_url", "(", "QueueName", "=", "queue_name", ")", "return", "queue", "[", "\"QueueUrl\"", "]" ]
Get the URL of the SQS queue to send events to.
[ "Get", "the", "URL", "of", "the", "SQS", "queue", "to", "send", "events", "to", "." ]
c3ebaa8388a3fe67e23a6c9c6b04c3e618497c4a
https://github.com/Netflix-Skunkworks/historical/blob/c3ebaa8388a3fe67e23a6c9c6b04c3e618497c4a/historical/common/sqs.py#L27-L32
4,184
Netflix-Skunkworks/historical
historical/common/sqs.py
produce_events
def produce_events(events, queue_url, batch_size=10, randomize_delay=0): """ Efficiently sends events to the SQS event queue. Note: SQS has a max size of 10 items. Please be aware that this can make the messages go past size -- even with shrinking messages! Events can get randomized delays, maximum of 900 seconds. Set that in `randomize_delay` :param events: :param queue_url: :param batch_size: :param randomize_delay: """ client = boto3.client('sqs', region_name=CURRENT_REGION) for chunk in chunks(events, batch_size): records = [make_sqs_record(event, delay_seconds=get_random_delay(randomize_delay)) for event in chunk] client.send_message_batch(Entries=records, QueueUrl=queue_url)
python
def produce_events(events, queue_url, batch_size=10, randomize_delay=0): """ Efficiently sends events to the SQS event queue. Note: SQS has a max size of 10 items. Please be aware that this can make the messages go past size -- even with shrinking messages! Events can get randomized delays, maximum of 900 seconds. Set that in `randomize_delay` :param events: :param queue_url: :param batch_size: :param randomize_delay: """ client = boto3.client('sqs', region_name=CURRENT_REGION) for chunk in chunks(events, batch_size): records = [make_sqs_record(event, delay_seconds=get_random_delay(randomize_delay)) for event in chunk] client.send_message_batch(Entries=records, QueueUrl=queue_url)
[ "def", "produce_events", "(", "events", ",", "queue_url", ",", "batch_size", "=", "10", ",", "randomize_delay", "=", "0", ")", ":", "client", "=", "boto3", ".", "client", "(", "'sqs'", ",", "region_name", "=", "CURRENT_REGION", ")", "for", "chunk", "in", "chunks", "(", "events", ",", "batch_size", ")", ":", "records", "=", "[", "make_sqs_record", "(", "event", ",", "delay_seconds", "=", "get_random_delay", "(", "randomize_delay", ")", ")", "for", "event", "in", "chunk", "]", "client", ".", "send_message_batch", "(", "Entries", "=", "records", ",", "QueueUrl", "=", "queue_url", ")" ]
Efficiently sends events to the SQS event queue. Note: SQS has a max size of 10 items. Please be aware that this can make the messages go past size -- even with shrinking messages! Events can get randomized delays, maximum of 900 seconds. Set that in `randomize_delay` :param events: :param queue_url: :param batch_size: :param randomize_delay:
[ "Efficiently", "sends", "events", "to", "the", "SQS", "event", "queue", "." ]
c3ebaa8388a3fe67e23a6c9c6b04c3e618497c4a
https://github.com/Netflix-Skunkworks/historical/blob/c3ebaa8388a3fe67e23a6c9c6b04c3e618497c4a/historical/common/sqs.py#L55-L73
4,185
Netflix-Skunkworks/historical
historical/security_group/collector.py
describe_group
def describe_group(record, region): """Attempts to describe group ids.""" account_id = record['account'] group_name = cloudwatch.filter_request_parameters('groupName', record) vpc_id = cloudwatch.filter_request_parameters('vpcId', record) group_id = cloudwatch.filter_request_parameters('groupId', record, look_in_response=True) # Did this get collected already by the poller? if cloudwatch.get_collected_details(record): LOG.debug(f"[<--] Received already collected security group data: {record['detail']['collected']}") return [record['detail']['collected']] try: # Always depend on Group ID first: if group_id: # pylint: disable=R1705 return describe_security_groups( account_number=account_id, assume_role=HISTORICAL_ROLE, region=region, GroupIds=[group_id] )['SecurityGroups'] elif vpc_id and group_name: return describe_security_groups( account_number=account_id, assume_role=HISTORICAL_ROLE, region=region, Filters=[ { 'Name': 'group-name', 'Values': [group_name] }, { 'Name': 'vpc-id', 'Values': [vpc_id] } ] )['SecurityGroups'] else: raise Exception('[X] Did not receive Group ID or VPC/Group Name pairs. ' f'We got: ID: {group_id} VPC/Name: {vpc_id}/{group_name}.') except ClientError as exc: if exc.response['Error']['Code'] == 'InvalidGroup.NotFound': return [] raise exc
python
def describe_group(record, region): """Attempts to describe group ids.""" account_id = record['account'] group_name = cloudwatch.filter_request_parameters('groupName', record) vpc_id = cloudwatch.filter_request_parameters('vpcId', record) group_id = cloudwatch.filter_request_parameters('groupId', record, look_in_response=True) # Did this get collected already by the poller? if cloudwatch.get_collected_details(record): LOG.debug(f"[<--] Received already collected security group data: {record['detail']['collected']}") return [record['detail']['collected']] try: # Always depend on Group ID first: if group_id: # pylint: disable=R1705 return describe_security_groups( account_number=account_id, assume_role=HISTORICAL_ROLE, region=region, GroupIds=[group_id] )['SecurityGroups'] elif vpc_id and group_name: return describe_security_groups( account_number=account_id, assume_role=HISTORICAL_ROLE, region=region, Filters=[ { 'Name': 'group-name', 'Values': [group_name] }, { 'Name': 'vpc-id', 'Values': [vpc_id] } ] )['SecurityGroups'] else: raise Exception('[X] Did not receive Group ID or VPC/Group Name pairs. ' f'We got: ID: {group_id} VPC/Name: {vpc_id}/{group_name}.') except ClientError as exc: if exc.response['Error']['Code'] == 'InvalidGroup.NotFound': return [] raise exc
[ "def", "describe_group", "(", "record", ",", "region", ")", ":", "account_id", "=", "record", "[", "'account'", "]", "group_name", "=", "cloudwatch", ".", "filter_request_parameters", "(", "'groupName'", ",", "record", ")", "vpc_id", "=", "cloudwatch", ".", "filter_request_parameters", "(", "'vpcId'", ",", "record", ")", "group_id", "=", "cloudwatch", ".", "filter_request_parameters", "(", "'groupId'", ",", "record", ",", "look_in_response", "=", "True", ")", "# Did this get collected already by the poller?", "if", "cloudwatch", ".", "get_collected_details", "(", "record", ")", ":", "LOG", ".", "debug", "(", "f\"[<--] Received already collected security group data: {record['detail']['collected']}\"", ")", "return", "[", "record", "[", "'detail'", "]", "[", "'collected'", "]", "]", "try", ":", "# Always depend on Group ID first:", "if", "group_id", ":", "# pylint: disable=R1705", "return", "describe_security_groups", "(", "account_number", "=", "account_id", ",", "assume_role", "=", "HISTORICAL_ROLE", ",", "region", "=", "region", ",", "GroupIds", "=", "[", "group_id", "]", ")", "[", "'SecurityGroups'", "]", "elif", "vpc_id", "and", "group_name", ":", "return", "describe_security_groups", "(", "account_number", "=", "account_id", ",", "assume_role", "=", "HISTORICAL_ROLE", ",", "region", "=", "region", ",", "Filters", "=", "[", "{", "'Name'", ":", "'group-name'", ",", "'Values'", ":", "[", "group_name", "]", "}", ",", "{", "'Name'", ":", "'vpc-id'", ",", "'Values'", ":", "[", "vpc_id", "]", "}", "]", ")", "[", "'SecurityGroups'", "]", "else", ":", "raise", "Exception", "(", "'[X] Did not receive Group ID or VPC/Group Name pairs. '", "f'We got: ID: {group_id} VPC/Name: {vpc_id}/{group_name}.'", ")", "except", "ClientError", "as", "exc", ":", "if", "exc", ".", "response", "[", "'Error'", "]", "[", "'Code'", "]", "==", "'InvalidGroup.NotFound'", ":", "return", "[", "]", "raise", "exc" ]
Attempts to describe group ids.
[ "Attempts", "to", "describe", "group", "ids", "." ]
c3ebaa8388a3fe67e23a6c9c6b04c3e618497c4a
https://github.com/Netflix-Skunkworks/historical/blob/c3ebaa8388a3fe67e23a6c9c6b04c3e618497c4a/historical/security_group/collector.py#L47-L92
4,186
Netflix-Skunkworks/historical
historical/security_group/collector.py
create_delete_model
def create_delete_model(record): """Create a security group model from a record.""" data = cloudwatch.get_historical_base_info(record) group_id = cloudwatch.filter_request_parameters('groupId', record) # vpc_id = cloudwatch.filter_request_parameters('vpcId', record) # group_name = cloudwatch.filter_request_parameters('groupName', record) arn = get_arn(group_id, cloudwatch.get_region(record), record['account']) LOG.debug(f'[-] Deleting Dynamodb Records. Hash Key: {arn}') # Tombstone these records so that the deletion event time can be accurately tracked. data.update({'configuration': {}}) items = list(CurrentSecurityGroupModel.query(arn, limit=1)) if items: model_dict = items[0].__dict__['attribute_values'].copy() model_dict.update(data) model = CurrentSecurityGroupModel(**model_dict) model.save() return model return None
python
def create_delete_model(record): """Create a security group model from a record.""" data = cloudwatch.get_historical_base_info(record) group_id = cloudwatch.filter_request_parameters('groupId', record) # vpc_id = cloudwatch.filter_request_parameters('vpcId', record) # group_name = cloudwatch.filter_request_parameters('groupName', record) arn = get_arn(group_id, cloudwatch.get_region(record), record['account']) LOG.debug(f'[-] Deleting Dynamodb Records. Hash Key: {arn}') # Tombstone these records so that the deletion event time can be accurately tracked. data.update({'configuration': {}}) items = list(CurrentSecurityGroupModel.query(arn, limit=1)) if items: model_dict = items[0].__dict__['attribute_values'].copy() model_dict.update(data) model = CurrentSecurityGroupModel(**model_dict) model.save() return model return None
[ "def", "create_delete_model", "(", "record", ")", ":", "data", "=", "cloudwatch", ".", "get_historical_base_info", "(", "record", ")", "group_id", "=", "cloudwatch", ".", "filter_request_parameters", "(", "'groupId'", ",", "record", ")", "# vpc_id = cloudwatch.filter_request_parameters('vpcId', record)", "# group_name = cloudwatch.filter_request_parameters('groupName', record)", "arn", "=", "get_arn", "(", "group_id", ",", "cloudwatch", ".", "get_region", "(", "record", ")", ",", "record", "[", "'account'", "]", ")", "LOG", ".", "debug", "(", "f'[-] Deleting Dynamodb Records. Hash Key: {arn}'", ")", "# Tombstone these records so that the deletion event time can be accurately tracked.", "data", ".", "update", "(", "{", "'configuration'", ":", "{", "}", "}", ")", "items", "=", "list", "(", "CurrentSecurityGroupModel", ".", "query", "(", "arn", ",", "limit", "=", "1", ")", ")", "if", "items", ":", "model_dict", "=", "items", "[", "0", "]", ".", "__dict__", "[", "'attribute_values'", "]", ".", "copy", "(", ")", "model_dict", ".", "update", "(", "data", ")", "model", "=", "CurrentSecurityGroupModel", "(", "*", "*", "model_dict", ")", "model", ".", "save", "(", ")", "return", "model", "return", "None" ]
Create a security group model from a record.
[ "Create", "a", "security", "group", "model", "from", "a", "record", "." ]
c3ebaa8388a3fe67e23a6c9c6b04c3e618497c4a
https://github.com/Netflix-Skunkworks/historical/blob/c3ebaa8388a3fe67e23a6c9c6b04c3e618497c4a/historical/security_group/collector.py#L95-L119
4,187
Netflix-Skunkworks/historical
historical/constants.py
extract_log_level_from_environment
def extract_log_level_from_environment(k, default): """Gets the log level from the environment variable.""" return LOG_LEVELS.get(os.environ.get(k)) or int(os.environ.get(k, default))
python
def extract_log_level_from_environment(k, default): """Gets the log level from the environment variable.""" return LOG_LEVELS.get(os.environ.get(k)) or int(os.environ.get(k, default))
[ "def", "extract_log_level_from_environment", "(", "k", ",", "default", ")", ":", "return", "LOG_LEVELS", ".", "get", "(", "os", ".", "environ", ".", "get", "(", "k", ")", ")", "or", "int", "(", "os", ".", "environ", ".", "get", "(", "k", ",", "default", ")", ")" ]
Gets the log level from the environment variable.
[ "Gets", "the", "log", "level", "from", "the", "environment", "variable", "." ]
c3ebaa8388a3fe67e23a6c9c6b04c3e618497c4a
https://github.com/Netflix-Skunkworks/historical/blob/c3ebaa8388a3fe67e23a6c9c6b04c3e618497c4a/historical/constants.py#L21-L23
4,188
Netflix-Skunkworks/historical
historical/common/cloudwatch.py
filter_request_parameters
def filter_request_parameters(field_name, msg, look_in_response=False): """ From an event, extract the field name from the message. Different API calls put this information in different places, so check a few places. """ val = msg['detail'].get(field_name, None) try: if not val: val = msg['detail'].get('requestParameters', {}).get(field_name, None) # If we STILL didn't find it -- check if it's in the response element (default off) if not val and look_in_response: if msg['detail'].get('responseElements'): val = msg['detail']['responseElements'].get(field_name, None) # Just in case... We didn't find the value, so just make it None: except AttributeError: val = None return val
python
def filter_request_parameters(field_name, msg, look_in_response=False): """ From an event, extract the field name from the message. Different API calls put this information in different places, so check a few places. """ val = msg['detail'].get(field_name, None) try: if not val: val = msg['detail'].get('requestParameters', {}).get(field_name, None) # If we STILL didn't find it -- check if it's in the response element (default off) if not val and look_in_response: if msg['detail'].get('responseElements'): val = msg['detail']['responseElements'].get(field_name, None) # Just in case... We didn't find the value, so just make it None: except AttributeError: val = None return val
[ "def", "filter_request_parameters", "(", "field_name", ",", "msg", ",", "look_in_response", "=", "False", ")", ":", "val", "=", "msg", "[", "'detail'", "]", ".", "get", "(", "field_name", ",", "None", ")", "try", ":", "if", "not", "val", ":", "val", "=", "msg", "[", "'detail'", "]", ".", "get", "(", "'requestParameters'", ",", "{", "}", ")", ".", "get", "(", "field_name", ",", "None", ")", "# If we STILL didn't find it -- check if it's in the response element (default off)", "if", "not", "val", "and", "look_in_response", ":", "if", "msg", "[", "'detail'", "]", ".", "get", "(", "'responseElements'", ")", ":", "val", "=", "msg", "[", "'detail'", "]", "[", "'responseElements'", "]", ".", "get", "(", "field_name", ",", "None", ")", "# Just in case... We didn't find the value, so just make it None:", "except", "AttributeError", ":", "val", "=", "None", "return", "val" ]
From an event, extract the field name from the message. Different API calls put this information in different places, so check a few places.
[ "From", "an", "event", "extract", "the", "field", "name", "from", "the", "message", ".", "Different", "API", "calls", "put", "this", "information", "in", "different", "places", "so", "check", "a", "few", "places", "." ]
c3ebaa8388a3fe67e23a6c9c6b04c3e618497c4a
https://github.com/Netflix-Skunkworks/historical/blob/c3ebaa8388a3fe67e23a6c9c6b04c3e618497c4a/historical/common/cloudwatch.py#L14-L33
4,189
Netflix-Skunkworks/historical
historical/common/cloudwatch.py
get_historical_base_info
def get_historical_base_info(event): """Gets the base details from the CloudWatch Event.""" data = { 'principalId': get_principal(event), 'userIdentity': get_user_identity(event), 'accountId': event['account'], 'userAgent': event['detail'].get('userAgent'), 'sourceIpAddress': event['detail'].get('sourceIPAddress'), 'requestParameters': event['detail'].get('requestParameters') } if event['detail'].get('eventTime'): data['eventTime'] = event['detail']['eventTime'] if event['detail'].get('eventSource'): data['eventSource'] = event['detail']['eventSource'] if event['detail'].get('eventName'): data['eventName'] = event['detail']['eventName'] return data
python
def get_historical_base_info(event): """Gets the base details from the CloudWatch Event.""" data = { 'principalId': get_principal(event), 'userIdentity': get_user_identity(event), 'accountId': event['account'], 'userAgent': event['detail'].get('userAgent'), 'sourceIpAddress': event['detail'].get('sourceIPAddress'), 'requestParameters': event['detail'].get('requestParameters') } if event['detail'].get('eventTime'): data['eventTime'] = event['detail']['eventTime'] if event['detail'].get('eventSource'): data['eventSource'] = event['detail']['eventSource'] if event['detail'].get('eventName'): data['eventName'] = event['detail']['eventName'] return data
[ "def", "get_historical_base_info", "(", "event", ")", ":", "data", "=", "{", "'principalId'", ":", "get_principal", "(", "event", ")", ",", "'userIdentity'", ":", "get_user_identity", "(", "event", ")", ",", "'accountId'", ":", "event", "[", "'account'", "]", ",", "'userAgent'", ":", "event", "[", "'detail'", "]", ".", "get", "(", "'userAgent'", ")", ",", "'sourceIpAddress'", ":", "event", "[", "'detail'", "]", ".", "get", "(", "'sourceIPAddress'", ")", ",", "'requestParameters'", ":", "event", "[", "'detail'", "]", ".", "get", "(", "'requestParameters'", ")", "}", "if", "event", "[", "'detail'", "]", ".", "get", "(", "'eventTime'", ")", ":", "data", "[", "'eventTime'", "]", "=", "event", "[", "'detail'", "]", "[", "'eventTime'", "]", "if", "event", "[", "'detail'", "]", ".", "get", "(", "'eventSource'", ")", ":", "data", "[", "'eventSource'", "]", "=", "event", "[", "'detail'", "]", "[", "'eventSource'", "]", "if", "event", "[", "'detail'", "]", ".", "get", "(", "'eventName'", ")", ":", "data", "[", "'eventName'", "]", "=", "event", "[", "'detail'", "]", "[", "'eventName'", "]", "return", "data" ]
Gets the base details from the CloudWatch Event.
[ "Gets", "the", "base", "details", "from", "the", "CloudWatch", "Event", "." ]
c3ebaa8388a3fe67e23a6c9c6b04c3e618497c4a
https://github.com/Netflix-Skunkworks/historical/blob/c3ebaa8388a3fe67e23a6c9c6b04c3e618497c4a/historical/common/cloudwatch.py#L67-L87
4,190
desbma/GoogleSpeech
google_speech/__init__.py
Speech.splitText
def splitText(text): """ Split text into sub segments of size not bigger than MAX_SEGMENT_SIZE. """ segments = [] remaining_text = __class__.cleanSpaces(text) while len(remaining_text) > __class__.MAX_SEGMENT_SIZE: cur_text = remaining_text[:__class__.MAX_SEGMENT_SIZE] # try to split at punctuation split_idx = __class__.findLastCharIndexMatching(cur_text, # https://en.wikipedia.org/wiki/Unicode_character_property#General_Category lambda x: unicodedata.category(x) in ("Ps", "Pe", "Pi", "Pf", "Po")) if split_idx is None: # try to split at whitespace split_idx = __class__.findLastCharIndexMatching(cur_text, lambda x: unicodedata.category(x).startswith("Z")) if split_idx is None: # try to split at anything not a letter or number split_idx = __class__.findLastCharIndexMatching(cur_text, lambda x: not (unicodedata.category(x)[0] in ("L", "N"))) if split_idx is None: # split at the last char split_idx = __class__.MAX_SEGMENT_SIZE - 1 new_segment = cur_text[:split_idx + 1].rstrip() segments.append(new_segment) remaining_text = remaining_text[split_idx + 1:].lstrip(string.whitespace + string.punctuation) if remaining_text: segments.append(remaining_text) return segments
python
def splitText(text): """ Split text into sub segments of size not bigger than MAX_SEGMENT_SIZE. """ segments = [] remaining_text = __class__.cleanSpaces(text) while len(remaining_text) > __class__.MAX_SEGMENT_SIZE: cur_text = remaining_text[:__class__.MAX_SEGMENT_SIZE] # try to split at punctuation split_idx = __class__.findLastCharIndexMatching(cur_text, # https://en.wikipedia.org/wiki/Unicode_character_property#General_Category lambda x: unicodedata.category(x) in ("Ps", "Pe", "Pi", "Pf", "Po")) if split_idx is None: # try to split at whitespace split_idx = __class__.findLastCharIndexMatching(cur_text, lambda x: unicodedata.category(x).startswith("Z")) if split_idx is None: # try to split at anything not a letter or number split_idx = __class__.findLastCharIndexMatching(cur_text, lambda x: not (unicodedata.category(x)[0] in ("L", "N"))) if split_idx is None: # split at the last char split_idx = __class__.MAX_SEGMENT_SIZE - 1 new_segment = cur_text[:split_idx + 1].rstrip() segments.append(new_segment) remaining_text = remaining_text[split_idx + 1:].lstrip(string.whitespace + string.punctuation) if remaining_text: segments.append(remaining_text) return segments
[ "def", "splitText", "(", "text", ")", ":", "segments", "=", "[", "]", "remaining_text", "=", "__class__", ".", "cleanSpaces", "(", "text", ")", "while", "len", "(", "remaining_text", ")", ">", "__class__", ".", "MAX_SEGMENT_SIZE", ":", "cur_text", "=", "remaining_text", "[", ":", "__class__", ".", "MAX_SEGMENT_SIZE", "]", "# try to split at punctuation", "split_idx", "=", "__class__", ".", "findLastCharIndexMatching", "(", "cur_text", ",", "# https://en.wikipedia.org/wiki/Unicode_character_property#General_Category", "lambda", "x", ":", "unicodedata", ".", "category", "(", "x", ")", "in", "(", "\"Ps\"", ",", "\"Pe\"", ",", "\"Pi\"", ",", "\"Pf\"", ",", "\"Po\"", ")", ")", "if", "split_idx", "is", "None", ":", "# try to split at whitespace", "split_idx", "=", "__class__", ".", "findLastCharIndexMatching", "(", "cur_text", ",", "lambda", "x", ":", "unicodedata", ".", "category", "(", "x", ")", ".", "startswith", "(", "\"Z\"", ")", ")", "if", "split_idx", "is", "None", ":", "# try to split at anything not a letter or number", "split_idx", "=", "__class__", ".", "findLastCharIndexMatching", "(", "cur_text", ",", "lambda", "x", ":", "not", "(", "unicodedata", ".", "category", "(", "x", ")", "[", "0", "]", "in", "(", "\"L\"", ",", "\"N\"", ")", ")", ")", "if", "split_idx", "is", "None", ":", "# split at the last char", "split_idx", "=", "__class__", ".", "MAX_SEGMENT_SIZE", "-", "1", "new_segment", "=", "cur_text", "[", ":", "split_idx", "+", "1", "]", ".", "rstrip", "(", ")", "segments", ".", "append", "(", "new_segment", ")", "remaining_text", "=", "remaining_text", "[", "split_idx", "+", "1", ":", "]", ".", "lstrip", "(", "string", ".", "whitespace", "+", "string", ".", "punctuation", ")", "if", "remaining_text", ":", "segments", ".", "append", "(", "remaining_text", ")", "return", "segments" ]
Split text into sub segments of size not bigger than MAX_SEGMENT_SIZE.
[ "Split", "text", "into", "sub", "segments", "of", "size", "not", "bigger", "than", "MAX_SEGMENT_SIZE", "." ]
6d3ec62dc26400ccb4f2e77b8ccd4cb416141233
https://github.com/desbma/GoogleSpeech/blob/6d3ec62dc26400ccb4f2e77b8ccd4cb416141233/google_speech/__init__.py#L99-L130
4,191
desbma/GoogleSpeech
google_speech/__init__.py
Speech.play
def play(self, sox_effects=()): """ Play a speech. """ # build the segments preloader_threads = [] if self.text != "-": segments = list(self) # start preloader thread(s) preloader_threads = [PreloaderThread(name="PreloaderThread-%u" % (i)) for i in range(PRELOADER_THREAD_COUNT)] for preloader_thread in preloader_threads: preloader_thread.segments = segments preloader_thread.start() else: segments = iter(self) # play segments for segment in segments: segment.play(sox_effects) if self.text != "-": # destroy preloader threads for preloader_thread in preloader_threads: preloader_thread.join()
python
def play(self, sox_effects=()): """ Play a speech. """ # build the segments preloader_threads = [] if self.text != "-": segments = list(self) # start preloader thread(s) preloader_threads = [PreloaderThread(name="PreloaderThread-%u" % (i)) for i in range(PRELOADER_THREAD_COUNT)] for preloader_thread in preloader_threads: preloader_thread.segments = segments preloader_thread.start() else: segments = iter(self) # play segments for segment in segments: segment.play(sox_effects) if self.text != "-": # destroy preloader threads for preloader_thread in preloader_threads: preloader_thread.join()
[ "def", "play", "(", "self", ",", "sox_effects", "=", "(", ")", ")", ":", "# build the segments", "preloader_threads", "=", "[", "]", "if", "self", ".", "text", "!=", "\"-\"", ":", "segments", "=", "list", "(", "self", ")", "# start preloader thread(s)", "preloader_threads", "=", "[", "PreloaderThread", "(", "name", "=", "\"PreloaderThread-%u\"", "%", "(", "i", ")", ")", "for", "i", "in", "range", "(", "PRELOADER_THREAD_COUNT", ")", "]", "for", "preloader_thread", "in", "preloader_threads", ":", "preloader_thread", ".", "segments", "=", "segments", "preloader_thread", ".", "start", "(", ")", "else", ":", "segments", "=", "iter", "(", "self", ")", "# play segments", "for", "segment", "in", "segments", ":", "segment", ".", "play", "(", "sox_effects", ")", "if", "self", ".", "text", "!=", "\"-\"", ":", "# destroy preloader threads", "for", "preloader_thread", "in", "preloader_threads", ":", "preloader_thread", ".", "join", "(", ")" ]
Play a speech.
[ "Play", "a", "speech", "." ]
6d3ec62dc26400ccb4f2e77b8ccd4cb416141233
https://github.com/desbma/GoogleSpeech/blob/6d3ec62dc26400ccb4f2e77b8ccd4cb416141233/google_speech/__init__.py#L138-L160
4,192
desbma/GoogleSpeech
google_speech/__init__.py
SpeechSegment.isInCache
def isInCache(self): """ Return True if audio data for this segment is present in cache, False otherwise. """ url = self.buildUrl(cache_friendly=True) return url in __class__.cache
python
def isInCache(self): """ Return True if audio data for this segment is present in cache, False otherwise. """ url = self.buildUrl(cache_friendly=True) return url in __class__.cache
[ "def", "isInCache", "(", "self", ")", ":", "url", "=", "self", ".", "buildUrl", "(", "cache_friendly", "=", "True", ")", "return", "url", "in", "__class__", ".", "cache" ]
Return True if audio data for this segment is present in cache, False otherwise.
[ "Return", "True", "if", "audio", "data", "for", "this", "segment", "is", "present", "in", "cache", "False", "otherwise", "." ]
6d3ec62dc26400ccb4f2e77b8ccd4cb416141233
https://github.com/desbma/GoogleSpeech/blob/6d3ec62dc26400ccb4f2e77b8ccd4cb416141233/google_speech/__init__.py#L207-L210
4,193
desbma/GoogleSpeech
google_speech/__init__.py
SpeechSegment.preLoad
def preLoad(self): """ Store audio data in cache for fast playback. """ logging.getLogger().debug("Preloading segment '%s'" % (self)) real_url = self.buildUrl() cache_url = self.buildUrl(cache_friendly=True) audio_data = self.download(real_url) assert(audio_data) __class__.cache[cache_url] = audio_data
python
def preLoad(self): """ Store audio data in cache for fast playback. """ logging.getLogger().debug("Preloading segment '%s'" % (self)) real_url = self.buildUrl() cache_url = self.buildUrl(cache_friendly=True) audio_data = self.download(real_url) assert(audio_data) __class__.cache[cache_url] = audio_data
[ "def", "preLoad", "(", "self", ")", ":", "logging", ".", "getLogger", "(", ")", ".", "debug", "(", "\"Preloading segment '%s'\"", "%", "(", "self", ")", ")", "real_url", "=", "self", ".", "buildUrl", "(", ")", "cache_url", "=", "self", ".", "buildUrl", "(", "cache_friendly", "=", "True", ")", "audio_data", "=", "self", ".", "download", "(", "real_url", ")", "assert", "(", "audio_data", ")", "__class__", ".", "cache", "[", "cache_url", "]", "=", "audio_data" ]
Store audio data in cache for fast playback.
[ "Store", "audio", "data", "in", "cache", "for", "fast", "playback", "." ]
6d3ec62dc26400ccb4f2e77b8ccd4cb416141233
https://github.com/desbma/GoogleSpeech/blob/6d3ec62dc26400ccb4f2e77b8ccd4cb416141233/google_speech/__init__.py#L212-L219
4,194
desbma/GoogleSpeech
google_speech/__init__.py
SpeechSegment.getAudioData
def getAudioData(self): """ Fetch the audio data. """ with self.preload_mutex: cache_url = self.buildUrl(cache_friendly=True) if cache_url in __class__.cache: logging.getLogger().debug("Got data for URL '%s' from cache" % (cache_url)) audio_data = __class__.cache[cache_url] assert(audio_data) else: real_url = self.buildUrl() audio_data = self.download(real_url) assert(audio_data) __class__.cache[cache_url] = audio_data return audio_data
python
def getAudioData(self): """ Fetch the audio data. """ with self.preload_mutex: cache_url = self.buildUrl(cache_friendly=True) if cache_url in __class__.cache: logging.getLogger().debug("Got data for URL '%s' from cache" % (cache_url)) audio_data = __class__.cache[cache_url] assert(audio_data) else: real_url = self.buildUrl() audio_data = self.download(real_url) assert(audio_data) __class__.cache[cache_url] = audio_data return audio_data
[ "def", "getAudioData", "(", "self", ")", ":", "with", "self", ".", "preload_mutex", ":", "cache_url", "=", "self", ".", "buildUrl", "(", "cache_friendly", "=", "True", ")", "if", "cache_url", "in", "__class__", ".", "cache", ":", "logging", ".", "getLogger", "(", ")", ".", "debug", "(", "\"Got data for URL '%s' from cache\"", "%", "(", "cache_url", ")", ")", "audio_data", "=", "__class__", ".", "cache", "[", "cache_url", "]", "assert", "(", "audio_data", ")", "else", ":", "real_url", "=", "self", ".", "buildUrl", "(", ")", "audio_data", "=", "self", ".", "download", "(", "real_url", ")", "assert", "(", "audio_data", ")", "__class__", ".", "cache", "[", "cache_url", "]", "=", "audio_data", "return", "audio_data" ]
Fetch the audio data.
[ "Fetch", "the", "audio", "data", "." ]
6d3ec62dc26400ccb4f2e77b8ccd4cb416141233
https://github.com/desbma/GoogleSpeech/blob/6d3ec62dc26400ccb4f2e77b8ccd4cb416141233/google_speech/__init__.py#L221-L234
4,195
desbma/GoogleSpeech
google_speech/__init__.py
SpeechSegment.play
def play(self, sox_effects=()): """ Play the segment. """ audio_data = self.getAudioData() logging.getLogger().info("Playing speech segment (%s): '%s'" % (self.lang, self)) cmd = ["sox", "-q", "-t", "mp3", "-"] if sys.platform.startswith("win32"): cmd.extend(("-t", "waveaudio")) cmd.extend(("-d", "trim", "0.1", "reverse", "trim", "0.07", "reverse")) # "trim", "0.25", "-0.1" cmd.extend(sox_effects) logging.getLogger().debug("Start player process") p = subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=subprocess.DEVNULL) p.communicate(input=audio_data) if p.returncode != 0: raise RuntimeError() logging.getLogger().debug("Done playing")
python
def play(self, sox_effects=()): """ Play the segment. """ audio_data = self.getAudioData() logging.getLogger().info("Playing speech segment (%s): '%s'" % (self.lang, self)) cmd = ["sox", "-q", "-t", "mp3", "-"] if sys.platform.startswith("win32"): cmd.extend(("-t", "waveaudio")) cmd.extend(("-d", "trim", "0.1", "reverse", "trim", "0.07", "reverse")) # "trim", "0.25", "-0.1" cmd.extend(sox_effects) logging.getLogger().debug("Start player process") p = subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=subprocess.DEVNULL) p.communicate(input=audio_data) if p.returncode != 0: raise RuntimeError() logging.getLogger().debug("Done playing")
[ "def", "play", "(", "self", ",", "sox_effects", "=", "(", ")", ")", ":", "audio_data", "=", "self", ".", "getAudioData", "(", ")", "logging", ".", "getLogger", "(", ")", ".", "info", "(", "\"Playing speech segment (%s): '%s'\"", "%", "(", "self", ".", "lang", ",", "self", ")", ")", "cmd", "=", "[", "\"sox\"", ",", "\"-q\"", ",", "\"-t\"", ",", "\"mp3\"", ",", "\"-\"", "]", "if", "sys", ".", "platform", ".", "startswith", "(", "\"win32\"", ")", ":", "cmd", ".", "extend", "(", "(", "\"-t\"", ",", "\"waveaudio\"", ")", ")", "cmd", ".", "extend", "(", "(", "\"-d\"", ",", "\"trim\"", ",", "\"0.1\"", ",", "\"reverse\"", ",", "\"trim\"", ",", "\"0.07\"", ",", "\"reverse\"", ")", ")", "# \"trim\", \"0.25\", \"-0.1\"", "cmd", ".", "extend", "(", "sox_effects", ")", "logging", ".", "getLogger", "(", ")", ".", "debug", "(", "\"Start player process\"", ")", "p", "=", "subprocess", ".", "Popen", "(", "cmd", ",", "stdin", "=", "subprocess", ".", "PIPE", ",", "stdout", "=", "subprocess", ".", "DEVNULL", ")", "p", ".", "communicate", "(", "input", "=", "audio_data", ")", "if", "p", ".", "returncode", "!=", "0", ":", "raise", "RuntimeError", "(", ")", "logging", ".", "getLogger", "(", ")", ".", "debug", "(", "\"Done playing\"", ")" ]
Play the segment.
[ "Play", "the", "segment", "." ]
6d3ec62dc26400ccb4f2e77b8ccd4cb416141233
https://github.com/desbma/GoogleSpeech/blob/6d3ec62dc26400ccb4f2e77b8ccd4cb416141233/google_speech/__init__.py#L236-L252
4,196
desbma/GoogleSpeech
google_speech/__init__.py
SpeechSegment.buildUrl
def buildUrl(self, cache_friendly=False): """ Construct the URL to get the sound from Goggle API. If cache_friendly is True, remove token from URL to use as a cache key. """ params = collections.OrderedDict() params["client"] = "tw-ob" params["ie"] = "UTF-8" params["idx"] = str(self.segment_num) if self.segment_count is not None: params["total"] = str(self.segment_count) params["textlen"] = str(len(self.text)) params["tl"] = self.lang lower_text = self.text.lower() params["q"] = lower_text return "%s?%s" % (__class__.BASE_URL, urllib.parse.urlencode(params))
python
def buildUrl(self, cache_friendly=False): """ Construct the URL to get the sound from Goggle API. If cache_friendly is True, remove token from URL to use as a cache key. """ params = collections.OrderedDict() params["client"] = "tw-ob" params["ie"] = "UTF-8" params["idx"] = str(self.segment_num) if self.segment_count is not None: params["total"] = str(self.segment_count) params["textlen"] = str(len(self.text)) params["tl"] = self.lang lower_text = self.text.lower() params["q"] = lower_text return "%s?%s" % (__class__.BASE_URL, urllib.parse.urlencode(params))
[ "def", "buildUrl", "(", "self", ",", "cache_friendly", "=", "False", ")", ":", "params", "=", "collections", ".", "OrderedDict", "(", ")", "params", "[", "\"client\"", "]", "=", "\"tw-ob\"", "params", "[", "\"ie\"", "]", "=", "\"UTF-8\"", "params", "[", "\"idx\"", "]", "=", "str", "(", "self", ".", "segment_num", ")", "if", "self", ".", "segment_count", "is", "not", "None", ":", "params", "[", "\"total\"", "]", "=", "str", "(", "self", ".", "segment_count", ")", "params", "[", "\"textlen\"", "]", "=", "str", "(", "len", "(", "self", ".", "text", ")", ")", "params", "[", "\"tl\"", "]", "=", "self", ".", "lang", "lower_text", "=", "self", ".", "text", ".", "lower", "(", ")", "params", "[", "\"q\"", "]", "=", "lower_text", "return", "\"%s?%s\"", "%", "(", "__class__", ".", "BASE_URL", ",", "urllib", ".", "parse", ".", "urlencode", "(", "params", ")", ")" ]
Construct the URL to get the sound from Goggle API. If cache_friendly is True, remove token from URL to use as a cache key.
[ "Construct", "the", "URL", "to", "get", "the", "sound", "from", "Goggle", "API", "." ]
6d3ec62dc26400ccb4f2e77b8ccd4cb416141233
https://github.com/desbma/GoogleSpeech/blob/6d3ec62dc26400ccb4f2e77b8ccd4cb416141233/google_speech/__init__.py#L254-L270
4,197
desbma/GoogleSpeech
google_speech/__init__.py
SpeechSegment.download
def download(self, url): """ Download a sound file. """ logging.getLogger().debug("Downloading '%s'..." % (url)) response = __class__.session.get(url, headers={"User-Agent": "Mozilla/5.0"}, timeout=3.1) response.raise_for_status() return response.content
python
def download(self, url): """ Download a sound file. """ logging.getLogger().debug("Downloading '%s'..." % (url)) response = __class__.session.get(url, headers={"User-Agent": "Mozilla/5.0"}, timeout=3.1) response.raise_for_status() return response.content
[ "def", "download", "(", "self", ",", "url", ")", ":", "logging", ".", "getLogger", "(", ")", ".", "debug", "(", "\"Downloading '%s'...\"", "%", "(", "url", ")", ")", "response", "=", "__class__", ".", "session", ".", "get", "(", "url", ",", "headers", "=", "{", "\"User-Agent\"", ":", "\"Mozilla/5.0\"", "}", ",", "timeout", "=", "3.1", ")", "response", ".", "raise_for_status", "(", ")", "return", "response", ".", "content" ]
Download a sound file.
[ "Download", "a", "sound", "file", "." ]
6d3ec62dc26400ccb4f2e77b8ccd4cb416141233
https://github.com/desbma/GoogleSpeech/blob/6d3ec62dc26400ccb4f2e77b8ccd4cb416141233/google_speech/__init__.py#L272-L279
4,198
gtalarico/airtable-python-wrapper
airtable/params.py
_BaseObjectArrayParam.to_param_dict
def to_param_dict(self): """ Sorts to ensure Order is consistent for Testing """ param_dict = {} for index, dictionary in enumerate(self.value): for key, value in dictionary.items(): param_name = '{param_name}[{index}][{key}]'.format( param_name=self.param_name, index=index, key=key) param_dict[param_name] = value return OrderedDict(sorted(param_dict.items()))
python
def to_param_dict(self): """ Sorts to ensure Order is consistent for Testing """ param_dict = {} for index, dictionary in enumerate(self.value): for key, value in dictionary.items(): param_name = '{param_name}[{index}][{key}]'.format( param_name=self.param_name, index=index, key=key) param_dict[param_name] = value return OrderedDict(sorted(param_dict.items()))
[ "def", "to_param_dict", "(", "self", ")", ":", "param_dict", "=", "{", "}", "for", "index", ",", "dictionary", "in", "enumerate", "(", "self", ".", "value", ")", ":", "for", "key", ",", "value", "in", "dictionary", ".", "items", "(", ")", ":", "param_name", "=", "'{param_name}[{index}][{key}]'", ".", "format", "(", "param_name", "=", "self", ".", "param_name", ",", "index", "=", "index", ",", "key", "=", "key", ")", "param_dict", "[", "param_name", "]", "=", "value", "return", "OrderedDict", "(", "sorted", "(", "param_dict", ".", "items", "(", ")", ")", ")" ]
Sorts to ensure Order is consistent for Testing
[ "Sorts", "to", "ensure", "Order", "is", "consistent", "for", "Testing" ]
48b2d806178085b52a31817571e5a1fc3dce4045
https://github.com/gtalarico/airtable-python-wrapper/blob/48b2d806178085b52a31817571e5a1fc3dce4045/airtable/params.py#L68-L78
4,199
gtalarico/airtable-python-wrapper
airtable/params.py
AirtableParams._get
def _get(cls, kwarg_name): """ Returns a Param Class Instance, by its kwarg or param name """ param_classes = cls._discover_params() try: param_class = param_classes[kwarg_name] except KeyError: raise ValueError('invalid param keyword {}'.format(kwarg_name)) else: return param_class
python
def _get(cls, kwarg_name): """ Returns a Param Class Instance, by its kwarg or param name """ param_classes = cls._discover_params() try: param_class = param_classes[kwarg_name] except KeyError: raise ValueError('invalid param keyword {}'.format(kwarg_name)) else: return param_class
[ "def", "_get", "(", "cls", ",", "kwarg_name", ")", ":", "param_classes", "=", "cls", ".", "_discover_params", "(", ")", "try", ":", "param_class", "=", "param_classes", "[", "kwarg_name", "]", "except", "KeyError", ":", "raise", "ValueError", "(", "'invalid param keyword {}'", ".", "format", "(", "kwarg_name", ")", ")", "else", ":", "return", "param_class" ]
Returns a Param Class Instance, by its kwarg or param name
[ "Returns", "a", "Param", "Class", "Instance", "by", "its", "kwarg", "or", "param", "name" ]
48b2d806178085b52a31817571e5a1fc3dce4045
https://github.com/gtalarico/airtable-python-wrapper/blob/48b2d806178085b52a31817571e5a1fc3dce4045/airtable/params.py#L362-L370