body_hash
stringlengths
64
64
body
stringlengths
23
109k
docstring
stringlengths
1
57k
path
stringlengths
4
198
name
stringlengths
1
115
repository_name
stringlengths
7
111
repository_stars
float64
0
191k
lang
stringclasses
1 value
body_without_docstring
stringlengths
14
108k
unified
stringlengths
45
133k
ab73e6af96394afa7b2751b697917ae65e2d29539afdc3896b6dce468c3a1395
def __init__(self, **kwargs): 'Constructor.\n\n Args:\n **kwargs (dict): The args to pass into GCPRepository.__init__()\n ' super(_ComputeImagesRepository, self).__init__(component='images', entity_field='image', **kwargs)
Constructor. Args: **kwargs (dict): The args to pass into GCPRepository.__init__()
google/cloud/forseti/common/gcp_api/compute.py
__init__
muralidkt/forseti-security
921
python
def __init__(self, **kwargs): 'Constructor.\n\n Args:\n **kwargs (dict): The args to pass into GCPRepository.__init__()\n ' super(_ComputeImagesRepository, self).__init__(component='images', entity_field='image', **kwargs)
def __init__(self, **kwargs): 'Constructor.\n\n Args:\n **kwargs (dict): The args to pass into GCPRepository.__init__()\n ' super(_ComputeImagesRepository, self).__init__(component='images', entity_field='image', **kwargs)<|docstring|>Constructor. Args: **kwargs (dict): The args to pass into GCPRepository.__init__()<|endoftext|>
ccfa55da2dde787d7504350f2946448ab02b8eea2503219903a75da54aba1c33
def __init__(self, **kwargs): 'Constructor.\n\n Args:\n **kwargs (dict): The args to pass into GCPRepository.__init__()\n ' super(_ComputeInstanceGroupManagersRepository, self).__init__(component='instanceGroupManagers', **kwargs)
Constructor. Args: **kwargs (dict): The args to pass into GCPRepository.__init__()
google/cloud/forseti/common/gcp_api/compute.py
__init__
muralidkt/forseti-security
921
python
def __init__(self, **kwargs): 'Constructor.\n\n Args:\n **kwargs (dict): The args to pass into GCPRepository.__init__()\n ' super(_ComputeInstanceGroupManagersRepository, self).__init__(component='instanceGroupManagers', **kwargs)
def __init__(self, **kwargs): 'Constructor.\n\n Args:\n **kwargs (dict): The args to pass into GCPRepository.__init__()\n ' super(_ComputeInstanceGroupManagersRepository, self).__init__(component='instanceGroupManagers', **kwargs)<|docstring|>Constructor. Args: **kwargs (dict): The args to pass into GCPRepository.__init__()<|endoftext|>
f4d5bc3afecfa36dea323a021a5378cec730b70554ac6f366cdcf482c9a066d2
def __init__(self, **kwargs): 'Constructor.\n\n Args:\n **kwargs (dict): The args to pass into GCPRepository.__init__()\n ' super(_ComputeInstanceGroupsRepository, self).__init__(component='instanceGroups', **kwargs)
Constructor. Args: **kwargs (dict): The args to pass into GCPRepository.__init__()
google/cloud/forseti/common/gcp_api/compute.py
__init__
muralidkt/forseti-security
921
python
def __init__(self, **kwargs): 'Constructor.\n\n Args:\n **kwargs (dict): The args to pass into GCPRepository.__init__()\n ' super(_ComputeInstanceGroupsRepository, self).__init__(component='instanceGroups', **kwargs)
def __init__(self, **kwargs): 'Constructor.\n\n Args:\n **kwargs (dict): The args to pass into GCPRepository.__init__()\n ' super(_ComputeInstanceGroupsRepository, self).__init__(component='instanceGroups', **kwargs)<|docstring|>Constructor. Args: **kwargs (dict): The args to pass into GCPRepository.__init__()<|endoftext|>
33e68965073f116d09bc6460bca330c0e36b864ba2f540d84b72ce585561cca3
def list_instances(self, resource, instance_group, zone, **kwargs): 'List instances for instance group.\n\n Args:\n resource (str): The project to query resources for.\n instance_group (str): The name of the instance group to query.\n zone (str): The zone of the instance group to query.\n **kwargs (dict): Additional args to pass through to the base method.\n\n Returns:\n iterator: An iterator over each page of results from the API.\n ' kwargs['instanceGroup'] = instance_group kwargs['zone'] = zone return repository_mixins.ListQueryMixin.list(self, resource, verb='listInstances', **kwargs)
List instances for instance group. Args: resource (str): The project to query resources for. instance_group (str): The name of the instance group to query. zone (str): The zone of the instance group to query. **kwargs (dict): Additional args to pass through to the base method. Returns: iterator: An iterator over each page of results from the API.
google/cloud/forseti/common/gcp_api/compute.py
list_instances
muralidkt/forseti-security
921
python
def list_instances(self, resource, instance_group, zone, **kwargs): 'List instances for instance group.\n\n Args:\n resource (str): The project to query resources for.\n instance_group (str): The name of the instance group to query.\n zone (str): The zone of the instance group to query.\n **kwargs (dict): Additional args to pass through to the base method.\n\n Returns:\n iterator: An iterator over each page of results from the API.\n ' kwargs['instanceGroup'] = instance_group kwargs['zone'] = zone return repository_mixins.ListQueryMixin.list(self, resource, verb='listInstances', **kwargs)
def list_instances(self, resource, instance_group, zone, **kwargs): 'List instances for instance group.\n\n Args:\n resource (str): The project to query resources for.\n instance_group (str): The name of the instance group to query.\n zone (str): The zone of the instance group to query.\n **kwargs (dict): Additional args to pass through to the base method.\n\n Returns:\n iterator: An iterator over each page of results from the API.\n ' kwargs['instanceGroup'] = instance_group kwargs['zone'] = zone return repository_mixins.ListQueryMixin.list(self, resource, verb='listInstances', **kwargs)<|docstring|>List instances for instance group. Args: resource (str): The project to query resources for. instance_group (str): The name of the instance group to query. zone (str): The zone of the instance group to query. **kwargs (dict): Additional args to pass through to the base method. Returns: iterator: An iterator over each page of results from the API.<|endoftext|>
1a11a8ff2f0649b6e467448fefdbbb941f7bb392b4f9c981bb7697db85bb1f96
def __init__(self, **kwargs): 'Constructor.\n\n Args:\n **kwargs (dict): The args to pass into GCPRepository.__init__()\n ' super(_ComputeInstanceTemplatesRepository, self).__init__(component='instanceTemplates', **kwargs)
Constructor. Args: **kwargs (dict): The args to pass into GCPRepository.__init__()
google/cloud/forseti/common/gcp_api/compute.py
__init__
muralidkt/forseti-security
921
python
def __init__(self, **kwargs): 'Constructor.\n\n Args:\n **kwargs (dict): The args to pass into GCPRepository.__init__()\n ' super(_ComputeInstanceTemplatesRepository, self).__init__(component='instanceTemplates', **kwargs)
def __init__(self, **kwargs): 'Constructor.\n\n Args:\n **kwargs (dict): The args to pass into GCPRepository.__init__()\n ' super(_ComputeInstanceTemplatesRepository, self).__init__(component='instanceTemplates', **kwargs)<|docstring|>Constructor. Args: **kwargs (dict): The args to pass into GCPRepository.__init__()<|endoftext|>
90ef57269da5d755164b5108fe6068536f93416085b939124d6fe625424c8a4b
def __init__(self, **kwargs): 'Constructor.\n\n Args:\n **kwargs (dict): The args to pass into GCPRepository.__init__()\n ' super(_ComputeInstancesRepository, self).__init__(component='instances', **kwargs)
Constructor. Args: **kwargs (dict): The args to pass into GCPRepository.__init__()
google/cloud/forseti/common/gcp_api/compute.py
__init__
muralidkt/forseti-security
921
python
def __init__(self, **kwargs): 'Constructor.\n\n Args:\n **kwargs (dict): The args to pass into GCPRepository.__init__()\n ' super(_ComputeInstancesRepository, self).__init__(component='instances', **kwargs)
def __init__(self, **kwargs): 'Constructor.\n\n Args:\n **kwargs (dict): The args to pass into GCPRepository.__init__()\n ' super(_ComputeInstancesRepository, self).__init__(component='instances', **kwargs)<|docstring|>Constructor. Args: **kwargs (dict): The args to pass into GCPRepository.__init__()<|endoftext|>
a67bcb67f803cbf58cc453d72e24c241035df0eb2d26d5271354ce9ba26687e3
def list(self, resource, zone, **kwargs): 'List instances by zone.\n\n Args:\n resource (str): The project to query resources for.\n zone (str): The zone of the instance group to query.\n **kwargs (dict): Additional args to pass through to the base method.\n\n Returns:\n iterator: An iterator over each page of results from the API.\n ' kwargs['zone'] = zone return repository_mixins.ListQueryMixin.list(self, resource, **kwargs)
List instances by zone. Args: resource (str): The project to query resources for. zone (str): The zone of the instance group to query. **kwargs (dict): Additional args to pass through to the base method. Returns: iterator: An iterator over each page of results from the API.
google/cloud/forseti/common/gcp_api/compute.py
list
muralidkt/forseti-security
921
python
def list(self, resource, zone, **kwargs): 'List instances by zone.\n\n Args:\n resource (str): The project to query resources for.\n zone (str): The zone of the instance group to query.\n **kwargs (dict): Additional args to pass through to the base method.\n\n Returns:\n iterator: An iterator over each page of results from the API.\n ' kwargs['zone'] = zone return repository_mixins.ListQueryMixin.list(self, resource, **kwargs)
def list(self, resource, zone, **kwargs): 'List instances by zone.\n\n Args:\n resource (str): The project to query resources for.\n zone (str): The zone of the instance group to query.\n **kwargs (dict): Additional args to pass through to the base method.\n\n Returns:\n iterator: An iterator over each page of results from the API.\n ' kwargs['zone'] = zone return repository_mixins.ListQueryMixin.list(self, resource, **kwargs)<|docstring|>List instances by zone. Args: resource (str): The project to query resources for. zone (str): The zone of the instance group to query. **kwargs (dict): Additional args to pass through to the base method. Returns: iterator: An iterator over each page of results from the API.<|endoftext|>
407c062915b09ee569d8db69f3e39b35a76f78a698120e58a97516011b6257b4
def __init__(self, **kwargs): 'Constructor.\n\n Args:\n **kwargs (dict): The args to pass into GCPRepository.__init__()\n ' super(_ComputeNetworksRepository, self).__init__(component='networks', **kwargs)
Constructor. Args: **kwargs (dict): The args to pass into GCPRepository.__init__()
google/cloud/forseti/common/gcp_api/compute.py
__init__
muralidkt/forseti-security
921
python
def __init__(self, **kwargs): 'Constructor.\n\n Args:\n **kwargs (dict): The args to pass into GCPRepository.__init__()\n ' super(_ComputeNetworksRepository, self).__init__(component='networks', **kwargs)
def __init__(self, **kwargs): 'Constructor.\n\n Args:\n **kwargs (dict): The args to pass into GCPRepository.__init__()\n ' super(_ComputeNetworksRepository, self).__init__(component='networks', **kwargs)<|docstring|>Constructor. Args: **kwargs (dict): The args to pass into GCPRepository.__init__()<|endoftext|>
92fda4de60c7dce22d6ad130e7211bab0d3b56e18b4a6b74824c287c2cfb126b
def __init__(self, **kwargs): 'Constructor.\n\n Args:\n **kwargs (dict): The args to pass into GCPRepository.__init__()\n ' super(_ComputeProjectsRepository, self).__init__(component='projects', **kwargs)
Constructor. Args: **kwargs (dict): The args to pass into GCPRepository.__init__()
google/cloud/forseti/common/gcp_api/compute.py
__init__
muralidkt/forseti-security
921
python
def __init__(self, **kwargs): 'Constructor.\n\n Args:\n **kwargs (dict): The args to pass into GCPRepository.__init__()\n ' super(_ComputeProjectsRepository, self).__init__(component='projects', **kwargs)
def __init__(self, **kwargs): 'Constructor.\n\n Args:\n **kwargs (dict): The args to pass into GCPRepository.__init__()\n ' super(_ComputeProjectsRepository, self).__init__(component='projects', **kwargs)<|docstring|>Constructor. Args: **kwargs (dict): The args to pass into GCPRepository.__init__()<|endoftext|>
e07cc757d5b8a7416306f282403649bdbbe299569a45b39488fde4961be9234e
def __init__(self, **kwargs): 'Constructor.\n\n Args:\n **kwargs (dict): The args to pass into GCPRepository.__init__()\n ' super(_ComputeRegionInstanceGroupsRepository, self).__init__(component='regionInstanceGroups', **kwargs)
Constructor. Args: **kwargs (dict): The args to pass into GCPRepository.__init__()
google/cloud/forseti/common/gcp_api/compute.py
__init__
muralidkt/forseti-security
921
python
def __init__(self, **kwargs): 'Constructor.\n\n Args:\n **kwargs (dict): The args to pass into GCPRepository.__init__()\n ' super(_ComputeRegionInstanceGroupsRepository, self).__init__(component='regionInstanceGroups', **kwargs)
def __init__(self, **kwargs): 'Constructor.\n\n Args:\n **kwargs (dict): The args to pass into GCPRepository.__init__()\n ' super(_ComputeRegionInstanceGroupsRepository, self).__init__(component='regionInstanceGroups', **kwargs)<|docstring|>Constructor. Args: **kwargs (dict): The args to pass into GCPRepository.__init__()<|endoftext|>
0e97b6a7fa230ff8d16c504b7eb55653b92ca3f4ea360a2537ceba16eedf73df
def list_instances(self, resource, instance_group, region, **kwargs): 'List instances for instance group.\n\n Args:\n resource (str): The project to query resources for.\n instance_group (str): The name of the instance group to query.\n region (str): The region of the instance group to query.\n **kwargs (dict): Additional args to pass through to the base method.\n\n Returns:\n iterator: An iterator over each page of results from the API.\n ' kwargs['instanceGroup'] = instance_group kwargs['region'] = region return repository_mixins.ListQueryMixin.list(self, resource, verb='listInstances', **kwargs)
List instances for instance group. Args: resource (str): The project to query resources for. instance_group (str): The name of the instance group to query. region (str): The region of the instance group to query. **kwargs (dict): Additional args to pass through to the base method. Returns: iterator: An iterator over each page of results from the API.
google/cloud/forseti/common/gcp_api/compute.py
list_instances
muralidkt/forseti-security
921
python
def list_instances(self, resource, instance_group, region, **kwargs): 'List instances for instance group.\n\n Args:\n resource (str): The project to query resources for.\n instance_group (str): The name of the instance group to query.\n region (str): The region of the instance group to query.\n **kwargs (dict): Additional args to pass through to the base method.\n\n Returns:\n iterator: An iterator over each page of results from the API.\n ' kwargs['instanceGroup'] = instance_group kwargs['region'] = region return repository_mixins.ListQueryMixin.list(self, resource, verb='listInstances', **kwargs)
def list_instances(self, resource, instance_group, region, **kwargs): 'List instances for instance group.\n\n Args:\n resource (str): The project to query resources for.\n instance_group (str): The name of the instance group to query.\n region (str): The region of the instance group to query.\n **kwargs (dict): Additional args to pass through to the base method.\n\n Returns:\n iterator: An iterator over each page of results from the API.\n ' kwargs['instanceGroup'] = instance_group kwargs['region'] = region return repository_mixins.ListQueryMixin.list(self, resource, verb='listInstances', **kwargs)<|docstring|>List instances for instance group. Args: resource (str): The project to query resources for. instance_group (str): The name of the instance group to query. region (str): The region of the instance group to query. **kwargs (dict): Additional args to pass through to the base method. Returns: iterator: An iterator over each page of results from the API.<|endoftext|>
de3867d8b53ae989a6e8f18b748385fb431ade72cc9f8b9d524f9e38f6c2197a
def __init__(self, **kwargs): 'Constructor.\n\n Args:\n **kwargs (dict): The args to pass into GCPRepository.__init__()\n ' super(_ComputeSnapshotsRepository, self).__init__(component='snapshots', **kwargs)
Constructor. Args: **kwargs (dict): The args to pass into GCPRepository.__init__()
google/cloud/forseti/common/gcp_api/compute.py
__init__
muralidkt/forseti-security
921
python
def __init__(self, **kwargs): 'Constructor.\n\n Args:\n **kwargs (dict): The args to pass into GCPRepository.__init__()\n ' super(_ComputeSnapshotsRepository, self).__init__(component='snapshots', **kwargs)
def __init__(self, **kwargs): 'Constructor.\n\n Args:\n **kwargs (dict): The args to pass into GCPRepository.__init__()\n ' super(_ComputeSnapshotsRepository, self).__init__(component='snapshots', **kwargs)<|docstring|>Constructor. Args: **kwargs (dict): The args to pass into GCPRepository.__init__()<|endoftext|>
f294f399c23a967dc5638ccb1d680be4a0901f535b885fc2666974a66fe51aed
def __init__(self, **kwargs): 'Constructor.\n\n Args:\n **kwargs (dict): The args to pass into GCPRepository.__init__()\n ' super(_ComputeSubnetworksRepository, self).__init__(component='subnetworks', **kwargs)
Constructor. Args: **kwargs (dict): The args to pass into GCPRepository.__init__()
google/cloud/forseti/common/gcp_api/compute.py
__init__
muralidkt/forseti-security
921
python
def __init__(self, **kwargs): 'Constructor.\n\n Args:\n **kwargs (dict): The args to pass into GCPRepository.__init__()\n ' super(_ComputeSubnetworksRepository, self).__init__(component='subnetworks', **kwargs)
def __init__(self, **kwargs): 'Constructor.\n\n Args:\n **kwargs (dict): The args to pass into GCPRepository.__init__()\n ' super(_ComputeSubnetworksRepository, self).__init__(component='subnetworks', **kwargs)<|docstring|>Constructor. Args: **kwargs (dict): The args to pass into GCPRepository.__init__()<|endoftext|>
15cbbd363e3500357b603b74a7f1643912baf276d28270e2d63bece955b01484
def list(self, resource, region, **kwargs): 'List subnetworks by region.\n\n Args:\n resource (str): The project to query resources for.\n region (str): The region of the forwarding rules to query.\n **kwargs (dict): Additional args to pass through to the base method.\n\n Returns:\n iterator: An iterator over each page of results from the API.\n ' kwargs['region'] = region return repository_mixins.ListQueryMixin.list(self, resource, **kwargs)
List subnetworks by region. Args: resource (str): The project to query resources for. region (str): The region of the forwarding rules to query. **kwargs (dict): Additional args to pass through to the base method. Returns: iterator: An iterator over each page of results from the API.
google/cloud/forseti/common/gcp_api/compute.py
list
muralidkt/forseti-security
921
python
def list(self, resource, region, **kwargs): 'List subnetworks by region.\n\n Args:\n resource (str): The project to query resources for.\n region (str): The region of the forwarding rules to query.\n **kwargs (dict): Additional args to pass through to the base method.\n\n Returns:\n iterator: An iterator over each page of results from the API.\n ' kwargs['region'] = region return repository_mixins.ListQueryMixin.list(self, resource, **kwargs)
def list(self, resource, region, **kwargs): 'List subnetworks by region.\n\n Args:\n resource (str): The project to query resources for.\n region (str): The region of the forwarding rules to query.\n **kwargs (dict): Additional args to pass through to the base method.\n\n Returns:\n iterator: An iterator over each page of results from the API.\n ' kwargs['region'] = region return repository_mixins.ListQueryMixin.list(self, resource, **kwargs)<|docstring|>List subnetworks by region. Args: resource (str): The project to query resources for. region (str): The region of the forwarding rules to query. **kwargs (dict): Additional args to pass through to the base method. Returns: iterator: An iterator over each page of results from the API.<|endoftext|>
597b94d1883f38d106ab238ae4565d1ba8f785f17dfd70d997cdf26985de00f1
def __init__(self, global_configs, **kwargs): 'Initialize.\n\n Args:\n global_configs (dict): Forseti config.\n **kwargs (dict): The kwargs.\n ' (max_calls, quota_period) = api_helpers.get_ratelimiter_config(global_configs, API_NAME) read_only = (kwargs.get('read_only', False) or kwargs.get('dry_run', False)) cache_discovery = (global_configs['cache_discovery'] if ('cache_discovery' in global_configs) else False) self.repository = ComputeRepositoryClient(quota_max_calls=max_calls, quota_period=quota_period, read_only=read_only, use_rate_limiter=kwargs.get('use_rate_limiter', True), cache_discovery=cache_discovery, cache=global_configs.get('cache'))
Initialize. Args: global_configs (dict): Forseti config. **kwargs (dict): The kwargs.
google/cloud/forseti/common/gcp_api/compute.py
__init__
muralidkt/forseti-security
921
python
def __init__(self, global_configs, **kwargs): 'Initialize.\n\n Args:\n global_configs (dict): Forseti config.\n **kwargs (dict): The kwargs.\n ' (max_calls, quota_period) = api_helpers.get_ratelimiter_config(global_configs, API_NAME) read_only = (kwargs.get('read_only', False) or kwargs.get('dry_run', False)) cache_discovery = (global_configs['cache_discovery'] if ('cache_discovery' in global_configs) else False) self.repository = ComputeRepositoryClient(quota_max_calls=max_calls, quota_period=quota_period, read_only=read_only, use_rate_limiter=kwargs.get('use_rate_limiter', True), cache_discovery=cache_discovery, cache=global_configs.get('cache'))
def __init__(self, global_configs, **kwargs): 'Initialize.\n\n Args:\n global_configs (dict): Forseti config.\n **kwargs (dict): The kwargs.\n ' (max_calls, quota_period) = api_helpers.get_ratelimiter_config(global_configs, API_NAME) read_only = (kwargs.get('read_only', False) or kwargs.get('dry_run', False)) cache_discovery = (global_configs['cache_discovery'] if ('cache_discovery' in global_configs) else False) self.repository = ComputeRepositoryClient(quota_max_calls=max_calls, quota_period=quota_period, read_only=read_only, use_rate_limiter=kwargs.get('use_rate_limiter', True), cache_discovery=cache_discovery, cache=global_configs.get('cache'))<|docstring|>Initialize. Args: global_configs (dict): Forseti config. **kwargs (dict): The kwargs.<|endoftext|>
28195973de649131dd17bea9bfc3618eb640648bc110dfc2fdd3b1debd76c617
def get_backend_services(self, project_id): 'Get the backend services for a project.\n\n Args:\n project_id (str): The project id.\n\n Returns:\n list: A list of backend services for this project.\n ' paged_results = self.repository.backend_services.aggregated_list(project_id) flattened_results = _flatten_aggregated_list_results(project_id, paged_results, 'backendServices') LOGGER.debug('Getting the backend services of a project, project_id = %s, flattened_results = %s', project_id, flattened_results) return flattened_results
Get the backend services for a project. Args: project_id (str): The project id. Returns: list: A list of backend services for this project.
google/cloud/forseti/common/gcp_api/compute.py
get_backend_services
muralidkt/forseti-security
921
python
def get_backend_services(self, project_id): 'Get the backend services for a project.\n\n Args:\n project_id (str): The project id.\n\n Returns:\n list: A list of backend services for this project.\n ' paged_results = self.repository.backend_services.aggregated_list(project_id) flattened_results = _flatten_aggregated_list_results(project_id, paged_results, 'backendServices') LOGGER.debug('Getting the backend services of a project, project_id = %s, flattened_results = %s', project_id, flattened_results) return flattened_results
def get_backend_services(self, project_id): 'Get the backend services for a project.\n\n Args:\n project_id (str): The project id.\n\n Returns:\n list: A list of backend services for this project.\n ' paged_results = self.repository.backend_services.aggregated_list(project_id) flattened_results = _flatten_aggregated_list_results(project_id, paged_results, 'backendServices') LOGGER.debug('Getting the backend services of a project, project_id = %s, flattened_results = %s', project_id, flattened_results) return flattened_results<|docstring|>Get the backend services for a project. Args: project_id (str): The project id. Returns: list: A list of backend services for this project.<|endoftext|>
694ccfd73b74f48d34baf8e6006328d2fe858a1a97183faa76352be08107cd8b
def get_disks(self, project_id, zone=None): 'Return the list of all disks in the project.\n\n Args:\n project_id (str): The project id.\n zone (str): An optional zone to query, if not provided then all\n disks in all zones are returned.\n\n Returns:\n list: A list of disk resources for this project.\n ' repository = self.repository.disks if zone: paged_results = repository.list(project_id, zone) results = _flatten_list_results(project_id, paged_results, 'items') else: paged_results = repository.aggregated_list(project_id) results = _flatten_aggregated_list_results(project_id, paged_results, 'disks') LOGGER.debug('Getting the list of all disks in the project, project_id = %s, zone = %s, results = %s', project_id, zone, results) return results
Return the list of all disks in the project. Args: project_id (str): The project id. zone (str): An optional zone to query, if not provided then all disks in all zones are returned. Returns: list: A list of disk resources for this project.
google/cloud/forseti/common/gcp_api/compute.py
get_disks
muralidkt/forseti-security
921
python
def get_disks(self, project_id, zone=None): 'Return the list of all disks in the project.\n\n Args:\n project_id (str): The project id.\n zone (str): An optional zone to query, if not provided then all\n disks in all zones are returned.\n\n Returns:\n list: A list of disk resources for this project.\n ' repository = self.repository.disks if zone: paged_results = repository.list(project_id, zone) results = _flatten_list_results(project_id, paged_results, 'items') else: paged_results = repository.aggregated_list(project_id) results = _flatten_aggregated_list_results(project_id, paged_results, 'disks') LOGGER.debug('Getting the list of all disks in the project, project_id = %s, zone = %s, results = %s', project_id, zone, results) return results
def get_disks(self, project_id, zone=None): 'Return the list of all disks in the project.\n\n Args:\n project_id (str): The project id.\n zone (str): An optional zone to query, if not provided then all\n disks in all zones are returned.\n\n Returns:\n list: A list of disk resources for this project.\n ' repository = self.repository.disks if zone: paged_results = repository.list(project_id, zone) results = _flatten_list_results(project_id, paged_results, 'items') else: paged_results = repository.aggregated_list(project_id) results = _flatten_aggregated_list_results(project_id, paged_results, 'disks') LOGGER.debug('Getting the list of all disks in the project, project_id = %s, zone = %s, results = %s', project_id, zone, results) return results<|docstring|>Return the list of all disks in the project. Args: project_id (str): The project id. zone (str): An optional zone to query, if not provided then all disks in all zones are returned. Returns: list: A list of disk resources for this project.<|endoftext|>
0ea3ea61ad98447b8e9e9f69e4e04505a2f7712047001baebf857f6e31cd067b
def get_snapshots(self, project_id): 'Return the list of all snapshots in the project.\n\n Args:\n project_id (str): The project id.\n\n Returns:\n list: A list of snapshot resources for this project.\n ' try: LOGGER.debug('Getting the list of all snapshots in project: %s', project_id) repository = self.repository.snapshots results = repository.list(project_id) return api_helpers.flatten_list_results(results, 'items') except (errors.HttpError, HttpLib2Error) as e: (api_not_enabled, details) = _api_not_enabled(e) if api_not_enabled: err = api_errors.ApiNotEnabledError(details, e) else: err = api_errors.ApiExecutionError(project_id, e) LOGGER.warning(err) raise err
Return the list of all snapshots in the project. Args: project_id (str): The project id. Returns: list: A list of snapshot resources for this project.
google/cloud/forseti/common/gcp_api/compute.py
get_snapshots
muralidkt/forseti-security
921
python
def get_snapshots(self, project_id): 'Return the list of all snapshots in the project.\n\n Args:\n project_id (str): The project id.\n\n Returns:\n list: A list of snapshot resources for this project.\n ' try: LOGGER.debug('Getting the list of all snapshots in project: %s', project_id) repository = self.repository.snapshots results = repository.list(project_id) return api_helpers.flatten_list_results(results, 'items') except (errors.HttpError, HttpLib2Error) as e: (api_not_enabled, details) = _api_not_enabled(e) if api_not_enabled: err = api_errors.ApiNotEnabledError(details, e) else: err = api_errors.ApiExecutionError(project_id, e) LOGGER.warning(err) raise err
def get_snapshots(self, project_id): 'Return the list of all snapshots in the project.\n\n Args:\n project_id (str): The project id.\n\n Returns:\n list: A list of snapshot resources for this project.\n ' try: LOGGER.debug('Getting the list of all snapshots in project: %s', project_id) repository = self.repository.snapshots results = repository.list(project_id) return api_helpers.flatten_list_results(results, 'items') except (errors.HttpError, HttpLib2Error) as e: (api_not_enabled, details) = _api_not_enabled(e) if api_not_enabled: err = api_errors.ApiNotEnabledError(details, e) else: err = api_errors.ApiExecutionError(project_id, e) LOGGER.warning(err) raise err<|docstring|>Return the list of all snapshots in the project. Args: project_id (str): The project id. Returns: list: A list of snapshot resources for this project.<|endoftext|>
0a5b6bc0588e2ce2d9745f57f9747b0063d8f4ae9129ee85bb394345fe0a8954
def get_firewall_rules(self, project_id): 'Get the firewall rules for a given project id.\n\n Args:\n project_id (str): The project id.\n\n Returns:\n list: A list of firewall rules for this project id.\n ' paged_results = self.repository.firewalls.list(project_id) flattened_results = _flatten_list_results(project_id, paged_results, 'items') LOGGER.debug('Getting the firewall rules of a given project, project_id = %s, flattened_results = %s', project_id, flattened_results) return flattened_results
Get the firewall rules for a given project id. Args: project_id (str): The project id. Returns: list: A list of firewall rules for this project id.
google/cloud/forseti/common/gcp_api/compute.py
get_firewall_rules
muralidkt/forseti-security
921
python
def get_firewall_rules(self, project_id): 'Get the firewall rules for a given project id.\n\n Args:\n project_id (str): The project id.\n\n Returns:\n list: A list of firewall rules for this project id.\n ' paged_results = self.repository.firewalls.list(project_id) flattened_results = _flatten_list_results(project_id, paged_results, 'items') LOGGER.debug('Getting the firewall rules of a given project, project_id = %s, flattened_results = %s', project_id, flattened_results) return flattened_results
def get_firewall_rules(self, project_id): 'Get the firewall rules for a given project id.\n\n Args:\n project_id (str): The project id.\n\n Returns:\n list: A list of firewall rules for this project id.\n ' paged_results = self.repository.firewalls.list(project_id) flattened_results = _flatten_list_results(project_id, paged_results, 'items') LOGGER.debug('Getting the firewall rules of a given project, project_id = %s, flattened_results = %s', project_id, flattened_results) return flattened_results<|docstring|>Get the firewall rules for a given project id. Args: project_id (str): The project id. Returns: list: A list of firewall rules for this project id.<|endoftext|>
d1a01c54331d8e76835f610534b651d8a373b3a2359c16316c6f25bcdd0776fe
def delete_firewall_rule(self, project_id, rule, uuid=None, blocking=False, retry_count=0, timeout=0): "Delete a firewall rule.\n\n Args:\n project_id (str): The project id.\n rule (dict): The firewall rule dict to delete.\n uuid (str): An optional UUID to identify this request. If the same\n request is resent to the API, it will ignore the additional\n requests. If uuid is not set, one will be generated for the\n request.\n blocking (bool): If true, don't return until the async operation\n completes on the backend or timeout seconds pass.\n retry_count (int): If greater than 0, retry on operation timeout.\n timeout (float): If greater than 0 and blocking is True, then raise an\n exception if timeout seconds pass before the operation completes.\n\n Returns:\n dict: Global Operation status and info.\n https://cloud.google.com/compute/docs/reference/latest/globalOperations/get\n\n Raises:\n OperationTimeoutError: Raised if the operation times out.\n " repository = self.repository.firewalls if (not uuid): uuid = uuid4() try: results = repository.delete(project_id, target=rule['name'], requestId=uuid) if blocking: results = self.wait_for_completion(project_id, results, timeout) except (errors.HttpError, HttpLib2Error) as e: LOGGER.error('Error deleting firewall rule %s: %s', rule['name'], e) (api_not_enabled, details) = _api_not_enabled(e) if api_not_enabled: raise api_errors.ApiNotEnabledError(details, e) raise api_errors.ApiExecutionError(project_id, e) except api_errors.OperationTimeoutError as e: LOGGER.warning('Timeout deleting firewall rule %s: %s', rule['name'], e) if retry_count: retry_count -= 1 return self.delete_firewall_rule(project_id, rule, uuid, blocking, retry_count, timeout) else: raise LOGGER.info('Deleting firewall rule %s on project %s. Rule: %s, Result: %s', rule['name'], project_id, json.dumps(rule, sort_keys=True), results) return results
Delete a firewall rule. Args: project_id (str): The project id. rule (dict): The firewall rule dict to delete. uuid (str): An optional UUID to identify this request. If the same request is resent to the API, it will ignore the additional requests. If uuid is not set, one will be generated for the request. blocking (bool): If true, don't return until the async operation completes on the backend or timeout seconds pass. retry_count (int): If greater than 0, retry on operation timeout. timeout (float): If greater than 0 and blocking is True, then raise an exception if timeout seconds pass before the operation completes. Returns: dict: Global Operation status and info. https://cloud.google.com/compute/docs/reference/latest/globalOperations/get Raises: OperationTimeoutError: Raised if the operation times out.
google/cloud/forseti/common/gcp_api/compute.py
delete_firewall_rule
muralidkt/forseti-security
921
python
def delete_firewall_rule(self, project_id, rule, uuid=None, blocking=False, retry_count=0, timeout=0): "Delete a firewall rule.\n\n Args:\n project_id (str): The project id.\n rule (dict): The firewall rule dict to delete.\n uuid (str): An optional UUID to identify this request. If the same\n request is resent to the API, it will ignore the additional\n requests. If uuid is not set, one will be generated for the\n request.\n blocking (bool): If true, don't return until the async operation\n completes on the backend or timeout seconds pass.\n retry_count (int): If greater than 0, retry on operation timeout.\n timeout (float): If greater than 0 and blocking is True, then raise an\n exception if timeout seconds pass before the operation completes.\n\n Returns:\n dict: Global Operation status and info.\n https://cloud.google.com/compute/docs/reference/latest/globalOperations/get\n\n Raises:\n OperationTimeoutError: Raised if the operation times out.\n " repository = self.repository.firewalls if (not uuid): uuid = uuid4() try: results = repository.delete(project_id, target=rule['name'], requestId=uuid) if blocking: results = self.wait_for_completion(project_id, results, timeout) except (errors.HttpError, HttpLib2Error) as e: LOGGER.error('Error deleting firewall rule %s: %s', rule['name'], e) (api_not_enabled, details) = _api_not_enabled(e) if api_not_enabled: raise api_errors.ApiNotEnabledError(details, e) raise api_errors.ApiExecutionError(project_id, e) except api_errors.OperationTimeoutError as e: LOGGER.warning('Timeout deleting firewall rule %s: %s', rule['name'], e) if retry_count: retry_count -= 1 return self.delete_firewall_rule(project_id, rule, uuid, blocking, retry_count, timeout) else: raise LOGGER.info('Deleting firewall rule %s on project %s. Rule: %s, Result: %s', rule['name'], project_id, json.dumps(rule, sort_keys=True), results) return results
def delete_firewall_rule(self, project_id, rule, uuid=None, blocking=False, retry_count=0, timeout=0): "Delete a firewall rule.\n\n Args:\n project_id (str): The project id.\n rule (dict): The firewall rule dict to delete.\n uuid (str): An optional UUID to identify this request. If the same\n request is resent to the API, it will ignore the additional\n requests. If uuid is not set, one will be generated for the\n request.\n blocking (bool): If true, don't return until the async operation\n completes on the backend or timeout seconds pass.\n retry_count (int): If greater than 0, retry on operation timeout.\n timeout (float): If greater than 0 and blocking is True, then raise an\n exception if timeout seconds pass before the operation completes.\n\n Returns:\n dict: Global Operation status and info.\n https://cloud.google.com/compute/docs/reference/latest/globalOperations/get\n\n Raises:\n OperationTimeoutError: Raised if the operation times out.\n " repository = self.repository.firewalls if (not uuid): uuid = uuid4() try: results = repository.delete(project_id, target=rule['name'], requestId=uuid) if blocking: results = self.wait_for_completion(project_id, results, timeout) except (errors.HttpError, HttpLib2Error) as e: LOGGER.error('Error deleting firewall rule %s: %s', rule['name'], e) (api_not_enabled, details) = _api_not_enabled(e) if api_not_enabled: raise api_errors.ApiNotEnabledError(details, e) raise api_errors.ApiExecutionError(project_id, e) except api_errors.OperationTimeoutError as e: LOGGER.warning('Timeout deleting firewall rule %s: %s', rule['name'], e) if retry_count: retry_count -= 1 return self.delete_firewall_rule(project_id, rule, uuid, blocking, retry_count, timeout) else: raise LOGGER.info('Deleting firewall rule %s on project %s. Rule: %s, Result: %s', rule['name'], project_id, json.dumps(rule, sort_keys=True), results) return results<|docstring|>Delete a firewall rule. Args: project_id (str): The project id. rule (dict): The firewall rule dict to delete. uuid (str): An optional UUID to identify this request. If the same request is resent to the API, it will ignore the additional requests. If uuid is not set, one will be generated for the request. blocking (bool): If true, don't return until the async operation completes on the backend or timeout seconds pass. retry_count (int): If greater than 0, retry on operation timeout. timeout (float): If greater than 0 and blocking is True, then raise an exception if timeout seconds pass before the operation completes. Returns: dict: Global Operation status and info. https://cloud.google.com/compute/docs/reference/latest/globalOperations/get Raises: OperationTimeoutError: Raised if the operation times out.<|endoftext|>
61dfe2051cc8dda82ad559973c247157f89836943d60863d181928ea71adba13
def insert_firewall_rule(self, project_id, rule, uuid=None, blocking=False, retry_count=0, timeout=0): "Insert a firewall rule.\n\n Args:\n project_id (str): The project id.\n rule (dict): The firewall rule dict to insert.\n uuid (str): An optional UUID to identify this request. If the same\n request is resent to the API, it will ignore the additional\n requests. If uuid is not set, one will be generated for the\n request.\n blocking (bool): If true, don't return until the async operation\n completes on the backend or timeout seconds pass.\n retry_count (int): If greater than 0, retry on operation timeout.\n timeout (float): If greater than 0 and blocking is True, then raise an\n exception if timeout seconds pass before the operation completes.\n\n Returns:\n dict: Global Operation status and info.\n https://cloud.google.com/compute/docs/reference/latest/globalOperations/get\n\n Raises:\n OperationTimeoutError: Raised if the operation times out.\n " repository = self.repository.firewalls if (not uuid): uuid = uuid4() try: results = repository.insert(project_id, data=rule, requestId=uuid) if blocking: results = self.wait_for_completion(project_id, results, timeout) except (errors.HttpError, HttpLib2Error) as e: LOGGER.error('Error inserting firewall rule %s: %s', rule['name'], e) (api_not_enabled, details) = _api_not_enabled(e) if api_not_enabled: raise api_errors.ApiNotEnabledError(details, e) raise api_errors.ApiExecutionError(project_id, e) except api_errors.OperationTimeoutError as e: LOGGER.warning('Timeout inserting firewall rule %s: %s', rule['name'], e) if retry_count: retry_count -= 1 return self.insert_firewall_rule(project_id, rule, uuid, blocking, retry_count, timeout) else: raise LOGGER.info('Inserting firewall rule %s on project %s. Rule: %s, Result: %s', rule['name'], project_id, json.dumps(rule, sort_keys=True), results) return results
Insert a firewall rule. Args: project_id (str): The project id. rule (dict): The firewall rule dict to insert. uuid (str): An optional UUID to identify this request. If the same request is resent to the API, it will ignore the additional requests. If uuid is not set, one will be generated for the request. blocking (bool): If true, don't return until the async operation completes on the backend or timeout seconds pass. retry_count (int): If greater than 0, retry on operation timeout. timeout (float): If greater than 0 and blocking is True, then raise an exception if timeout seconds pass before the operation completes. Returns: dict: Global Operation status and info. https://cloud.google.com/compute/docs/reference/latest/globalOperations/get Raises: OperationTimeoutError: Raised if the operation times out.
google/cloud/forseti/common/gcp_api/compute.py
insert_firewall_rule
muralidkt/forseti-security
921
python
def insert_firewall_rule(self, project_id, rule, uuid=None, blocking=False, retry_count=0, timeout=0): "Insert a firewall rule.\n\n Args:\n project_id (str): The project id.\n rule (dict): The firewall rule dict to insert.\n uuid (str): An optional UUID to identify this request. If the same\n request is resent to the API, it will ignore the additional\n requests. If uuid is not set, one will be generated for the\n request.\n blocking (bool): If true, don't return until the async operation\n completes on the backend or timeout seconds pass.\n retry_count (int): If greater than 0, retry on operation timeout.\n timeout (float): If greater than 0 and blocking is True, then raise an\n exception if timeout seconds pass before the operation completes.\n\n Returns:\n dict: Global Operation status and info.\n https://cloud.google.com/compute/docs/reference/latest/globalOperations/get\n\n Raises:\n OperationTimeoutError: Raised if the operation times out.\n " repository = self.repository.firewalls if (not uuid): uuid = uuid4() try: results = repository.insert(project_id, data=rule, requestId=uuid) if blocking: results = self.wait_for_completion(project_id, results, timeout) except (errors.HttpError, HttpLib2Error) as e: LOGGER.error('Error inserting firewall rule %s: %s', rule['name'], e) (api_not_enabled, details) = _api_not_enabled(e) if api_not_enabled: raise api_errors.ApiNotEnabledError(details, e) raise api_errors.ApiExecutionError(project_id, e) except api_errors.OperationTimeoutError as e: LOGGER.warning('Timeout inserting firewall rule %s: %s', rule['name'], e) if retry_count: retry_count -= 1 return self.insert_firewall_rule(project_id, rule, uuid, blocking, retry_count, timeout) else: raise LOGGER.info('Inserting firewall rule %s on project %s. Rule: %s, Result: %s', rule['name'], project_id, json.dumps(rule, sort_keys=True), results) return results
def insert_firewall_rule(self, project_id, rule, uuid=None, blocking=False, retry_count=0, timeout=0): "Insert a firewall rule.\n\n Args:\n project_id (str): The project id.\n rule (dict): The firewall rule dict to insert.\n uuid (str): An optional UUID to identify this request. If the same\n request is resent to the API, it will ignore the additional\n requests. If uuid is not set, one will be generated for the\n request.\n blocking (bool): If true, don't return until the async operation\n completes on the backend or timeout seconds pass.\n retry_count (int): If greater than 0, retry on operation timeout.\n timeout (float): If greater than 0 and blocking is True, then raise an\n exception if timeout seconds pass before the operation completes.\n\n Returns:\n dict: Global Operation status and info.\n https://cloud.google.com/compute/docs/reference/latest/globalOperations/get\n\n Raises:\n OperationTimeoutError: Raised if the operation times out.\n " repository = self.repository.firewalls if (not uuid): uuid = uuid4() try: results = repository.insert(project_id, data=rule, requestId=uuid) if blocking: results = self.wait_for_completion(project_id, results, timeout) except (errors.HttpError, HttpLib2Error) as e: LOGGER.error('Error inserting firewall rule %s: %s', rule['name'], e) (api_not_enabled, details) = _api_not_enabled(e) if api_not_enabled: raise api_errors.ApiNotEnabledError(details, e) raise api_errors.ApiExecutionError(project_id, e) except api_errors.OperationTimeoutError as e: LOGGER.warning('Timeout inserting firewall rule %s: %s', rule['name'], e) if retry_count: retry_count -= 1 return self.insert_firewall_rule(project_id, rule, uuid, blocking, retry_count, timeout) else: raise LOGGER.info('Inserting firewall rule %s on project %s. Rule: %s, Result: %s', rule['name'], project_id, json.dumps(rule, sort_keys=True), results) return results<|docstring|>Insert a firewall rule. Args: project_id (str): The project id. rule (dict): The firewall rule dict to insert. uuid (str): An optional UUID to identify this request. If the same request is resent to the API, it will ignore the additional requests. If uuid is not set, one will be generated for the request. blocking (bool): If true, don't return until the async operation completes on the backend or timeout seconds pass. retry_count (int): If greater than 0, retry on operation timeout. timeout (float): If greater than 0 and blocking is True, then raise an exception if timeout seconds pass before the operation completes. Returns: dict: Global Operation status and info. https://cloud.google.com/compute/docs/reference/latest/globalOperations/get Raises: OperationTimeoutError: Raised if the operation times out.<|endoftext|>
15872e2b1ac8831d72c3f5c43d391f1b8287ccb38bf51f1228aab9afef8ef404
def patch_firewall_rule(self, project_id, rule, uuid=None, blocking=False, retry_count=0, timeout=0): "Patch a firewall rule.\n\n Args:\n project_id (str): The project id.\n rule (dict): The firewall rule dict to patch, only fields defined in\n the dict will be modified. The 'name' key is a required field and\n must match an existing rule.\n uuid (str): An optional UUID to identify this request. If the same\n request is resent to the API, it will ignore the additional\n requests. If uuid is not set, one will be generated for the\n request.\n blocking (bool): If true, don't return until the async operation\n completes on the backend or timeout seconds pass.\n retry_count (int): If greater than 0, retry on operation timeout.\n timeout (float): If greater than 0 and blocking is True, then raise an\n exception if timeout seconds pass before the operation completes.\n\n Returns:\n dict: Global Operation status and info.\n https://cloud.google.com/compute/docs/reference/latest/globalOperations/get\n\n Raises:\n ApiNotEnabledError: The api is not enabled.\n ApiExecutionError: The api returned an error.\n KeyError: The 'name' key is missing from the rule dict.\n OperationTimeoutError: Raised if the operation times out.\n " repository = self.repository.firewalls if (not uuid): uuid = uuid4() try: results = repository.patch(project_id, target=rule['name'], data=rule, requestId=uuid) if blocking: results = self.wait_for_completion(project_id, results, timeout) except (errors.HttpError, HttpLib2Error) as e: LOGGER.error('Error patching firewall rule %s: %s', rule['name'], e) (api_not_enabled, details) = _api_not_enabled(e) if api_not_enabled: raise api_errors.ApiNotEnabledError(details, e) raise api_errors.ApiExecutionError(project_id, e) except api_errors.OperationTimeoutError as e: LOGGER.warning('Timeout patching firewall rule %s: %s', rule['name'], e) if retry_count: retry_count -= 1 return self.patch_firewall_rule(project_id, rule, uuid, blocking, retry_count, timeout) else: raise LOGGER.info('Patching firewall rule %s on project %s. Rule: %s, Result: %s', rule['name'], project_id, json.dumps(rule, sort_keys=True), results) return results
Patch a firewall rule. Args: project_id (str): The project id. rule (dict): The firewall rule dict to patch, only fields defined in the dict will be modified. The 'name' key is a required field and must match an existing rule. uuid (str): An optional UUID to identify this request. If the same request is resent to the API, it will ignore the additional requests. If uuid is not set, one will be generated for the request. blocking (bool): If true, don't return until the async operation completes on the backend or timeout seconds pass. retry_count (int): If greater than 0, retry on operation timeout. timeout (float): If greater than 0 and blocking is True, then raise an exception if timeout seconds pass before the operation completes. Returns: dict: Global Operation status and info. https://cloud.google.com/compute/docs/reference/latest/globalOperations/get Raises: ApiNotEnabledError: The api is not enabled. ApiExecutionError: The api returned an error. KeyError: The 'name' key is missing from the rule dict. OperationTimeoutError: Raised if the operation times out.
google/cloud/forseti/common/gcp_api/compute.py
patch_firewall_rule
muralidkt/forseti-security
921
python
def patch_firewall_rule(self, project_id, rule, uuid=None, blocking=False, retry_count=0, timeout=0): "Patch a firewall rule.\n\n Args:\n project_id (str): The project id.\n rule (dict): The firewall rule dict to patch, only fields defined in\n the dict will be modified. The 'name' key is a required field and\n must match an existing rule.\n uuid (str): An optional UUID to identify this request. If the same\n request is resent to the API, it will ignore the additional\n requests. If uuid is not set, one will be generated for the\n request.\n blocking (bool): If true, don't return until the async operation\n completes on the backend or timeout seconds pass.\n retry_count (int): If greater than 0, retry on operation timeout.\n timeout (float): If greater than 0 and blocking is True, then raise an\n exception if timeout seconds pass before the operation completes.\n\n Returns:\n dict: Global Operation status and info.\n https://cloud.google.com/compute/docs/reference/latest/globalOperations/get\n\n Raises:\n ApiNotEnabledError: The api is not enabled.\n ApiExecutionError: The api returned an error.\n KeyError: The 'name' key is missing from the rule dict.\n OperationTimeoutError: Raised if the operation times out.\n " repository = self.repository.firewalls if (not uuid): uuid = uuid4() try: results = repository.patch(project_id, target=rule['name'], data=rule, requestId=uuid) if blocking: results = self.wait_for_completion(project_id, results, timeout) except (errors.HttpError, HttpLib2Error) as e: LOGGER.error('Error patching firewall rule %s: %s', rule['name'], e) (api_not_enabled, details) = _api_not_enabled(e) if api_not_enabled: raise api_errors.ApiNotEnabledError(details, e) raise api_errors.ApiExecutionError(project_id, e) except api_errors.OperationTimeoutError as e: LOGGER.warning('Timeout patching firewall rule %s: %s', rule['name'], e) if retry_count: retry_count -= 1 return self.patch_firewall_rule(project_id, rule, uuid, blocking, retry_count, timeout) else: raise LOGGER.info('Patching firewall rule %s on project %s. Rule: %s, Result: %s', rule['name'], project_id, json.dumps(rule, sort_keys=True), results) return results
def patch_firewall_rule(self, project_id, rule, uuid=None, blocking=False, retry_count=0, timeout=0): "Patch a firewall rule.\n\n Args:\n project_id (str): The project id.\n rule (dict): The firewall rule dict to patch, only fields defined in\n the dict will be modified. The 'name' key is a required field and\n must match an existing rule.\n uuid (str): An optional UUID to identify this request. If the same\n request is resent to the API, it will ignore the additional\n requests. If uuid is not set, one will be generated for the\n request.\n blocking (bool): If true, don't return until the async operation\n completes on the backend or timeout seconds pass.\n retry_count (int): If greater than 0, retry on operation timeout.\n timeout (float): If greater than 0 and blocking is True, then raise an\n exception if timeout seconds pass before the operation completes.\n\n Returns:\n dict: Global Operation status and info.\n https://cloud.google.com/compute/docs/reference/latest/globalOperations/get\n\n Raises:\n ApiNotEnabledError: The api is not enabled.\n ApiExecutionError: The api returned an error.\n KeyError: The 'name' key is missing from the rule dict.\n OperationTimeoutError: Raised if the operation times out.\n " repository = self.repository.firewalls if (not uuid): uuid = uuid4() try: results = repository.patch(project_id, target=rule['name'], data=rule, requestId=uuid) if blocking: results = self.wait_for_completion(project_id, results, timeout) except (errors.HttpError, HttpLib2Error) as e: LOGGER.error('Error patching firewall rule %s: %s', rule['name'], e) (api_not_enabled, details) = _api_not_enabled(e) if api_not_enabled: raise api_errors.ApiNotEnabledError(details, e) raise api_errors.ApiExecutionError(project_id, e) except api_errors.OperationTimeoutError as e: LOGGER.warning('Timeout patching firewall rule %s: %s', rule['name'], e) if retry_count: retry_count -= 1 return self.patch_firewall_rule(project_id, rule, uuid, blocking, retry_count, timeout) else: raise LOGGER.info('Patching firewall rule %s on project %s. Rule: %s, Result: %s', rule['name'], project_id, json.dumps(rule, sort_keys=True), results) return results<|docstring|>Patch a firewall rule. Args: project_id (str): The project id. rule (dict): The firewall rule dict to patch, only fields defined in the dict will be modified. The 'name' key is a required field and must match an existing rule. uuid (str): An optional UUID to identify this request. If the same request is resent to the API, it will ignore the additional requests. If uuid is not set, one will be generated for the request. blocking (bool): If true, don't return until the async operation completes on the backend or timeout seconds pass. retry_count (int): If greater than 0, retry on operation timeout. timeout (float): If greater than 0 and blocking is True, then raise an exception if timeout seconds pass before the operation completes. Returns: dict: Global Operation status and info. https://cloud.google.com/compute/docs/reference/latest/globalOperations/get Raises: ApiNotEnabledError: The api is not enabled. ApiExecutionError: The api returned an error. KeyError: The 'name' key is missing from the rule dict. OperationTimeoutError: Raised if the operation times out.<|endoftext|>
31cfd07b177c225b8b111a16470b289432e1438be578fac5247182e7518a8c6d
def update_firewall_rule(self, project_id, rule, uuid=None, blocking=False, retry_count=0, timeout=0): "Update a firewall rule.\n\n *NOTE*: Update only works for INGRESS rules, do not use for EGRESS\n rules. Patch should be used for all rule updates.\n\n Args:\n project_id (str): The project id.\n rule (dict): The firewall rule dict to update. The 'name' key is a\n required field and must match an existing rule.\n uuid (str): An optional UUID to identify this request. If the same\n request is resent to the API, it will ignore the additional\n requests. If uuid is not set, one will be generated for the\n request.\n blocking (bool): If true, don't return until the async operation\n completes on the backend or timeout seconds pass.\n retry_count (int): If greater than 0, retry on operation timeout.\n timeout (float): If greater than 0 and blocking is True, then raise an\n exception if timeout seconds pass before the operation completes.\n\n Returns:\n dict: Global Operation status and info.\n https://cloud.google.com/compute/docs/reference/latest/globalOperations/get\n\n Raises:\n ApiNotEnabledError: The api is not enabled.\n ApiExecutionError: The api returned an error.\n KeyError: The 'name' key is missing from the rule dict.\n OperationTimeoutError: Raised if the operation times out.\n " repository = self.repository.firewalls if (not uuid): uuid = uuid4() try: results = repository.update(project_id, target=rule['name'], data=rule, requestId=uuid) if blocking: results = self.wait_for_completion(project_id, results, timeout) except (errors.HttpError, HttpLib2Error) as e: LOGGER.error('Error updating firewall rule %s: %s', rule['name'], e) (api_not_enabled, details) = _api_not_enabled(e) if api_not_enabled: raise api_errors.ApiNotEnabledError(details, e) raise api_errors.ApiExecutionError(project_id, e) except api_errors.OperationTimeoutError as e: LOGGER.warning('Timeout updating firewall rule %s: %s', rule['name'], e) if retry_count: retry_count -= 1 return self.update_firewall_rule(project_id, rule, uuid, blocking, retry_count, timeout) else: raise LOGGER.info('Updating firewall rule %s on project %s. Rule: %s, Result: %s', rule['name'], project_id, json.dumps(rule, sort_keys=True), results) return results
Update a firewall rule. *NOTE*: Update only works for INGRESS rules, do not use for EGRESS rules. Patch should be used for all rule updates. Args: project_id (str): The project id. rule (dict): The firewall rule dict to update. The 'name' key is a required field and must match an existing rule. uuid (str): An optional UUID to identify this request. If the same request is resent to the API, it will ignore the additional requests. If uuid is not set, one will be generated for the request. blocking (bool): If true, don't return until the async operation completes on the backend or timeout seconds pass. retry_count (int): If greater than 0, retry on operation timeout. timeout (float): If greater than 0 and blocking is True, then raise an exception if timeout seconds pass before the operation completes. Returns: dict: Global Operation status and info. https://cloud.google.com/compute/docs/reference/latest/globalOperations/get Raises: ApiNotEnabledError: The api is not enabled. ApiExecutionError: The api returned an error. KeyError: The 'name' key is missing from the rule dict. OperationTimeoutError: Raised if the operation times out.
google/cloud/forseti/common/gcp_api/compute.py
update_firewall_rule
muralidkt/forseti-security
921
python
def update_firewall_rule(self, project_id, rule, uuid=None, blocking=False, retry_count=0, timeout=0): "Update a firewall rule.\n\n *NOTE*: Update only works for INGRESS rules, do not use for EGRESS\n rules. Patch should be used for all rule updates.\n\n Args:\n project_id (str): The project id.\n rule (dict): The firewall rule dict to update. The 'name' key is a\n required field and must match an existing rule.\n uuid (str): An optional UUID to identify this request. If the same\n request is resent to the API, it will ignore the additional\n requests. If uuid is not set, one will be generated for the\n request.\n blocking (bool): If true, don't return until the async operation\n completes on the backend or timeout seconds pass.\n retry_count (int): If greater than 0, retry on operation timeout.\n timeout (float): If greater than 0 and blocking is True, then raise an\n exception if timeout seconds pass before the operation completes.\n\n Returns:\n dict: Global Operation status and info.\n https://cloud.google.com/compute/docs/reference/latest/globalOperations/get\n\n Raises:\n ApiNotEnabledError: The api is not enabled.\n ApiExecutionError: The api returned an error.\n KeyError: The 'name' key is missing from the rule dict.\n OperationTimeoutError: Raised if the operation times out.\n " repository = self.repository.firewalls if (not uuid): uuid = uuid4() try: results = repository.update(project_id, target=rule['name'], data=rule, requestId=uuid) if blocking: results = self.wait_for_completion(project_id, results, timeout) except (errors.HttpError, HttpLib2Error) as e: LOGGER.error('Error updating firewall rule %s: %s', rule['name'], e) (api_not_enabled, details) = _api_not_enabled(e) if api_not_enabled: raise api_errors.ApiNotEnabledError(details, e) raise api_errors.ApiExecutionError(project_id, e) except api_errors.OperationTimeoutError as e: LOGGER.warning('Timeout updating firewall rule %s: %s', rule['name'], e) if retry_count: retry_count -= 1 return self.update_firewall_rule(project_id, rule, uuid, blocking, retry_count, timeout) else: raise LOGGER.info('Updating firewall rule %s on project %s. Rule: %s, Result: %s', rule['name'], project_id, json.dumps(rule, sort_keys=True), results) return results
def update_firewall_rule(self, project_id, rule, uuid=None, blocking=False, retry_count=0, timeout=0): "Update a firewall rule.\n\n *NOTE*: Update only works for INGRESS rules, do not use for EGRESS\n rules. Patch should be used for all rule updates.\n\n Args:\n project_id (str): The project id.\n rule (dict): The firewall rule dict to update. The 'name' key is a\n required field and must match an existing rule.\n uuid (str): An optional UUID to identify this request. If the same\n request is resent to the API, it will ignore the additional\n requests. If uuid is not set, one will be generated for the\n request.\n blocking (bool): If true, don't return until the async operation\n completes on the backend or timeout seconds pass.\n retry_count (int): If greater than 0, retry on operation timeout.\n timeout (float): If greater than 0 and blocking is True, then raise an\n exception if timeout seconds pass before the operation completes.\n\n Returns:\n dict: Global Operation status and info.\n https://cloud.google.com/compute/docs/reference/latest/globalOperations/get\n\n Raises:\n ApiNotEnabledError: The api is not enabled.\n ApiExecutionError: The api returned an error.\n KeyError: The 'name' key is missing from the rule dict.\n OperationTimeoutError: Raised if the operation times out.\n " repository = self.repository.firewalls if (not uuid): uuid = uuid4() try: results = repository.update(project_id, target=rule['name'], data=rule, requestId=uuid) if blocking: results = self.wait_for_completion(project_id, results, timeout) except (errors.HttpError, HttpLib2Error) as e: LOGGER.error('Error updating firewall rule %s: %s', rule['name'], e) (api_not_enabled, details) = _api_not_enabled(e) if api_not_enabled: raise api_errors.ApiNotEnabledError(details, e) raise api_errors.ApiExecutionError(project_id, e) except api_errors.OperationTimeoutError as e: LOGGER.warning('Timeout updating firewall rule %s: %s', rule['name'], e) if retry_count: retry_count -= 1 return self.update_firewall_rule(project_id, rule, uuid, blocking, retry_count, timeout) else: raise LOGGER.info('Updating firewall rule %s on project %s. Rule: %s, Result: %s', rule['name'], project_id, json.dumps(rule, sort_keys=True), results) return results<|docstring|>Update a firewall rule. *NOTE*: Update only works for INGRESS rules, do not use for EGRESS rules. Patch should be used for all rule updates. Args: project_id (str): The project id. rule (dict): The firewall rule dict to update. The 'name' key is a required field and must match an existing rule. uuid (str): An optional UUID to identify this request. If the same request is resent to the API, it will ignore the additional requests. If uuid is not set, one will be generated for the request. blocking (bool): If true, don't return until the async operation completes on the backend or timeout seconds pass. retry_count (int): If greater than 0, retry on operation timeout. timeout (float): If greater than 0 and blocking is True, then raise an exception if timeout seconds pass before the operation completes. Returns: dict: Global Operation status and info. https://cloud.google.com/compute/docs/reference/latest/globalOperations/get Raises: ApiNotEnabledError: The api is not enabled. ApiExecutionError: The api returned an error. KeyError: The 'name' key is missing from the rule dict. OperationTimeoutError: Raised if the operation times out.<|endoftext|>
d71f802e7b659a02e20f591308f4fdce2d11b9990b05f0d7a9d69f5c9903efa9
def replace_firewall_rule(self, project_id, rule, delete_uuid=None, insert_uuid=None, blocking=True, retry_count=0, timeout=0): "Replace a firewall rule using delete & insert.\n\n Args:\n project_id (str): The project id.\n rule (dict): The firewall rule dict to insert.\n uuid (str): An optional UUID to identify this request. If the same\n request is resent to the API, it will ignore the additional\n requests. If uuid is not set, one will be generated for the request.\n blocking (bool): Required to be true, don't return until the async\n operation completes on the backend or timeout seconds pass.\n retry_count (int): If greater than 0, retry on operation timeout.\n timeout (float): If greater than 0 and blocking is True, then raise an\n exception if timeout seconds pass before the operation completes.\n\n Returns:pyspanner.py:1528\n dict: Global Operation status and info.\n https://cloud.google.com/compute/docs/reference/latest/globalOperations/get\n\n Raises:\n ApiNotEnabledError: The api is not enabled.\n ApiExecutionError: The api returned an error.\n KeyError: The 'name' key is missing from the rule dict.\n OperationTimeoutError: Raised if the operation times out.\n " if (not blocking): raise ValueError('blocking must be true.') repository = self.repository.firewalls if (not delete_uuid): delete_uuid = uuid4() if (not insert_uuid): insert_uuid = uuid4() try: results = repository.delete(project_id, target=rule['name'], requestId=delete_uuid) self.wait_for_completion(project_id, results, timeout) results = repository.insert(project_id, data=rule, requestId=insert_uuid) results = self.wait_for_completion(project_id, results, timeout) except (errors.HttpError, HttpLib2Error) as e: LOGGER.error('Error replacing firewall rule %s: %s', rule['name'], e) (api_not_enabled, details) = _api_not_enabled(e) if api_not_enabled: raise api_errors.ApiNotEnabledError(details, e) raise api_errors.ApiExecutionError(project_id, e) except api_errors.OperationTimeoutError as e: LOGGER.warning('Timeout replacing firewall rule %s: %s', rule['name'], e) if retry_count: retry_count -= 1 return self.replace_firewall_rule(project_id=project_id, rule=rule, insert_uuid=insert_uuid, delete_uuid=delete_uuid, blocking=blocking, retry_count=retry_count, timeout=timeout) else: raise LOGGER.info('Replacing firewall rule %s on project %s. Rule: %s, Result: %s', rule['name'], project_id, json.dumps(rule, sort_keys=True), results) return results
Replace a firewall rule using delete & insert. Args: project_id (str): The project id. rule (dict): The firewall rule dict to insert. uuid (str): An optional UUID to identify this request. If the same request is resent to the API, it will ignore the additional requests. If uuid is not set, one will be generated for the request. blocking (bool): Required to be true, don't return until the async operation completes on the backend or timeout seconds pass. retry_count (int): If greater than 0, retry on operation timeout. timeout (float): If greater than 0 and blocking is True, then raise an exception if timeout seconds pass before the operation completes. Returns:pyspanner.py:1528 dict: Global Operation status and info. https://cloud.google.com/compute/docs/reference/latest/globalOperations/get Raises: ApiNotEnabledError: The api is not enabled. ApiExecutionError: The api returned an error. KeyError: The 'name' key is missing from the rule dict. OperationTimeoutError: Raised if the operation times out.
google/cloud/forseti/common/gcp_api/compute.py
replace_firewall_rule
muralidkt/forseti-security
921
python
def replace_firewall_rule(self, project_id, rule, delete_uuid=None, insert_uuid=None, blocking=True, retry_count=0, timeout=0): "Replace a firewall rule using delete & insert.\n\n Args:\n project_id (str): The project id.\n rule (dict): The firewall rule dict to insert.\n uuid (str): An optional UUID to identify this request. If the same\n request is resent to the API, it will ignore the additional\n requests. If uuid is not set, one will be generated for the request.\n blocking (bool): Required to be true, don't return until the async\n operation completes on the backend or timeout seconds pass.\n retry_count (int): If greater than 0, retry on operation timeout.\n timeout (float): If greater than 0 and blocking is True, then raise an\n exception if timeout seconds pass before the operation completes.\n\n Returns:pyspanner.py:1528\n dict: Global Operation status and info.\n https://cloud.google.com/compute/docs/reference/latest/globalOperations/get\n\n Raises:\n ApiNotEnabledError: The api is not enabled.\n ApiExecutionError: The api returned an error.\n KeyError: The 'name' key is missing from the rule dict.\n OperationTimeoutError: Raised if the operation times out.\n " if (not blocking): raise ValueError('blocking must be true.') repository = self.repository.firewalls if (not delete_uuid): delete_uuid = uuid4() if (not insert_uuid): insert_uuid = uuid4() try: results = repository.delete(project_id, target=rule['name'], requestId=delete_uuid) self.wait_for_completion(project_id, results, timeout) results = repository.insert(project_id, data=rule, requestId=insert_uuid) results = self.wait_for_completion(project_id, results, timeout) except (errors.HttpError, HttpLib2Error) as e: LOGGER.error('Error replacing firewall rule %s: %s', rule['name'], e) (api_not_enabled, details) = _api_not_enabled(e) if api_not_enabled: raise api_errors.ApiNotEnabledError(details, e) raise api_errors.ApiExecutionError(project_id, e) except api_errors.OperationTimeoutError as e: LOGGER.warning('Timeout replacing firewall rule %s: %s', rule['name'], e) if retry_count: retry_count -= 1 return self.replace_firewall_rule(project_id=project_id, rule=rule, insert_uuid=insert_uuid, delete_uuid=delete_uuid, blocking=blocking, retry_count=retry_count, timeout=timeout) else: raise LOGGER.info('Replacing firewall rule %s on project %s. Rule: %s, Result: %s', rule['name'], project_id, json.dumps(rule, sort_keys=True), results) return results
def replace_firewall_rule(self, project_id, rule, delete_uuid=None, insert_uuid=None, blocking=True, retry_count=0, timeout=0): "Replace a firewall rule using delete & insert.\n\n Args:\n project_id (str): The project id.\n rule (dict): The firewall rule dict to insert.\n uuid (str): An optional UUID to identify this request. If the same\n request is resent to the API, it will ignore the additional\n requests. If uuid is not set, one will be generated for the request.\n blocking (bool): Required to be true, don't return until the async\n operation completes on the backend or timeout seconds pass.\n retry_count (int): If greater than 0, retry on operation timeout.\n timeout (float): If greater than 0 and blocking is True, then raise an\n exception if timeout seconds pass before the operation completes.\n\n Returns:pyspanner.py:1528\n dict: Global Operation status and info.\n https://cloud.google.com/compute/docs/reference/latest/globalOperations/get\n\n Raises:\n ApiNotEnabledError: The api is not enabled.\n ApiExecutionError: The api returned an error.\n KeyError: The 'name' key is missing from the rule dict.\n OperationTimeoutError: Raised if the operation times out.\n " if (not blocking): raise ValueError('blocking must be true.') repository = self.repository.firewalls if (not delete_uuid): delete_uuid = uuid4() if (not insert_uuid): insert_uuid = uuid4() try: results = repository.delete(project_id, target=rule['name'], requestId=delete_uuid) self.wait_for_completion(project_id, results, timeout) results = repository.insert(project_id, data=rule, requestId=insert_uuid) results = self.wait_for_completion(project_id, results, timeout) except (errors.HttpError, HttpLib2Error) as e: LOGGER.error('Error replacing firewall rule %s: %s', rule['name'], e) (api_not_enabled, details) = _api_not_enabled(e) if api_not_enabled: raise api_errors.ApiNotEnabledError(details, e) raise api_errors.ApiExecutionError(project_id, e) except api_errors.OperationTimeoutError as e: LOGGER.warning('Timeout replacing firewall rule %s: %s', rule['name'], e) if retry_count: retry_count -= 1 return self.replace_firewall_rule(project_id=project_id, rule=rule, insert_uuid=insert_uuid, delete_uuid=delete_uuid, blocking=blocking, retry_count=retry_count, timeout=timeout) else: raise LOGGER.info('Replacing firewall rule %s on project %s. Rule: %s, Result: %s', rule['name'], project_id, json.dumps(rule, sort_keys=True), results) return results<|docstring|>Replace a firewall rule using delete & insert. Args: project_id (str): The project id. rule (dict): The firewall rule dict to insert. uuid (str): An optional UUID to identify this request. If the same request is resent to the API, it will ignore the additional requests. If uuid is not set, one will be generated for the request. blocking (bool): Required to be true, don't return until the async operation completes on the backend or timeout seconds pass. retry_count (int): If greater than 0, retry on operation timeout. timeout (float): If greater than 0 and blocking is True, then raise an exception if timeout seconds pass before the operation completes. Returns:pyspanner.py:1528 dict: Global Operation status and info. https://cloud.google.com/compute/docs/reference/latest/globalOperations/get Raises: ApiNotEnabledError: The api is not enabled. ApiExecutionError: The api returned an error. KeyError: The 'name' key is missing from the rule dict. OperationTimeoutError: Raised if the operation times out.<|endoftext|>
d795e95d37b82e0d3277891d12a48adf9ebb9a82c8082ab903650d0fe8af9c89
def get_forwarding_rules(self, project_id, region=None): 'Get the forwarding rules for a project.\n\n If no region name is specified, use aggregatedList() to query for\n forwarding rules in all regions.\n\n Args:\n project_id (str): The project id.\n region (str): The region name.\n\n Returns:\n list: A list of forwarding rules for this project.\n ' repository = self.repository.forwarding_rules if region: paged_results = repository.list(project_id, region) results = _flatten_list_results(project_id, paged_results, 'items') else: paged_results = repository.aggregated_list(project_id) results = _flatten_aggregated_list_results(project_id, paged_results, 'forwardingRules') LOGGER.debug('Getting the forwarding rules for a project, project_id = %s, region = %s, results = %s', project_id, region, results) return results
Get the forwarding rules for a project. If no region name is specified, use aggregatedList() to query for forwarding rules in all regions. Args: project_id (str): The project id. region (str): The region name. Returns: list: A list of forwarding rules for this project.
google/cloud/forseti/common/gcp_api/compute.py
get_forwarding_rules
muralidkt/forseti-security
921
python
def get_forwarding_rules(self, project_id, region=None): 'Get the forwarding rules for a project.\n\n If no region name is specified, use aggregatedList() to query for\n forwarding rules in all regions.\n\n Args:\n project_id (str): The project id.\n region (str): The region name.\n\n Returns:\n list: A list of forwarding rules for this project.\n ' repository = self.repository.forwarding_rules if region: paged_results = repository.list(project_id, region) results = _flatten_list_results(project_id, paged_results, 'items') else: paged_results = repository.aggregated_list(project_id) results = _flatten_aggregated_list_results(project_id, paged_results, 'forwardingRules') LOGGER.debug('Getting the forwarding rules for a project, project_id = %s, region = %s, results = %s', project_id, region, results) return results
def get_forwarding_rules(self, project_id, region=None): 'Get the forwarding rules for a project.\n\n If no region name is specified, use aggregatedList() to query for\n forwarding rules in all regions.\n\n Args:\n project_id (str): The project id.\n region (str): The region name.\n\n Returns:\n list: A list of forwarding rules for this project.\n ' repository = self.repository.forwarding_rules if region: paged_results = repository.list(project_id, region) results = _flatten_list_results(project_id, paged_results, 'items') else: paged_results = repository.aggregated_list(project_id) results = _flatten_aggregated_list_results(project_id, paged_results, 'forwardingRules') LOGGER.debug('Getting the forwarding rules for a project, project_id = %s, region = %s, results = %s', project_id, region, results) return results<|docstring|>Get the forwarding rules for a project. If no region name is specified, use aggregatedList() to query for forwarding rules in all regions. Args: project_id (str): The project id. region (str): The region name. Returns: list: A list of forwarding rules for this project.<|endoftext|>
dcd0be5934b8afe7a0a21def0534183989cf464fe29cbfd0daca1a1d7a128498
def get_global_operation(self, project_id, operation_id): 'Get the Operations Status\n Args:\n project_id (str): The project id.\n operation_id (str): The operation id.\n\n Returns:\n dict: Global Operation status and info.\n https://cloud.google.com/compute/docs/reference/latest/globalOperations/get\n\n Raises:\n ApiNotEnabledError: Returns if the api is not enabled.\n ApiExecutionError: Returns if the api is not executable.\n\n ' try: results = self.repository.global_operations.get(project_id, operation_id) LOGGER.debug('Getting the operation status, project_id = %s, operation_id = %s, results = %s', project_id, operation_id, results) return results except (errors.HttpError, HttpLib2Error) as e: (api_not_enabled, details) = _api_not_enabled(e) if api_not_enabled: raise api_errors.ApiNotEnabledError(details, e) raise api_errors.ApiExecutionError(project_id, e)
Get the Operations Status Args: project_id (str): The project id. operation_id (str): The operation id. Returns: dict: Global Operation status and info. https://cloud.google.com/compute/docs/reference/latest/globalOperations/get Raises: ApiNotEnabledError: Returns if the api is not enabled. ApiExecutionError: Returns if the api is not executable.
google/cloud/forseti/common/gcp_api/compute.py
get_global_operation
muralidkt/forseti-security
921
python
def get_global_operation(self, project_id, operation_id): 'Get the Operations Status\n Args:\n project_id (str): The project id.\n operation_id (str): The operation id.\n\n Returns:\n dict: Global Operation status and info.\n https://cloud.google.com/compute/docs/reference/latest/globalOperations/get\n\n Raises:\n ApiNotEnabledError: Returns if the api is not enabled.\n ApiExecutionError: Returns if the api is not executable.\n\n ' try: results = self.repository.global_operations.get(project_id, operation_id) LOGGER.debug('Getting the operation status, project_id = %s, operation_id = %s, results = %s', project_id, operation_id, results) return results except (errors.HttpError, HttpLib2Error) as e: (api_not_enabled, details) = _api_not_enabled(e) if api_not_enabled: raise api_errors.ApiNotEnabledError(details, e) raise api_errors.ApiExecutionError(project_id, e)
def get_global_operation(self, project_id, operation_id): 'Get the Operations Status\n Args:\n project_id (str): The project id.\n operation_id (str): The operation id.\n\n Returns:\n dict: Global Operation status and info.\n https://cloud.google.com/compute/docs/reference/latest/globalOperations/get\n\n Raises:\n ApiNotEnabledError: Returns if the api is not enabled.\n ApiExecutionError: Returns if the api is not executable.\n\n ' try: results = self.repository.global_operations.get(project_id, operation_id) LOGGER.debug('Getting the operation status, project_id = %s, operation_id = %s, results = %s', project_id, operation_id, results) return results except (errors.HttpError, HttpLib2Error) as e: (api_not_enabled, details) = _api_not_enabled(e) if api_not_enabled: raise api_errors.ApiNotEnabledError(details, e) raise api_errors.ApiExecutionError(project_id, e)<|docstring|>Get the Operations Status Args: project_id (str): The project id. operation_id (str): The operation id. Returns: dict: Global Operation status and info. https://cloud.google.com/compute/docs/reference/latest/globalOperations/get Raises: ApiNotEnabledError: Returns if the api is not enabled. ApiExecutionError: Returns if the api is not executable.<|endoftext|>
7829da8a9fee8d21242a836005a74bbf0b8317559081045b341614b316687290
def get_image(self, project_id, image_name): 'Get an image from a project.\n\n Args:\n project_id (str): The project id.\n image_name (str): The image name to get.\n\n Returns:\n dict: A Compute Image resource dict.\n https://cloud.google.com/compute/docs/reference/latest/images\n ' try: results = self.repository.images.get(project_id, target=image_name) LOGGER.debug('Getting an image from a project, project_id = %s, image_name = %s, results = %s', project_id, image_name, results) return results except (errors.HttpError, HttpLib2Error) as e: (api_not_enabled, details) = _api_not_enabled(e) if api_not_enabled: raise api_errors.ApiNotEnabledError(details, e) raise api_errors.ApiExecutionError(project_id, e)
Get an image from a project. Args: project_id (str): The project id. image_name (str): The image name to get. Returns: dict: A Compute Image resource dict. https://cloud.google.com/compute/docs/reference/latest/images
google/cloud/forseti/common/gcp_api/compute.py
get_image
muralidkt/forseti-security
921
python
def get_image(self, project_id, image_name): 'Get an image from a project.\n\n Args:\n project_id (str): The project id.\n image_name (str): The image name to get.\n\n Returns:\n dict: A Compute Image resource dict.\n https://cloud.google.com/compute/docs/reference/latest/images\n ' try: results = self.repository.images.get(project_id, target=image_name) LOGGER.debug('Getting an image from a project, project_id = %s, image_name = %s, results = %s', project_id, image_name, results) return results except (errors.HttpError, HttpLib2Error) as e: (api_not_enabled, details) = _api_not_enabled(e) if api_not_enabled: raise api_errors.ApiNotEnabledError(details, e) raise api_errors.ApiExecutionError(project_id, e)
def get_image(self, project_id, image_name): 'Get an image from a project.\n\n Args:\n project_id (str): The project id.\n image_name (str): The image name to get.\n\n Returns:\n dict: A Compute Image resource dict.\n https://cloud.google.com/compute/docs/reference/latest/images\n ' try: results = self.repository.images.get(project_id, target=image_name) LOGGER.debug('Getting an image from a project, project_id = %s, image_name = %s, results = %s', project_id, image_name, results) return results except (errors.HttpError, HttpLib2Error) as e: (api_not_enabled, details) = _api_not_enabled(e) if api_not_enabled: raise api_errors.ApiNotEnabledError(details, e) raise api_errors.ApiExecutionError(project_id, e)<|docstring|>Get an image from a project. Args: project_id (str): The project id. image_name (str): The image name to get. Returns: dict: A Compute Image resource dict. https://cloud.google.com/compute/docs/reference/latest/images<|endoftext|>
2f42b365ceffd7a6d6c3f28d5fb4f1ebaccc3df1134caf1ed8ca3cfc9fd4d9dc
def get_images(self, project_id): 'Get all images created in a project.\n\n Args:\n project_id (str): The project id.\n\n Returns:\n list: A list of images for this project.\n ' paged_results = self.repository.images.list(project_id) flattened_results = _flatten_list_results(project_id, paged_results, 'items') LOGGER.debug('Getting all images created in a project, project_id = %s, flattened_results = %s', project_id, flattened_results) return flattened_results
Get all images created in a project. Args: project_id (str): The project id. Returns: list: A list of images for this project.
google/cloud/forseti/common/gcp_api/compute.py
get_images
muralidkt/forseti-security
921
python
def get_images(self, project_id): 'Get all images created in a project.\n\n Args:\n project_id (str): The project id.\n\n Returns:\n list: A list of images for this project.\n ' paged_results = self.repository.images.list(project_id) flattened_results = _flatten_list_results(project_id, paged_results, 'items') LOGGER.debug('Getting all images created in a project, project_id = %s, flattened_results = %s', project_id, flattened_results) return flattened_results
def get_images(self, project_id): 'Get all images created in a project.\n\n Args:\n project_id (str): The project id.\n\n Returns:\n list: A list of images for this project.\n ' paged_results = self.repository.images.list(project_id) flattened_results = _flatten_list_results(project_id, paged_results, 'items') LOGGER.debug('Getting all images created in a project, project_id = %s, flattened_results = %s', project_id, flattened_results) return flattened_results<|docstring|>Get all images created in a project. Args: project_id (str): The project id. Returns: list: A list of images for this project.<|endoftext|>
f2ffcdc7e0bf6fa0aa8184a4cb7cb91c973a00120db6d36729bcfb5182782706
def get_instance_group_instances(self, project_id, instance_group_name, region=None, zone=None): "Get the instance groups for a project.\n\n One and only one of zone (for zonal instance groups) and region\n (for regional instance groups) must be specified.\n\n Args:\n project_id (str): The project id.\n instance_group_name (str): The instance group's name.\n region (str): The regional instance group's region.\n zone (str): The zonal instance group's zone.\n\n Returns:\n list: instance URLs for this instance group.\n\n Raises:\n ValueError: invalid combination of parameters\n " if (not (bool(zone) ^ bool(region))): err_message = 'One and only one of zone and region must be specified.' LOGGER.error(err_message) raise ValueError(err_message) if zone: repository = self.repository.instance_groups paged_results = repository.list_instances(project_id, instance_group_name, zone, fields='items/instance,nextPageToken', body={'instanceState': 'ALL'}) else: repository = self.repository.region_instance_groups paged_results = repository.list_instances(project_id, instance_group_name, region, fields='items/instance,nextPageToken', body={'instanceState': 'ALL'}) results = [instance_data.get('instance') for instance_data in _flatten_list_results(project_id, paged_results, 'items') if ('instance' in instance_data)] LOGGER.debug('Getting the instance group for a project, project_id = %s, instance_group_name = %s, region = %s, zone = %s, flattened_results = %s', project_id, instance_group_name, region, zone, results) return results
Get the instance groups for a project. One and only one of zone (for zonal instance groups) and region (for regional instance groups) must be specified. Args: project_id (str): The project id. instance_group_name (str): The instance group's name. region (str): The regional instance group's region. zone (str): The zonal instance group's zone. Returns: list: instance URLs for this instance group. Raises: ValueError: invalid combination of parameters
google/cloud/forseti/common/gcp_api/compute.py
get_instance_group_instances
muralidkt/forseti-security
921
python
def get_instance_group_instances(self, project_id, instance_group_name, region=None, zone=None): "Get the instance groups for a project.\n\n One and only one of zone (for zonal instance groups) and region\n (for regional instance groups) must be specified.\n\n Args:\n project_id (str): The project id.\n instance_group_name (str): The instance group's name.\n region (str): The regional instance group's region.\n zone (str): The zonal instance group's zone.\n\n Returns:\n list: instance URLs for this instance group.\n\n Raises:\n ValueError: invalid combination of parameters\n " if (not (bool(zone) ^ bool(region))): err_message = 'One and only one of zone and region must be specified.' LOGGER.error(err_message) raise ValueError(err_message) if zone: repository = self.repository.instance_groups paged_results = repository.list_instances(project_id, instance_group_name, zone, fields='items/instance,nextPageToken', body={'instanceState': 'ALL'}) else: repository = self.repository.region_instance_groups paged_results = repository.list_instances(project_id, instance_group_name, region, fields='items/instance,nextPageToken', body={'instanceState': 'ALL'}) results = [instance_data.get('instance') for instance_data in _flatten_list_results(project_id, paged_results, 'items') if ('instance' in instance_data)] LOGGER.debug('Getting the instance group for a project, project_id = %s, instance_group_name = %s, region = %s, zone = %s, flattened_results = %s', project_id, instance_group_name, region, zone, results) return results
def get_instance_group_instances(self, project_id, instance_group_name, region=None, zone=None): "Get the instance groups for a project.\n\n One and only one of zone (for zonal instance groups) and region\n (for regional instance groups) must be specified.\n\n Args:\n project_id (str): The project id.\n instance_group_name (str): The instance group's name.\n region (str): The regional instance group's region.\n zone (str): The zonal instance group's zone.\n\n Returns:\n list: instance URLs for this instance group.\n\n Raises:\n ValueError: invalid combination of parameters\n " if (not (bool(zone) ^ bool(region))): err_message = 'One and only one of zone and region must be specified.' LOGGER.error(err_message) raise ValueError(err_message) if zone: repository = self.repository.instance_groups paged_results = repository.list_instances(project_id, instance_group_name, zone, fields='items/instance,nextPageToken', body={'instanceState': 'ALL'}) else: repository = self.repository.region_instance_groups paged_results = repository.list_instances(project_id, instance_group_name, region, fields='items/instance,nextPageToken', body={'instanceState': 'ALL'}) results = [instance_data.get('instance') for instance_data in _flatten_list_results(project_id, paged_results, 'items') if ('instance' in instance_data)] LOGGER.debug('Getting the instance group for a project, project_id = %s, instance_group_name = %s, region = %s, zone = %s, flattened_results = %s', project_id, instance_group_name, region, zone, results) return results<|docstring|>Get the instance groups for a project. One and only one of zone (for zonal instance groups) and region (for regional instance groups) must be specified. Args: project_id (str): The project id. instance_group_name (str): The instance group's name. region (str): The regional instance group's region. zone (str): The zonal instance group's zone. Returns: list: instance URLs for this instance group. Raises: ValueError: invalid combination of parameters<|endoftext|>
83f0a1dbab7a8ffba3f2c6966b238dfdac1b7f818c42f4068e00de514e8902c9
def get_instance_group_managers(self, project_id): 'Get the instance group managers for a project.\n\n Args:\n project_id (str): The project id.\n\n Returns:\n list: A list of instance group managers for this project.\n ' paged_results = self.repository.instance_group_managers.aggregated_list(project_id) flattened_results = _flatten_aggregated_list_results(project_id, paged_results, 'instanceGroupManagers') LOGGER.debug('Getting the instance group managers for a project, project_id = %s, flattened_results = %s', project_id, flattened_results) return flattened_results
Get the instance group managers for a project. Args: project_id (str): The project id. Returns: list: A list of instance group managers for this project.
google/cloud/forseti/common/gcp_api/compute.py
get_instance_group_managers
muralidkt/forseti-security
921
python
def get_instance_group_managers(self, project_id): 'Get the instance group managers for a project.\n\n Args:\n project_id (str): The project id.\n\n Returns:\n list: A list of instance group managers for this project.\n ' paged_results = self.repository.instance_group_managers.aggregated_list(project_id) flattened_results = _flatten_aggregated_list_results(project_id, paged_results, 'instanceGroupManagers') LOGGER.debug('Getting the instance group managers for a project, project_id = %s, flattened_results = %s', project_id, flattened_results) return flattened_results
def get_instance_group_managers(self, project_id): 'Get the instance group managers for a project.\n\n Args:\n project_id (str): The project id.\n\n Returns:\n list: A list of instance group managers for this project.\n ' paged_results = self.repository.instance_group_managers.aggregated_list(project_id) flattened_results = _flatten_aggregated_list_results(project_id, paged_results, 'instanceGroupManagers') LOGGER.debug('Getting the instance group managers for a project, project_id = %s, flattened_results = %s', project_id, flattened_results) return flattened_results<|docstring|>Get the instance group managers for a project. Args: project_id (str): The project id. Returns: list: A list of instance group managers for this project.<|endoftext|>
ce408502789c1a16385f88fa4e909202700d45fba4788505e50384484f3724aa
def get_instance_groups(self, project_id, include_instance_urls=True): 'Get the instance groups for a project.\n\n Args:\n project_id (str): The project id.\n include_instance_urls (bool): If true, fetch instance urls for each\n instance group and include them in the resource dictionary.\n\n Returns:\n list: A list of instance groups for this project.\n ' paged_results = self.repository.instance_groups.aggregated_list(project_id) instance_groups = sorted(_flatten_aggregated_list_results(project_id, paged_results, 'instanceGroups'), key=(lambda d: d.get('name'))) if include_instance_urls: for instance_group in instance_groups: zone = os.path.basename(instance_group.get('zone', '')) region = os.path.basename(instance_group.get('region', '')) instance_group['instance_urls'] = self.get_instance_group_instances(project_id, instance_group['name'], zone=zone, region=region) LOGGER.debug('Getting the instance groups for a project, project_id = %s, instance_groups = %s', project_id, instance_groups) return instance_groups
Get the instance groups for a project. Args: project_id (str): The project id. include_instance_urls (bool): If true, fetch instance urls for each instance group and include them in the resource dictionary. Returns: list: A list of instance groups for this project.
google/cloud/forseti/common/gcp_api/compute.py
get_instance_groups
muralidkt/forseti-security
921
python
def get_instance_groups(self, project_id, include_instance_urls=True): 'Get the instance groups for a project.\n\n Args:\n project_id (str): The project id.\n include_instance_urls (bool): If true, fetch instance urls for each\n instance group and include them in the resource dictionary.\n\n Returns:\n list: A list of instance groups for this project.\n ' paged_results = self.repository.instance_groups.aggregated_list(project_id) instance_groups = sorted(_flatten_aggregated_list_results(project_id, paged_results, 'instanceGroups'), key=(lambda d: d.get('name'))) if include_instance_urls: for instance_group in instance_groups: zone = os.path.basename(instance_group.get('zone', )) region = os.path.basename(instance_group.get('region', )) instance_group['instance_urls'] = self.get_instance_group_instances(project_id, instance_group['name'], zone=zone, region=region) LOGGER.debug('Getting the instance groups for a project, project_id = %s, instance_groups = %s', project_id, instance_groups) return instance_groups
def get_instance_groups(self, project_id, include_instance_urls=True): 'Get the instance groups for a project.\n\n Args:\n project_id (str): The project id.\n include_instance_urls (bool): If true, fetch instance urls for each\n instance group and include them in the resource dictionary.\n\n Returns:\n list: A list of instance groups for this project.\n ' paged_results = self.repository.instance_groups.aggregated_list(project_id) instance_groups = sorted(_flatten_aggregated_list_results(project_id, paged_results, 'instanceGroups'), key=(lambda d: d.get('name'))) if include_instance_urls: for instance_group in instance_groups: zone = os.path.basename(instance_group.get('zone', )) region = os.path.basename(instance_group.get('region', )) instance_group['instance_urls'] = self.get_instance_group_instances(project_id, instance_group['name'], zone=zone, region=region) LOGGER.debug('Getting the instance groups for a project, project_id = %s, instance_groups = %s', project_id, instance_groups) return instance_groups<|docstring|>Get the instance groups for a project. Args: project_id (str): The project id. include_instance_urls (bool): If true, fetch instance urls for each instance group and include them in the resource dictionary. Returns: list: A list of instance groups for this project.<|endoftext|>
f9091fc0b928614f68f9619ef776acc3343d422d7d775e402e4b491e3c7d7614
def get_instance_templates(self, project_id): 'Get the instance templates for a project.\n\n Args:\n project_id (str): The project id.\n\n Returns:\n list: A list of instance templates for this project.\n ' paged_results = self.repository.instance_templates.list(project_id) flattened_results = _flatten_list_results(project_id, paged_results, 'items') LOGGER.debug('Getting the instance templates for a project, project_id = %s, flattened_results = %s', project_id, flattened_results) return flattened_results
Get the instance templates for a project. Args: project_id (str): The project id. Returns: list: A list of instance templates for this project.
google/cloud/forseti/common/gcp_api/compute.py
get_instance_templates
muralidkt/forseti-security
921
python
def get_instance_templates(self, project_id): 'Get the instance templates for a project.\n\n Args:\n project_id (str): The project id.\n\n Returns:\n list: A list of instance templates for this project.\n ' paged_results = self.repository.instance_templates.list(project_id) flattened_results = _flatten_list_results(project_id, paged_results, 'items') LOGGER.debug('Getting the instance templates for a project, project_id = %s, flattened_results = %s', project_id, flattened_results) return flattened_results
def get_instance_templates(self, project_id): 'Get the instance templates for a project.\n\n Args:\n project_id (str): The project id.\n\n Returns:\n list: A list of instance templates for this project.\n ' paged_results = self.repository.instance_templates.list(project_id) flattened_results = _flatten_list_results(project_id, paged_results, 'items') LOGGER.debug('Getting the instance templates for a project, project_id = %s, flattened_results = %s', project_id, flattened_results) return flattened_results<|docstring|>Get the instance templates for a project. Args: project_id (str): The project id. Returns: list: A list of instance templates for this project.<|endoftext|>
762bfb6736e342150e5d68fc97c696c63930a243f465f3e73654bfda9f5cdd7f
def get_instances(self, project_id, zone=None): 'Get the instances for a project.\n\n Args:\n project_id (str): The project id.\n zone (str): The zone to list the instances in.\n\n Returns:\n list: A list of instances for this project.\n ' repository = self.repository.instances if zone: paged_results = repository.list(project_id, zone) flattened_results = _flatten_list_results(project_id, paged_results, 'items') else: paged_results = repository.aggregated_list(project_id) flattened_results = _flatten_aggregated_list_results(project_id, paged_results, 'instances') LOGGER.debug('Getting the instances for a project, project_id = %s, flattened_results = %s', project_id, flattened_results) return flattened_results
Get the instances for a project. Args: project_id (str): The project id. zone (str): The zone to list the instances in. Returns: list: A list of instances for this project.
google/cloud/forseti/common/gcp_api/compute.py
get_instances
muralidkt/forseti-security
921
python
def get_instances(self, project_id, zone=None): 'Get the instances for a project.\n\n Args:\n project_id (str): The project id.\n zone (str): The zone to list the instances in.\n\n Returns:\n list: A list of instances for this project.\n ' repository = self.repository.instances if zone: paged_results = repository.list(project_id, zone) flattened_results = _flatten_list_results(project_id, paged_results, 'items') else: paged_results = repository.aggregated_list(project_id) flattened_results = _flatten_aggregated_list_results(project_id, paged_results, 'instances') LOGGER.debug('Getting the instances for a project, project_id = %s, flattened_results = %s', project_id, flattened_results) return flattened_results
def get_instances(self, project_id, zone=None): 'Get the instances for a project.\n\n Args:\n project_id (str): The project id.\n zone (str): The zone to list the instances in.\n\n Returns:\n list: A list of instances for this project.\n ' repository = self.repository.instances if zone: paged_results = repository.list(project_id, zone) flattened_results = _flatten_list_results(project_id, paged_results, 'items') else: paged_results = repository.aggregated_list(project_id) flattened_results = _flatten_aggregated_list_results(project_id, paged_results, 'instances') LOGGER.debug('Getting the instances for a project, project_id = %s, flattened_results = %s', project_id, flattened_results) return flattened_results<|docstring|>Get the instances for a project. Args: project_id (str): The project id. zone (str): The zone to list the instances in. Returns: list: A list of instances for this project.<|endoftext|>
43087d48efa21d70e66085aed1bb7cea4c7e49178f222d1abee39d7185f81d92
def get_networks(self, project_id): 'Get the networks list for a given project id.\n\n Args:\n project_id (str): The project id.\n\n Returns:\n list: A list of networks for this project id.\n ' paged_results = self.repository.networks.list(project_id) flattened_results = _flatten_list_results(project_id, paged_results, 'items') LOGGER.debug('Getting the network list for a given project, project_id = %s, flattened_results = %s', project_id, flattened_results) return flattened_results
Get the networks list for a given project id. Args: project_id (str): The project id. Returns: list: A list of networks for this project id.
google/cloud/forseti/common/gcp_api/compute.py
get_networks
muralidkt/forseti-security
921
python
def get_networks(self, project_id): 'Get the networks list for a given project id.\n\n Args:\n project_id (str): The project id.\n\n Returns:\n list: A list of networks for this project id.\n ' paged_results = self.repository.networks.list(project_id) flattened_results = _flatten_list_results(project_id, paged_results, 'items') LOGGER.debug('Getting the network list for a given project, project_id = %s, flattened_results = %s', project_id, flattened_results) return flattened_results
def get_networks(self, project_id): 'Get the networks list for a given project id.\n\n Args:\n project_id (str): The project id.\n\n Returns:\n list: A list of networks for this project id.\n ' paged_results = self.repository.networks.list(project_id) flattened_results = _flatten_list_results(project_id, paged_results, 'items') LOGGER.debug('Getting the network list for a given project, project_id = %s, flattened_results = %s', project_id, flattened_results) return flattened_results<|docstring|>Get the networks list for a given project id. Args: project_id (str): The project id. Returns: list: A list of networks for this project id.<|endoftext|>
f56fe2b7110b09f18f7aba0e8a386cde1780cf70bc09c1266fef6045fe2e3ebe
def get_project(self, project_id): 'Returns the specified Project resource.\n\n Args:\n project_id (str): The project id.\n\n Returns:\n dict: A Compute Project resource dict.\n https://cloud.google.com/compute/docs/reference/latest/projects/get\n ' try: results = self.repository.projects.get(project_id) LOGGER.debug('Getting the specified project resource, project_id = %s, results = %s', project_id, results) return results except (errors.HttpError, HttpLib2Error) as e: (api_not_enabled, details) = _api_not_enabled(e) if api_not_enabled: raise api_errors.ApiNotEnabledError(details, e) raise api_errors.ApiExecutionError(project_id, e)
Returns the specified Project resource. Args: project_id (str): The project id. Returns: dict: A Compute Project resource dict. https://cloud.google.com/compute/docs/reference/latest/projects/get
google/cloud/forseti/common/gcp_api/compute.py
get_project
muralidkt/forseti-security
921
python
def get_project(self, project_id): 'Returns the specified Project resource.\n\n Args:\n project_id (str): The project id.\n\n Returns:\n dict: A Compute Project resource dict.\n https://cloud.google.com/compute/docs/reference/latest/projects/get\n ' try: results = self.repository.projects.get(project_id) LOGGER.debug('Getting the specified project resource, project_id = %s, results = %s', project_id, results) return results except (errors.HttpError, HttpLib2Error) as e: (api_not_enabled, details) = _api_not_enabled(e) if api_not_enabled: raise api_errors.ApiNotEnabledError(details, e) raise api_errors.ApiExecutionError(project_id, e)
def get_project(self, project_id): 'Returns the specified Project resource.\n\n Args:\n project_id (str): The project id.\n\n Returns:\n dict: A Compute Project resource dict.\n https://cloud.google.com/compute/docs/reference/latest/projects/get\n ' try: results = self.repository.projects.get(project_id) LOGGER.debug('Getting the specified project resource, project_id = %s, results = %s', project_id, results) return results except (errors.HttpError, HttpLib2Error) as e: (api_not_enabled, details) = _api_not_enabled(e) if api_not_enabled: raise api_errors.ApiNotEnabledError(details, e) raise api_errors.ApiExecutionError(project_id, e)<|docstring|>Returns the specified Project resource. Args: project_id (str): The project id. Returns: dict: A Compute Project resource dict. https://cloud.google.com/compute/docs/reference/latest/projects/get<|endoftext|>
bffd95d079c89bf04f98fb22fad32be97617d298c52a5e625c32b0e58e62346a
def get_quota(self, project_id, metric): 'Returns the quota for any metric\n\n Args:\n project_id (str): The project id.\n metric (str): The metric name of the quota needed.\n\n Returns:\n dict: The quota of a requested metric in a dict.\n\n An example return value:\n\n {\n "metric": "FIREWALLS",\n "limit": 100.0,\n "usage": 9.0\n }\n\n Raises:\n KeyError: Metric was not found in the project.\n ' resource = self.get_project(project_id) quotas = resource.get('quotas', []) LOGGER.debug('Getting the quota for any metric, project_id = %s, metric = %s, quotas = %s', project_id, metric, quotas) for quota in quotas: if (quota.get('metric', '') == metric): return quota err = KeyError(('Passed in metric, %s, was not found for project id, %s.' % (metric, project_id))) LOGGER.error(err) raise err
Returns the quota for any metric Args: project_id (str): The project id. metric (str): The metric name of the quota needed. Returns: dict: The quota of a requested metric in a dict. An example return value: { "metric": "FIREWALLS", "limit": 100.0, "usage": 9.0 } Raises: KeyError: Metric was not found in the project.
google/cloud/forseti/common/gcp_api/compute.py
get_quota
muralidkt/forseti-security
921
python
def get_quota(self, project_id, metric): 'Returns the quota for any metric\n\n Args:\n project_id (str): The project id.\n metric (str): The metric name of the quota needed.\n\n Returns:\n dict: The quota of a requested metric in a dict.\n\n An example return value:\n\n {\n "metric": "FIREWALLS",\n "limit": 100.0,\n "usage": 9.0\n }\n\n Raises:\n KeyError: Metric was not found in the project.\n ' resource = self.get_project(project_id) quotas = resource.get('quotas', []) LOGGER.debug('Getting the quota for any metric, project_id = %s, metric = %s, quotas = %s', project_id, metric, quotas) for quota in quotas: if (quota.get('metric', ) == metric): return quota err = KeyError(('Passed in metric, %s, was not found for project id, %s.' % (metric, project_id))) LOGGER.error(err) raise err
def get_quota(self, project_id, metric): 'Returns the quota for any metric\n\n Args:\n project_id (str): The project id.\n metric (str): The metric name of the quota needed.\n\n Returns:\n dict: The quota of a requested metric in a dict.\n\n An example return value:\n\n {\n "metric": "FIREWALLS",\n "limit": 100.0,\n "usage": 9.0\n }\n\n Raises:\n KeyError: Metric was not found in the project.\n ' resource = self.get_project(project_id) quotas = resource.get('quotas', []) LOGGER.debug('Getting the quota for any metric, project_id = %s, metric = %s, quotas = %s', project_id, metric, quotas) for quota in quotas: if (quota.get('metric', ) == metric): return quota err = KeyError(('Passed in metric, %s, was not found for project id, %s.' % (metric, project_id))) LOGGER.error(err) raise err<|docstring|>Returns the quota for any metric Args: project_id (str): The project id. metric (str): The metric name of the quota needed. Returns: dict: The quota of a requested metric in a dict. An example return value: { "metric": "FIREWALLS", "limit": 100.0, "usage": 9.0 } Raises: KeyError: Metric was not found in the project.<|endoftext|>
daa9df25ec49921186f82370a8b979ed8b59c86b99697a4c9b2d41657334e42e
def get_firewall_quota(self, project_id): 'Calls get_quota to request the firewall quota\n Args:\n project_id (str): The project id.\n\n Returns:\n dict: The quota of a requested metric in a dict.\n\n An example return value:\n\n {\n "metric": "FIREWALLS",\n "limit": 100.0,\n "usage": 9.0\n }\n\n Raises:\n KeyError: Metric was not a firewall resource.\n ' metric = 'FIREWALLS' resource = self.get_quota(project_id, metric) LOGGER.debug('Getting the firewall quota, project_id = %s, resource = %s', project_id, resource) return resource
Calls get_quota to request the firewall quota Args: project_id (str): The project id. Returns: dict: The quota of a requested metric in a dict. An example return value: { "metric": "FIREWALLS", "limit": 100.0, "usage": 9.0 } Raises: KeyError: Metric was not a firewall resource.
google/cloud/forseti/common/gcp_api/compute.py
get_firewall_quota
muralidkt/forseti-security
921
python
def get_firewall_quota(self, project_id): 'Calls get_quota to request the firewall quota\n Args:\n project_id (str): The project id.\n\n Returns:\n dict: The quota of a requested metric in a dict.\n\n An example return value:\n\n {\n "metric": "FIREWALLS",\n "limit": 100.0,\n "usage": 9.0\n }\n\n Raises:\n KeyError: Metric was not a firewall resource.\n ' metric = 'FIREWALLS' resource = self.get_quota(project_id, metric) LOGGER.debug('Getting the firewall quota, project_id = %s, resource = %s', project_id, resource) return resource
def get_firewall_quota(self, project_id): 'Calls get_quota to request the firewall quota\n Args:\n project_id (str): The project id.\n\n Returns:\n dict: The quota of a requested metric in a dict.\n\n An example return value:\n\n {\n "metric": "FIREWALLS",\n "limit": 100.0,\n "usage": 9.0\n }\n\n Raises:\n KeyError: Metric was not a firewall resource.\n ' metric = 'FIREWALLS' resource = self.get_quota(project_id, metric) LOGGER.debug('Getting the firewall quota, project_id = %s, resource = %s', project_id, resource) return resource<|docstring|>Calls get_quota to request the firewall quota Args: project_id (str): The project id. Returns: dict: The quota of a requested metric in a dict. An example return value: { "metric": "FIREWALLS", "limit": 100.0, "usage": 9.0 } Raises: KeyError: Metric was not a firewall resource.<|endoftext|>
3e5471c0e3387ebc0e101c2ae5c3d790f6bcc5646f20b9a465f9ba7cfa352e6c
def get_subnetworks(self, project_id, region=None): 'Return the list of all subnetworks in the project.\n\n Args:\n project_id (str): The project id.\n region (str): An optional region to query, if not provided then all\n subnetworks in all regions are returned.\n\n Returns:\n list: A list of subnetwork resources for this project.\n ' repository = self.repository.subnetworks if region: paged_results = repository.list(project_id, region) flattened_results = _flatten_list_results(project_id, paged_results, 'items') else: paged_results = repository.aggregated_list(project_id) flattened_results = _flatten_aggregated_list_results(project_id, paged_results, 'subnetworks') LOGGER.debug('Getting a list of all subnetworks in the project, project_id = %s, region = %s, flattened_results = %s', project_id, region, flattened_results) return flattened_results
Return the list of all subnetworks in the project. Args: project_id (str): The project id. region (str): An optional region to query, if not provided then all subnetworks in all regions are returned. Returns: list: A list of subnetwork resources for this project.
google/cloud/forseti/common/gcp_api/compute.py
get_subnetworks
muralidkt/forseti-security
921
python
def get_subnetworks(self, project_id, region=None): 'Return the list of all subnetworks in the project.\n\n Args:\n project_id (str): The project id.\n region (str): An optional region to query, if not provided then all\n subnetworks in all regions are returned.\n\n Returns:\n list: A list of subnetwork resources for this project.\n ' repository = self.repository.subnetworks if region: paged_results = repository.list(project_id, region) flattened_results = _flatten_list_results(project_id, paged_results, 'items') else: paged_results = repository.aggregated_list(project_id) flattened_results = _flatten_aggregated_list_results(project_id, paged_results, 'subnetworks') LOGGER.debug('Getting a list of all subnetworks in the project, project_id = %s, region = %s, flattened_results = %s', project_id, region, flattened_results) return flattened_results
def get_subnetworks(self, project_id, region=None): 'Return the list of all subnetworks in the project.\n\n Args:\n project_id (str): The project id.\n region (str): An optional region to query, if not provided then all\n subnetworks in all regions are returned.\n\n Returns:\n list: A list of subnetwork resources for this project.\n ' repository = self.repository.subnetworks if region: paged_results = repository.list(project_id, region) flattened_results = _flatten_list_results(project_id, paged_results, 'items') else: paged_results = repository.aggregated_list(project_id) flattened_results = _flatten_aggregated_list_results(project_id, paged_results, 'subnetworks') LOGGER.debug('Getting a list of all subnetworks in the project, project_id = %s, region = %s, flattened_results = %s', project_id, region, flattened_results) return flattened_results<|docstring|>Return the list of all subnetworks in the project. Args: project_id (str): The project id. region (str): An optional region to query, if not provided then all subnetworks in all regions are returned. Returns: list: A list of subnetwork resources for this project.<|endoftext|>
e9e7a96473f9362f06e9e149f448c93b39c267d33cf4f167dcda8cb38f34d727
def is_api_enabled(self, project_id): 'Checks if the Compute API is enabled for the specified project.\n\n Args:\n project_id (str): The project id.\n\n Returns:\n bool: True if the API is enabled, else False.\n ' try: result = self.repository.projects.get(project_id, fields='name') LOGGER.debug('Checking if Compute API is enabled, project_id = %s, result = %s', project_id, result) return bool(('name' in result)) except (errors.HttpError, HttpLib2Error) as e: (api_not_enabled, _) = _api_not_enabled(e) if api_not_enabled: return False raise api_errors.ApiExecutionError(project_id, e)
Checks if the Compute API is enabled for the specified project. Args: project_id (str): The project id. Returns: bool: True if the API is enabled, else False.
google/cloud/forseti/common/gcp_api/compute.py
is_api_enabled
muralidkt/forseti-security
921
python
def is_api_enabled(self, project_id): 'Checks if the Compute API is enabled for the specified project.\n\n Args:\n project_id (str): The project id.\n\n Returns:\n bool: True if the API is enabled, else False.\n ' try: result = self.repository.projects.get(project_id, fields='name') LOGGER.debug('Checking if Compute API is enabled, project_id = %s, result = %s', project_id, result) return bool(('name' in result)) except (errors.HttpError, HttpLib2Error) as e: (api_not_enabled, _) = _api_not_enabled(e) if api_not_enabled: return False raise api_errors.ApiExecutionError(project_id, e)
def is_api_enabled(self, project_id): 'Checks if the Compute API is enabled for the specified project.\n\n Args:\n project_id (str): The project id.\n\n Returns:\n bool: True if the API is enabled, else False.\n ' try: result = self.repository.projects.get(project_id, fields='name') LOGGER.debug('Checking if Compute API is enabled, project_id = %s, result = %s', project_id, result) return bool(('name' in result)) except (errors.HttpError, HttpLib2Error) as e: (api_not_enabled, _) = _api_not_enabled(e) if api_not_enabled: return False raise api_errors.ApiExecutionError(project_id, e)<|docstring|>Checks if the Compute API is enabled for the specified project. Args: project_id (str): The project id. Returns: bool: True if the API is enabled, else False.<|endoftext|>
64dbd15a041eb72877fdaa85157ad158ca18d205955e120e63d808c222692dd8
def wait_for_completion(self, project_id, operation, timeout=0, initial_delay=None): 'Wait for the operation to complete.\n\n Args:\n project_id (str): The project id.\n operation (dict): The global operation response from an API call.\n timeout (float): The maximum time to wait for the operation to\n complete.\n initial_delay (float): The time to wait before first checking if the\n API has completed.\n\n Returns:\n dict: Global Operation status and info.\n https://cloud.google.com/compute/docs/reference/latest/globalOperations/get\n\n Raises:\n OperationTimeoutError: Raised if the operation times out.\n ' if (operation.get('status', '') == 'DONE'): return operation if (initial_delay is None): initial_delay = self.ESTIMATED_API_COMPLETION_IN_SEC started_timestamp = time.time() time.sleep(initial_delay) while True: operation_name = operation['name'] operation = self.get_global_operation(project_id, operation_id=operation_name) if (operation.get('status', '') == 'DONE'): _debug_operation_response_time(project_id, operation) return operation if (timeout and ((time.time() - started_timestamp) > timeout)): raise api_errors.OperationTimeoutError(project_id, operation) time.sleep(2)
Wait for the operation to complete. Args: project_id (str): The project id. operation (dict): The global operation response from an API call. timeout (float): The maximum time to wait for the operation to complete. initial_delay (float): The time to wait before first checking if the API has completed. Returns: dict: Global Operation status and info. https://cloud.google.com/compute/docs/reference/latest/globalOperations/get Raises: OperationTimeoutError: Raised if the operation times out.
google/cloud/forseti/common/gcp_api/compute.py
wait_for_completion
muralidkt/forseti-security
921
python
def wait_for_completion(self, project_id, operation, timeout=0, initial_delay=None): 'Wait for the operation to complete.\n\n Args:\n project_id (str): The project id.\n operation (dict): The global operation response from an API call.\n timeout (float): The maximum time to wait for the operation to\n complete.\n initial_delay (float): The time to wait before first checking if the\n API has completed.\n\n Returns:\n dict: Global Operation status and info.\n https://cloud.google.com/compute/docs/reference/latest/globalOperations/get\n\n Raises:\n OperationTimeoutError: Raised if the operation times out.\n ' if (operation.get('status', ) == 'DONE'): return operation if (initial_delay is None): initial_delay = self.ESTIMATED_API_COMPLETION_IN_SEC started_timestamp = time.time() time.sleep(initial_delay) while True: operation_name = operation['name'] operation = self.get_global_operation(project_id, operation_id=operation_name) if (operation.get('status', ) == 'DONE'): _debug_operation_response_time(project_id, operation) return operation if (timeout and ((time.time() - started_timestamp) > timeout)): raise api_errors.OperationTimeoutError(project_id, operation) time.sleep(2)
def wait_for_completion(self, project_id, operation, timeout=0, initial_delay=None): 'Wait for the operation to complete.\n\n Args:\n project_id (str): The project id.\n operation (dict): The global operation response from an API call.\n timeout (float): The maximum time to wait for the operation to\n complete.\n initial_delay (float): The time to wait before first checking if the\n API has completed.\n\n Returns:\n dict: Global Operation status and info.\n https://cloud.google.com/compute/docs/reference/latest/globalOperations/get\n\n Raises:\n OperationTimeoutError: Raised if the operation times out.\n ' if (operation.get('status', ) == 'DONE'): return operation if (initial_delay is None): initial_delay = self.ESTIMATED_API_COMPLETION_IN_SEC started_timestamp = time.time() time.sleep(initial_delay) while True: operation_name = operation['name'] operation = self.get_global_operation(project_id, operation_id=operation_name) if (operation.get('status', ) == 'DONE'): _debug_operation_response_time(project_id, operation) return operation if (timeout and ((time.time() - started_timestamp) > timeout)): raise api_errors.OperationTimeoutError(project_id, operation) time.sleep(2)<|docstring|>Wait for the operation to complete. Args: project_id (str): The project id. operation (dict): The global operation response from an API call. timeout (float): The maximum time to wait for the operation to complete. initial_delay (float): The time to wait before first checking if the API has completed. Returns: dict: Global Operation status and info. https://cloud.google.com/compute/docs/reference/latest/globalOperations/get Raises: OperationTimeoutError: Raised if the operation times out.<|endoftext|>
e4471c0fabe96499e07772d87418f2aba6f88bbca384276d80ffc6505109ee6d
def findEgg(prefix: str) -> str: 'Find an egg whose name begins with the given string. Raises if this egg does not exist or is\n not unique.\n ' found: Optional[str] = None for dirEntry in os.scandir(EGGS_DIR): if (dirEntry.is_dir() and dirEntry.name.startswith(prefix)): if (found is not None): raise ValueError(f'Found multiple eggs beginning with "{prefix}": {found} and {dirEntry.name}') found = dirEntry.name if (found is None): raise ValueError(f'Found no egg beginning with "{prefix}"') return os.path.join(EGGS_DIR, found)
Find an egg whose name begins with the given string. Raises if this egg does not exist or is not unique.
setup.py
findEgg
humu/heapprof
34
python
def findEgg(prefix: str) -> str: 'Find an egg whose name begins with the given string. Raises if this egg does not exist or is\n not unique.\n ' found: Optional[str] = None for dirEntry in os.scandir(EGGS_DIR): if (dirEntry.is_dir() and dirEntry.name.startswith(prefix)): if (found is not None): raise ValueError(f'Found multiple eggs beginning with "{prefix}": {found} and {dirEntry.name}') found = dirEntry.name if (found is None): raise ValueError(f'Found no egg beginning with "{prefix}"') return os.path.join(EGGS_DIR, found)
def findEgg(prefix: str) -> str: 'Find an egg whose name begins with the given string. Raises if this egg does not exist or is\n not unique.\n ' found: Optional[str] = None for dirEntry in os.scandir(EGGS_DIR): if (dirEntry.is_dir() and dirEntry.name.startswith(prefix)): if (found is not None): raise ValueError(f'Found multiple eggs beginning with "{prefix}": {found} and {dirEntry.name}') found = dirEntry.name if (found is None): raise ValueError(f'Found no egg beginning with "{prefix}"') return os.path.join(EGGS_DIR, found)<|docstring|>Find an egg whose name begins with the given string. Raises if this egg does not exist or is not unique.<|endoftext|>
6f3451ca26eda56cea76e926f6fc563dd056f83a2fb2303d1b21b345c9279a11
def is_tau_too_high(self): '\n Check if the last passage was too long ago\n :return: True if the last passage was too long ago, False otherwise\n :rtype: boolean\n ' return (((len(self.device_list) > 5) and (self.tau > 180)) or ((len(self.device_list) >= 1) and (self.tau > 210)))
Check if the last passage was too long ago :return: True if the last passage was too long ago, False otherwise :rtype: boolean
app/model/monitoring_areas/room.py
is_tau_too_high
muglyon/https-github.com-muglyon-DCOP-Decentralised-Control-of-Intelligent-Devices
3
python
def is_tau_too_high(self): '\n Check if the last passage was too long ago\n :return: True if the last passage was too long ago, False otherwise\n :rtype: boolean\n ' return (((len(self.device_list) > 5) and (self.tau > 180)) or ((len(self.device_list) >= 1) and (self.tau > 210)))
def is_tau_too_high(self): '\n Check if the last passage was too long ago\n :return: True if the last passage was too long ago, False otherwise\n :rtype: boolean\n ' return (((len(self.device_list) > 5) and (self.tau > 180)) or ((len(self.device_list) >= 1) and (self.tau > 210)))<|docstring|>Check if the last passage was too long ago :return: True if the last passage was too long ago, False otherwise :rtype: boolean<|endoftext|>
37fe1ea15a0c846a51e4b26314417556ba9071ea3dc2ff393a914e486d0fb12a
def is_in_critical_state(self): '\n Check if the room is in critical state\n :return: True if the room has at least one device in critical state, False otherwise\n :rtype: boolean\n # ' return any((d.is_in_critic_state for d in self.device_list))
Check if the room is in critical state :return: True if the room has at least one device in critical state, False otherwise :rtype: boolean #
app/model/monitoring_areas/room.py
is_in_critical_state
muglyon/https-github.com-muglyon-DCOP-Decentralised-Control-of-Intelligent-Devices
3
python
def is_in_critical_state(self): '\n Check if the room is in critical state\n :return: True if the room has at least one device in critical state, False otherwise\n :rtype: boolean\n # ' return any((d.is_in_critic_state for d in self.device_list))
def is_in_critical_state(self): '\n Check if the room is in critical state\n :return: True if the room has at least one device in critical state, False otherwise\n :rtype: boolean\n # ' return any((d.is_in_critic_state for d in self.device_list))<|docstring|>Check if the room is in critical state :return: True if the room has at least one device in critical state, False otherwise :rtype: boolean #<|endoftext|>
56aedec33d532fb6d4ba0425cbd17fe6f1d5b6165defb4ad92383f547d70bb54
def get_min_end_of_prog(self): '\n Get the minimum time before a program ends\n :return: the minimum time in minutes\n :rtype: integer\n ' minimum = 241 for device in self.device_list: if (device.end_of_prog < minimum): minimum = device.end_of_prog return minimum
Get the minimum time before a program ends :return: the minimum time in minutes :rtype: integer
app/model/monitoring_areas/room.py
get_min_end_of_prog
muglyon/https-github.com-muglyon-DCOP-Decentralised-Control-of-Intelligent-Devices
3
python
def get_min_end_of_prog(self): '\n Get the minimum time before a program ends\n :return: the minimum time in minutes\n :rtype: integer\n ' minimum = 241 for device in self.device_list: if (device.end_of_prog < minimum): minimum = device.end_of_prog return minimum
def get_min_end_of_prog(self): '\n Get the minimum time before a program ends\n :return: the minimum time in minutes\n :rtype: integer\n ' minimum = 241 for device in self.device_list: if (device.end_of_prog < minimum): minimum = device.end_of_prog return minimum<|docstring|>Get the minimum time before a program ends :return: the minimum time in minutes :rtype: integer<|endoftext|>
658a362dabf8a3b5f3cfc697e6dbabd895a4ad62b8896c9a62b26054ef5435c9
def update_device(self, device): "\n Update state of the device\n If it's a new one, the device is added to the list\n :param device: device to update\n :type device: Device\n " is_device_exist = False for d in self.device_list: if (d.id == device.id): device = d is_device_exist = True break if (not is_device_exist): self.device_list.append(device)
Update state of the device If it's a new one, the device is added to the list :param device: device to update :type device: Device
app/model/monitoring_areas/room.py
update_device
muglyon/https-github.com-muglyon-DCOP-Decentralised-Control-of-Intelligent-Devices
3
python
def update_device(self, device): "\n Update state of the device\n If it's a new one, the device is added to the list\n :param device: device to update\n :type device: Device\n " is_device_exist = False for d in self.device_list: if (d.id == device.id): device = d is_device_exist = True break if (not is_device_exist): self.device_list.append(device)
def update_device(self, device): "\n Update state of the device\n If it's a new one, the device is added to the list\n :param device: device to update\n :type device: Device\n " is_device_exist = False for d in self.device_list: if (d.id == device.id): device = d is_device_exist = True break if (not is_device_exist): self.device_list.append(device)<|docstring|>Update state of the device If it's a new one, the device is added to the list :param device: device to update :type device: Device<|endoftext|>
e745cb409c2682d612d92459b398e3cc50622f722f9eaff1c102660d1aa405a1
def get_max_forkpoint(self) -> int: 'Returns the max height where there is a fork\n related to this chain.\n ' mc = self.get_max_child() return (mc if (mc is not None) else self.forkpoint)
Returns the max height where there is a fork related to this chain.
electrum_ltc/blockchain.py
get_max_forkpoint
Electronic-Gulden-Foundation/electrum-ltc
1
python
def get_max_forkpoint(self) -> int: 'Returns the max height where there is a fork\n related to this chain.\n ' mc = self.get_max_child() return (mc if (mc is not None) else self.forkpoint)
def get_max_forkpoint(self) -> int: 'Returns the max height where there is a fork\n related to this chain.\n ' mc = self.get_max_child() return (mc if (mc is not None) else self.forkpoint)<|docstring|>Returns the max height where there is a fork related to this chain.<|endoftext|>
9316029765cfdf6807536dd6368dc00097a7c215cefcecb97ec611c784f5f7d3
def get_parent_heights(self) -> Mapping[('Blockchain', int)]: 'Returns map: (parent chain -> height of last common block)' with blockchains_lock: result = {self: self.height()} chain = self while True: parent = chain.parent if (parent is None): break result[parent] = (chain.forkpoint - 1) chain = parent return result
Returns map: (parent chain -> height of last common block)
electrum_ltc/blockchain.py
get_parent_heights
Electronic-Gulden-Foundation/electrum-ltc
1
python
def get_parent_heights(self) -> Mapping[('Blockchain', int)]: with blockchains_lock: result = {self: self.height()} chain = self while True: parent = chain.parent if (parent is None): break result[parent] = (chain.forkpoint - 1) chain = parent return result
def get_parent_heights(self) -> Mapping[('Blockchain', int)]: with blockchains_lock: result = {self: self.height()} chain = self while True: parent = chain.parent if (parent is None): break result[parent] = (chain.forkpoint - 1) chain = parent return result<|docstring|>Returns map: (parent chain -> height of last common block)<|endoftext|>
b5cacf243f2735fe26d2e6d66f5e53e6a858e5b4d3c1029d1a30fc005b6a58f7
def check_hash(self, height: int, header_hash: str) -> bool: 'Returns whether the hash of the block at given height\n is the given hash.\n ' assert (isinstance(header_hash, str) and (len(header_hash) == 64)), header_hash try: return (header_hash == self.get_hash(height)) except Exception: return False
Returns whether the hash of the block at given height is the given hash.
electrum_ltc/blockchain.py
check_hash
Electronic-Gulden-Foundation/electrum-ltc
1
python
def check_hash(self, height: int, header_hash: str) -> bool: 'Returns whether the hash of the block at given height\n is the given hash.\n ' assert (isinstance(header_hash, str) and (len(header_hash) == 64)), header_hash try: return (header_hash == self.get_hash(height)) except Exception: return False
def check_hash(self, height: int, header_hash: str) -> bool: 'Returns whether the hash of the block at given height\n is the given hash.\n ' assert (isinstance(header_hash, str) and (len(header_hash) == 64)), header_hash try: return (header_hash == self.get_hash(height)) except Exception: return False<|docstring|>Returns whether the hash of the block at given height is the given hash.<|endoftext|>
2198828a715bff93bd9218f549a68f2118aaedb3b247185f1d8cdc4f7eee3a60
def _swap_with_parent(self) -> bool: "Check if this chain became stronger than its parent, and swap\n the underlying files if so. The Blockchain instances will keep\n 'containing' the same headers, but their ids change and so\n they will be stored in different files." if (self.parent is None): return False if (self.parent.get_chainwork() >= self.get_chainwork()): return False self.logger.info(f'swapping {self.forkpoint} {self.parent.forkpoint}') parent_branch_size = ((self.parent.height() - self.forkpoint) + 1) forkpoint = self.forkpoint parent = self.parent child_old_id = self.get_id() parent_old_id = parent.get_id() self.assert_headers_file_available(self.path()) child_old_name = self.path() with open(self.path(), 'rb') as f: my_data = f.read() self.assert_headers_file_available(parent.path()) assert (forkpoint > parent.forkpoint), f"forkpoint of parent chain ({parent.forkpoint}) should be at lower height than children's ({forkpoint})" with open(parent.path(), 'rb') as f: f.seek(((forkpoint - parent.forkpoint) * HEADER_SIZE)) parent_data = f.read((parent_branch_size * HEADER_SIZE)) self.write(parent_data, 0) parent.write(my_data, ((forkpoint - parent.forkpoint) * HEADER_SIZE)) (self.parent, parent.parent) = (parent.parent, self) (self.forkpoint, parent.forkpoint) = (parent.forkpoint, self.forkpoint) (self._forkpoint_hash, parent._forkpoint_hash) = (parent._forkpoint_hash, hash_raw_header(bh2u(parent_data[:HEADER_SIZE]))) (self._prev_hash, parent._prev_hash) = (parent._prev_hash, self._prev_hash) os.replace(child_old_name, parent.path()) self.update_size() parent.update_size() blockchains.pop(child_old_id, None) blockchains.pop(parent_old_id, None) blockchains[self.get_id()] = self blockchains[parent.get_id()] = parent return True
Check if this chain became stronger than its parent, and swap the underlying files if so. The Blockchain instances will keep 'containing' the same headers, but their ids change and so they will be stored in different files.
electrum_ltc/blockchain.py
_swap_with_parent
Electronic-Gulden-Foundation/electrum-ltc
1
python
def _swap_with_parent(self) -> bool: "Check if this chain became stronger than its parent, and swap\n the underlying files if so. The Blockchain instances will keep\n 'containing' the same headers, but their ids change and so\n they will be stored in different files." if (self.parent is None): return False if (self.parent.get_chainwork() >= self.get_chainwork()): return False self.logger.info(f'swapping {self.forkpoint} {self.parent.forkpoint}') parent_branch_size = ((self.parent.height() - self.forkpoint) + 1) forkpoint = self.forkpoint parent = self.parent child_old_id = self.get_id() parent_old_id = parent.get_id() self.assert_headers_file_available(self.path()) child_old_name = self.path() with open(self.path(), 'rb') as f: my_data = f.read() self.assert_headers_file_available(parent.path()) assert (forkpoint > parent.forkpoint), f"forkpoint of parent chain ({parent.forkpoint}) should be at lower height than children's ({forkpoint})" with open(parent.path(), 'rb') as f: f.seek(((forkpoint - parent.forkpoint) * HEADER_SIZE)) parent_data = f.read((parent_branch_size * HEADER_SIZE)) self.write(parent_data, 0) parent.write(my_data, ((forkpoint - parent.forkpoint) * HEADER_SIZE)) (self.parent, parent.parent) = (parent.parent, self) (self.forkpoint, parent.forkpoint) = (parent.forkpoint, self.forkpoint) (self._forkpoint_hash, parent._forkpoint_hash) = (parent._forkpoint_hash, hash_raw_header(bh2u(parent_data[:HEADER_SIZE]))) (self._prev_hash, parent._prev_hash) = (parent._prev_hash, self._prev_hash) os.replace(child_old_name, parent.path()) self.update_size() parent.update_size() blockchains.pop(child_old_id, None) blockchains.pop(parent_old_id, None) blockchains[self.get_id()] = self blockchains[parent.get_id()] = parent return True
def _swap_with_parent(self) -> bool: "Check if this chain became stronger than its parent, and swap\n the underlying files if so. The Blockchain instances will keep\n 'containing' the same headers, but their ids change and so\n they will be stored in different files." if (self.parent is None): return False if (self.parent.get_chainwork() >= self.get_chainwork()): return False self.logger.info(f'swapping {self.forkpoint} {self.parent.forkpoint}') parent_branch_size = ((self.parent.height() - self.forkpoint) + 1) forkpoint = self.forkpoint parent = self.parent child_old_id = self.get_id() parent_old_id = parent.get_id() self.assert_headers_file_available(self.path()) child_old_name = self.path() with open(self.path(), 'rb') as f: my_data = f.read() self.assert_headers_file_available(parent.path()) assert (forkpoint > parent.forkpoint), f"forkpoint of parent chain ({parent.forkpoint}) should be at lower height than children's ({forkpoint})" with open(parent.path(), 'rb') as f: f.seek(((forkpoint - parent.forkpoint) * HEADER_SIZE)) parent_data = f.read((parent_branch_size * HEADER_SIZE)) self.write(parent_data, 0) parent.write(my_data, ((forkpoint - parent.forkpoint) * HEADER_SIZE)) (self.parent, parent.parent) = (parent.parent, self) (self.forkpoint, parent.forkpoint) = (parent.forkpoint, self.forkpoint) (self._forkpoint_hash, parent._forkpoint_hash) = (parent._forkpoint_hash, hash_raw_header(bh2u(parent_data[:HEADER_SIZE]))) (self._prev_hash, parent._prev_hash) = (parent._prev_hash, self._prev_hash) os.replace(child_old_name, parent.path()) self.update_size() parent.update_size() blockchains.pop(child_old_id, None) blockchains.pop(parent_old_id, None) blockchains[self.get_id()] = self blockchains[parent.get_id()] = parent return True<|docstring|>Check if this chain became stronger than its parent, and swap the underlying files if so. The Blockchain instances will keep 'containing' the same headers, but their ids change and so they will be stored in different files.<|endoftext|>
c520a8121512831d3137157545b8920e197510fa106e6f534e8c52b05c1ba3a1
def header_at_tip(self) -> Optional[dict]: 'Return latest header.' height = self.height() return self.read_header(height)
Return latest header.
electrum_ltc/blockchain.py
header_at_tip
Electronic-Gulden-Foundation/electrum-ltc
1
python
def header_at_tip(self) -> Optional[dict]: height = self.height() return self.read_header(height)
def header_at_tip(self) -> Optional[dict]: height = self.height() return self.read_header(height)<|docstring|>Return latest header.<|endoftext|>
ea4cad909ef8180ed1410cd19a60e73b20e87780bb07f5975417e6c0589026df
def chainwork_of_header_at_height(self, height: int) -> int: 'work done by single header at given height' chunk_idx = ((height // MINER_CONFIRMATION_WINDOW) - 1) target = self.get_target(chunk_idx) work = (((((2 ** 256) - target) - 1) // (target + 1)) + 1) return work
work done by single header at given height
electrum_ltc/blockchain.py
chainwork_of_header_at_height
Electronic-Gulden-Foundation/electrum-ltc
1
python
def chainwork_of_header_at_height(self, height: int) -> int: chunk_idx = ((height // MINER_CONFIRMATION_WINDOW) - 1) target = self.get_target(chunk_idx) work = (((((2 ** 256) - target) - 1) // (target + 1)) + 1) return work
def chainwork_of_header_at_height(self, height: int) -> int: chunk_idx = ((height // MINER_CONFIRMATION_WINDOW) - 1) target = self.get_target(chunk_idx) work = (((((2 ** 256) - target) - 1) // (target + 1)) + 1) return work<|docstring|>work done by single header at given height<|endoftext|>
8ac155658b012ed62c4b45ea26bec13c805c8542257c1791f5768c4c1c9d9382
def bubblesort(array): '\n bubblesort(array) -> list\n \n array -> [list]: A list of elements to be sorted using bubblesort \n ' steps = 0 while True: swapped = False for i in range((len(array) - 1)): if (array[i] > array[(i + 1)]): (array[(i + 1)], array[i]) = (array[i], array[(i + 1)]) swapped = True steps += 1 if (not swapped): break return (array, steps)
bubblesort(array) -> list array -> [list]: A list of elements to be sorted using bubblesort
problem_sets/ps1/sorting.py
bubblesort
nathan-yan/YSPA2019
0
python
def bubblesort(array): '\n bubblesort(array) -> list\n \n array -> [list]: A list of elements to be sorted using bubblesort \n ' steps = 0 while True: swapped = False for i in range((len(array) - 1)): if (array[i] > array[(i + 1)]): (array[(i + 1)], array[i]) = (array[i], array[(i + 1)]) swapped = True steps += 1 if (not swapped): break return (array, steps)
def bubblesort(array): '\n bubblesort(array) -> list\n \n array -> [list]: A list of elements to be sorted using bubblesort \n ' steps = 0 while True: swapped = False for i in range((len(array) - 1)): if (array[i] > array[(i + 1)]): (array[(i + 1)], array[i]) = (array[i], array[(i + 1)]) swapped = True steps += 1 if (not swapped): break return (array, steps)<|docstring|>bubblesort(array) -> list array -> [list]: A list of elements to be sorted using bubblesort<|endoftext|>
29cdc49a314e9fcfd9c1a38a8909b9399650593560ed5f566dfc5bc47af0e65d
def combsort(array, scaling_factor): '\n combsort(array, scaling_factor) -> list\n \n array -> [list]: A list of elements to be sorted using combsort \n scaling_factor -> [float]: A scalar that reduces the size of the\n gap every sweep (>1)\n ' steps = 0 gap = len(array) while True: swapped = False gap = int((gap / scaling_factor)) for i in range((len(array) - gap)): if (array[i] > array[(i + gap)]): (array[(i + gap)], array[i]) = (array[i], array[(i + gap)]) swapped = True steps += 1 if ((not swapped) and (gap == 0)): break return (array, steps)
combsort(array, scaling_factor) -> list array -> [list]: A list of elements to be sorted using combsort scaling_factor -> [float]: A scalar that reduces the size of the gap every sweep (>1)
problem_sets/ps1/sorting.py
combsort
nathan-yan/YSPA2019
0
python
def combsort(array, scaling_factor): '\n combsort(array, scaling_factor) -> list\n \n array -> [list]: A list of elements to be sorted using combsort \n scaling_factor -> [float]: A scalar that reduces the size of the\n gap every sweep (>1)\n ' steps = 0 gap = len(array) while True: swapped = False gap = int((gap / scaling_factor)) for i in range((len(array) - gap)): if (array[i] > array[(i + gap)]): (array[(i + gap)], array[i]) = (array[i], array[(i + gap)]) swapped = True steps += 1 if ((not swapped) and (gap == 0)): break return (array, steps)
def combsort(array, scaling_factor): '\n combsort(array, scaling_factor) -> list\n \n array -> [list]: A list of elements to be sorted using combsort \n scaling_factor -> [float]: A scalar that reduces the size of the\n gap every sweep (>1)\n ' steps = 0 gap = len(array) while True: swapped = False gap = int((gap / scaling_factor)) for i in range((len(array) - gap)): if (array[i] > array[(i + gap)]): (array[(i + gap)], array[i]) = (array[i], array[(i + gap)]) swapped = True steps += 1 if ((not swapped) and (gap == 0)): break return (array, steps)<|docstring|>combsort(array, scaling_factor) -> list array -> [list]: A list of elements to be sorted using combsort scaling_factor -> [float]: A scalar that reduces the size of the gap every sweep (>1)<|endoftext|>
ec9ed4c25a5dac48d8c5a4e4fca72cedc2df110c7df8061ee8cc2bd1a2888e28
def check_user_compromised(self, epoch, pos, user_id): 'Check if the sampled user is compromised for the attack.\n\n If single_epoch_attack is defined (eg not None) then ignore\n :param epoch:\n :param pos:\n :param user_id:\n :return:\n ' accuracy_threshold = 90 compromised = False if (self.params.fl_single_epoch_attack is not None): if (self.params.fl_single_epoch_attack == 0): if ((self.metrics[0].get_value() == {}) or (self.metrics[0].get_main_metric_value() < accuracy_threshold)): compromised = (user_id in self.adversaries) else: logger.warning(f'Skipping attack once at epoch {epoch} as accuracy is higher than {accuracy_threshold}') elif (epoch == self.params.fl_single_epoch_attack): if (pos < self.params.fl_number_of_adversaries): compromised = True logger.warning(f'Attacking once at epoch {epoch}. Compromised user: {user_id}.') else: compromised = (user_id in self.adversaries) return compromised
Check if the sampled user is compromised for the attack. If single_epoch_attack is defined (eg not None) then ignore :param epoch: :param pos: :param user_id: :return:
tasks/fl/fl_task.py
check_user_compromised
wongyuanneng/FYP-Attacks-against-FL
2
python
def check_user_compromised(self, epoch, pos, user_id): 'Check if the sampled user is compromised for the attack.\n\n If single_epoch_attack is defined (eg not None) then ignore\n :param epoch:\n :param pos:\n :param user_id:\n :return:\n ' accuracy_threshold = 90 compromised = False if (self.params.fl_single_epoch_attack is not None): if (self.params.fl_single_epoch_attack == 0): if ((self.metrics[0].get_value() == {}) or (self.metrics[0].get_main_metric_value() < accuracy_threshold)): compromised = (user_id in self.adversaries) else: logger.warning(f'Skipping attack once at epoch {epoch} as accuracy is higher than {accuracy_threshold}') elif (epoch == self.params.fl_single_epoch_attack): if (pos < self.params.fl_number_of_adversaries): compromised = True logger.warning(f'Attacking once at epoch {epoch}. Compromised user: {user_id}.') else: compromised = (user_id in self.adversaries) return compromised
def check_user_compromised(self, epoch, pos, user_id): 'Check if the sampled user is compromised for the attack.\n\n If single_epoch_attack is defined (eg not None) then ignore\n :param epoch:\n :param pos:\n :param user_id:\n :return:\n ' accuracy_threshold = 90 compromised = False if (self.params.fl_single_epoch_attack is not None): if (self.params.fl_single_epoch_attack == 0): if ((self.metrics[0].get_value() == {}) or (self.metrics[0].get_main_metric_value() < accuracy_threshold)): compromised = (user_id in self.adversaries) else: logger.warning(f'Skipping attack once at epoch {epoch} as accuracy is higher than {accuracy_threshold}') elif (epoch == self.params.fl_single_epoch_attack): if (pos < self.params.fl_number_of_adversaries): compromised = True logger.warning(f'Attacking once at epoch {epoch}. Compromised user: {user_id}.') else: compromised = (user_id in self.adversaries) return compromised<|docstring|>Check if the sampled user is compromised for the attack. If single_epoch_attack is defined (eg not None) then ignore :param epoch: :param pos: :param user_id: :return:<|endoftext|>
b802ffc1cb13c6b3e59f5f9db5cf4a312c158b4b1364423c226f02778630fef8
def clip(text: str, max_len: int=80) -> str: 'Return new ``str`` clipped at last space before or after ``max_len``.\n Return full ``text`` if no space found.\n ' end = None if (len(text) > max_len): space_before = text.rfind(' ', 0, max_len) if (space_before >= 0): end = space_before else: space_after = text.rfind(' ', max_len) if (space_after >= 0): end = space_after if (end is None): end = len(text) return text[:end].rstrip()
Return new ``str`` clipped at last space before or after ``max_len``. Return full ``text`` if no space found.
15-more-types/clip_annot.py
clip
p-j-smith/example-code-2e
990
python
def clip(text: str, max_len: int=80) -> str: 'Return new ``str`` clipped at last space before or after ``max_len``.\n Return full ``text`` if no space found.\n ' end = None if (len(text) > max_len): space_before = text.rfind(' ', 0, max_len) if (space_before >= 0): end = space_before else: space_after = text.rfind(' ', max_len) if (space_after >= 0): end = space_after if (end is None): end = len(text) return text[:end].rstrip()
def clip(text: str, max_len: int=80) -> str: 'Return new ``str`` clipped at last space before or after ``max_len``.\n Return full ``text`` if no space found.\n ' end = None if (len(text) > max_len): space_before = text.rfind(' ', 0, max_len) if (space_before >= 0): end = space_before else: space_after = text.rfind(' ', max_len) if (space_after >= 0): end = space_after if (end is None): end = len(text) return text[:end].rstrip()<|docstring|>Return new ``str`` clipped at last space before or after ``max_len``. Return full ``text`` if no space found.<|endoftext|>
05aba081cb12e1289b239ed08f2f7e8b87e155896a7f03e42c6d471494162ae3
def circ2buckets(qubit_count, circuit, pdict={}, max_depth=None): "\n Takes a circuit in the form of list of lists, builds\n corresponding buckets. Buckets contain Tensors\n defining quantum gates. Each bucket\n corresponds to a variable. Each bucket can hold tensors\n acting on it's variable and variables with higher index.\n\n Parameters\n ----------\n qubit_count : int\n number of qubits in the circuit\n circuit : list of lists\n quantum circuit as returned by\n :py:meth:`operators.read_circuit_file`\n pdict : dict\n Dictionary with placeholders if any parameteric gates\n were unresolved\n\n max_depth : int\n Maximal depth of the circuit which should be used\n Returns\n -------\n buckets : list of lists\n list of lists (buckets)\n data_dict : dict\n Dictionary with all tensor data\n bra_variables : list\n variables of the output qubits\n ket_variables: list\n variables of the input qubits\n " if (max_depth is None): max_depth = len(circuit) data_dict = {} layer_variables = [Var(qubit, name=f'o_{qubit}') for qubit in range(qubit_count)] current_var_idx = qubit_count bra_variables = [var for var in layer_variables] for qubit in range(qubit_count): buckets = [[] for qubit in range(qubit_count)] measurement_circ = [[ops.M(qubit) for qubit in range(qubit_count)]] combined_circ = functools.reduce((lambda x, y: itertools.chain(x, y)), [measurement_circ, reversed(circuit[:max_depth])]) for layer in combined_circ: for op in layer: variables = [] current_var_idx_copy = current_var_idx min_var_idx = current_var_idx for qubit in op.qubits: if (qubit in op.changed_qubits): variables.extend([layer_variables[qubit], Var(current_var_idx_copy)]) current_var_idx_copy += 1 else: variables.extend([layer_variables[qubit]]) min_var_idx = min(min_var_idx, int(layer_variables[qubit])) for (par, value) in op.parameters.items(): if isinstance(value, ops.placeholder): op._parameters[par] = pdict[value] data_key = (op.name, hash((op.name, tuple(op.parameters.items())))) t = Tensor(op.name, variables, data_key=data_key) data_dict[data_key] = op.gen_tensor() buckets[min_var_idx].append(t) for qubit in op.changed_qubits: layer_variables[qubit] = Var(current_var_idx) buckets.append([]) current_var_idx += 1 ket_variables = [] op = ops.M(0) data_key = (op.name, hash((op.name, tuple(op.parameters.items())))) data_dict.update({data_key: op.gen_tensor()}) for qubit in range(qubit_count): var = layer_variables[qubit] new_var = Var(current_var_idx, name=f'i_{qubit}', size=2) ket_variables.append(new_var) buckets[int(var)].append(Tensor(op.name, indices=[var, new_var], data_key=data_key)) buckets.append([]) layer_variables[qubit] = new_var current_var_idx += 1 return (buckets, data_dict, bra_variables, ket_variables)
Takes a circuit in the form of list of lists, builds corresponding buckets. Buckets contain Tensors defining quantum gates. Each bucket corresponds to a variable. Each bucket can hold tensors acting on it's variable and variables with higher index. Parameters ---------- qubit_count : int number of qubits in the circuit circuit : list of lists quantum circuit as returned by :py:meth:`operators.read_circuit_file` pdict : dict Dictionary with placeholders if any parameteric gates were unresolved max_depth : int Maximal depth of the circuit which should be used Returns ------- buckets : list of lists list of lists (buckets) data_dict : dict Dictionary with all tensor data bra_variables : list variables of the output qubits ket_variables: list variables of the input qubits
qtree/optimizer.py
circ2buckets
Huawei-HiQ/qtree
1
python
def circ2buckets(qubit_count, circuit, pdict={}, max_depth=None): "\n Takes a circuit in the form of list of lists, builds\n corresponding buckets. Buckets contain Tensors\n defining quantum gates. Each bucket\n corresponds to a variable. Each bucket can hold tensors\n acting on it's variable and variables with higher index.\n\n Parameters\n ----------\n qubit_count : int\n number of qubits in the circuit\n circuit : list of lists\n quantum circuit as returned by\n :py:meth:`operators.read_circuit_file`\n pdict : dict\n Dictionary with placeholders if any parameteric gates\n were unresolved\n\n max_depth : int\n Maximal depth of the circuit which should be used\n Returns\n -------\n buckets : list of lists\n list of lists (buckets)\n data_dict : dict\n Dictionary with all tensor data\n bra_variables : list\n variables of the output qubits\n ket_variables: list\n variables of the input qubits\n " if (max_depth is None): max_depth = len(circuit) data_dict = {} layer_variables = [Var(qubit, name=f'o_{qubit}') for qubit in range(qubit_count)] current_var_idx = qubit_count bra_variables = [var for var in layer_variables] for qubit in range(qubit_count): buckets = [[] for qubit in range(qubit_count)] measurement_circ = [[ops.M(qubit) for qubit in range(qubit_count)]] combined_circ = functools.reduce((lambda x, y: itertools.chain(x, y)), [measurement_circ, reversed(circuit[:max_depth])]) for layer in combined_circ: for op in layer: variables = [] current_var_idx_copy = current_var_idx min_var_idx = current_var_idx for qubit in op.qubits: if (qubit in op.changed_qubits): variables.extend([layer_variables[qubit], Var(current_var_idx_copy)]) current_var_idx_copy += 1 else: variables.extend([layer_variables[qubit]]) min_var_idx = min(min_var_idx, int(layer_variables[qubit])) for (par, value) in op.parameters.items(): if isinstance(value, ops.placeholder): op._parameters[par] = pdict[value] data_key = (op.name, hash((op.name, tuple(op.parameters.items())))) t = Tensor(op.name, variables, data_key=data_key) data_dict[data_key] = op.gen_tensor() buckets[min_var_idx].append(t) for qubit in op.changed_qubits: layer_variables[qubit] = Var(current_var_idx) buckets.append([]) current_var_idx += 1 ket_variables = [] op = ops.M(0) data_key = (op.name, hash((op.name, tuple(op.parameters.items())))) data_dict.update({data_key: op.gen_tensor()}) for qubit in range(qubit_count): var = layer_variables[qubit] new_var = Var(current_var_idx, name=f'i_{qubit}', size=2) ket_variables.append(new_var) buckets[int(var)].append(Tensor(op.name, indices=[var, new_var], data_key=data_key)) buckets.append([]) layer_variables[qubit] = new_var current_var_idx += 1 return (buckets, data_dict, bra_variables, ket_variables)
def circ2buckets(qubit_count, circuit, pdict={}, max_depth=None): "\n Takes a circuit in the form of list of lists, builds\n corresponding buckets. Buckets contain Tensors\n defining quantum gates. Each bucket\n corresponds to a variable. Each bucket can hold tensors\n acting on it's variable and variables with higher index.\n\n Parameters\n ----------\n qubit_count : int\n number of qubits in the circuit\n circuit : list of lists\n quantum circuit as returned by\n :py:meth:`operators.read_circuit_file`\n pdict : dict\n Dictionary with placeholders if any parameteric gates\n were unresolved\n\n max_depth : int\n Maximal depth of the circuit which should be used\n Returns\n -------\n buckets : list of lists\n list of lists (buckets)\n data_dict : dict\n Dictionary with all tensor data\n bra_variables : list\n variables of the output qubits\n ket_variables: list\n variables of the input qubits\n " if (max_depth is None): max_depth = len(circuit) data_dict = {} layer_variables = [Var(qubit, name=f'o_{qubit}') for qubit in range(qubit_count)] current_var_idx = qubit_count bra_variables = [var for var in layer_variables] for qubit in range(qubit_count): buckets = [[] for qubit in range(qubit_count)] measurement_circ = [[ops.M(qubit) for qubit in range(qubit_count)]] combined_circ = functools.reduce((lambda x, y: itertools.chain(x, y)), [measurement_circ, reversed(circuit[:max_depth])]) for layer in combined_circ: for op in layer: variables = [] current_var_idx_copy = current_var_idx min_var_idx = current_var_idx for qubit in op.qubits: if (qubit in op.changed_qubits): variables.extend([layer_variables[qubit], Var(current_var_idx_copy)]) current_var_idx_copy += 1 else: variables.extend([layer_variables[qubit]]) min_var_idx = min(min_var_idx, int(layer_variables[qubit])) for (par, value) in op.parameters.items(): if isinstance(value, ops.placeholder): op._parameters[par] = pdict[value] data_key = (op.name, hash((op.name, tuple(op.parameters.items())))) t = Tensor(op.name, variables, data_key=data_key) data_dict[data_key] = op.gen_tensor() buckets[min_var_idx].append(t) for qubit in op.changed_qubits: layer_variables[qubit] = Var(current_var_idx) buckets.append([]) current_var_idx += 1 ket_variables = [] op = ops.M(0) data_key = (op.name, hash((op.name, tuple(op.parameters.items())))) data_dict.update({data_key: op.gen_tensor()}) for qubit in range(qubit_count): var = layer_variables[qubit] new_var = Var(current_var_idx, name=f'i_{qubit}', size=2) ket_variables.append(new_var) buckets[int(var)].append(Tensor(op.name, indices=[var, new_var], data_key=data_key)) buckets.append([]) layer_variables[qubit] = new_var current_var_idx += 1 return (buckets, data_dict, bra_variables, ket_variables)<|docstring|>Takes a circuit in the form of list of lists, builds corresponding buckets. Buckets contain Tensors defining quantum gates. Each bucket corresponds to a variable. Each bucket can hold tensors acting on it's variable and variables with higher index. Parameters ---------- qubit_count : int number of qubits in the circuit circuit : list of lists quantum circuit as returned by :py:meth:`operators.read_circuit_file` pdict : dict Dictionary with placeholders if any parameteric gates were unresolved max_depth : int Maximal depth of the circuit which should be used Returns ------- buckets : list of lists list of lists (buckets) data_dict : dict Dictionary with all tensor data bra_variables : list variables of the output qubits ket_variables: list variables of the input qubits<|endoftext|>
bbe895039659a15018bbc8c1d182e2a3e34f3d39d973b2a9defe2e3f40bf267b
def bucket_elimination(buckets, process_bucket_fn, n_var_nosum=0): '\n Algorithm to evaluate a contraction of a large number of tensors.\n The variables to contract over are assigned ``buckets`` which\n hold tensors having respective variables. The algorithm\n proceeds through contracting one variable at a time, thus we eliminate\n buckets one by one.\n\n Parameters\n ----------\n buckets : list of lists\n process_bucket_fn : function\n function that will process this kind of buckets\n n_var_nosum : int, optional\n number of variables that have to be left in the\n result. Expected at the end of bucket list\n Returns\n -------\n result : numpy.array\n ' n_var_contract = (len(buckets) - n_var_nosum) result = None for (n, bucket) in enumerate(buckets[:n_var_contract]): if (len(bucket) > 0): tensor = process_bucket_fn(bucket) if (len(tensor.indices) > 0): first_index = int(tensor.indices[0]) buckets[first_index].append(tensor) elif (result is not None): result *= tensor else: result = tensor rest = list(itertools.chain.from_iterable(buckets[n_var_contract:])) if (len(rest) > 0): tensor = process_bucket_fn(rest, no_sum=True) if (result is not None): result *= tensor else: result = tensor return result
Algorithm to evaluate a contraction of a large number of tensors. The variables to contract over are assigned ``buckets`` which hold tensors having respective variables. The algorithm proceeds through contracting one variable at a time, thus we eliminate buckets one by one. Parameters ---------- buckets : list of lists process_bucket_fn : function function that will process this kind of buckets n_var_nosum : int, optional number of variables that have to be left in the result. Expected at the end of bucket list Returns ------- result : numpy.array
qtree/optimizer.py
bucket_elimination
Huawei-HiQ/qtree
1
python
def bucket_elimination(buckets, process_bucket_fn, n_var_nosum=0): '\n Algorithm to evaluate a contraction of a large number of tensors.\n The variables to contract over are assigned ``buckets`` which\n hold tensors having respective variables. The algorithm\n proceeds through contracting one variable at a time, thus we eliminate\n buckets one by one.\n\n Parameters\n ----------\n buckets : list of lists\n process_bucket_fn : function\n function that will process this kind of buckets\n n_var_nosum : int, optional\n number of variables that have to be left in the\n result. Expected at the end of bucket list\n Returns\n -------\n result : numpy.array\n ' n_var_contract = (len(buckets) - n_var_nosum) result = None for (n, bucket) in enumerate(buckets[:n_var_contract]): if (len(bucket) > 0): tensor = process_bucket_fn(bucket) if (len(tensor.indices) > 0): first_index = int(tensor.indices[0]) buckets[first_index].append(tensor) elif (result is not None): result *= tensor else: result = tensor rest = list(itertools.chain.from_iterable(buckets[n_var_contract:])) if (len(rest) > 0): tensor = process_bucket_fn(rest, no_sum=True) if (result is not None): result *= tensor else: result = tensor return result
def bucket_elimination(buckets, process_bucket_fn, n_var_nosum=0): '\n Algorithm to evaluate a contraction of a large number of tensors.\n The variables to contract over are assigned ``buckets`` which\n hold tensors having respective variables. The algorithm\n proceeds through contracting one variable at a time, thus we eliminate\n buckets one by one.\n\n Parameters\n ----------\n buckets : list of lists\n process_bucket_fn : function\n function that will process this kind of buckets\n n_var_nosum : int, optional\n number of variables that have to be left in the\n result. Expected at the end of bucket list\n Returns\n -------\n result : numpy.array\n ' n_var_contract = (len(buckets) - n_var_nosum) result = None for (n, bucket) in enumerate(buckets[:n_var_contract]): if (len(bucket) > 0): tensor = process_bucket_fn(bucket) if (len(tensor.indices) > 0): first_index = int(tensor.indices[0]) buckets[first_index].append(tensor) elif (result is not None): result *= tensor else: result = tensor rest = list(itertools.chain.from_iterable(buckets[n_var_contract:])) if (len(rest) > 0): tensor = process_bucket_fn(rest, no_sum=True) if (result is not None): result *= tensor else: result = tensor return result<|docstring|>Algorithm to evaluate a contraction of a large number of tensors. The variables to contract over are assigned ``buckets`` which hold tensors having respective variables. The algorithm proceeds through contracting one variable at a time, thus we eliminate buckets one by one. Parameters ---------- buckets : list of lists process_bucket_fn : function function that will process this kind of buckets n_var_nosum : int, optional number of variables that have to be left in the result. Expected at the end of bucket list Returns ------- result : numpy.array<|endoftext|>
f4ac1caf59991abda25d03db890754c10e97d16795a4b6313310ad07e6bcac59
def graph2buckets(graph): '\n Takes a Networkx MultiGraph and produces a corresponding\n bucket list. This is an inverse of the :py:meth:`buckets2graph`\n\n Parameters\n ----------\n graph : networkx.MultiGraph\n contraction graph of the circuit. Has to support self loops\n and parallel edges. Parallel edges are needed to support\n multiple qubit operators on same qubits\n (which can be collapsed in one operation)\n\n Returns\n -------\n buckets : list of lists\n ' buckets = [] variables = sorted(graph.nodes(data=False)) for variable in variables: candidate_tensors = {} for edge in graph.edges(variables, data=True): (_, other_variable, edge_data) = edge tensor = edge_data['tensor'] key = (tensor['name'], tensor['indices'], tensor['data_key']) if (key not in candidate_tensors): indices_vars = tuple((Var(var, name=graph.nodes[var]['name'], size=graph.nodes[var]['size']) for var in tensor['indices'])) candidate_tensors[key] = Tensor(name=tensor['name'], indices=indices_vars, data_key=tensor['data_key']) bucket = [] for (key, tensor) in candidate_tensors.items(): sorted_tensor_indices = list(sorted(tensor.indices, key=int)) if (int(sorted_tensor_indices[0]) == variable): bucket.append(tensor) buckets.append(bucket) return buckets
Takes a Networkx MultiGraph and produces a corresponding bucket list. This is an inverse of the :py:meth:`buckets2graph` Parameters ---------- graph : networkx.MultiGraph contraction graph of the circuit. Has to support self loops and parallel edges. Parallel edges are needed to support multiple qubit operators on same qubits (which can be collapsed in one operation) Returns ------- buckets : list of lists
qtree/optimizer.py
graph2buckets
Huawei-HiQ/qtree
1
python
def graph2buckets(graph): '\n Takes a Networkx MultiGraph and produces a corresponding\n bucket list. This is an inverse of the :py:meth:`buckets2graph`\n\n Parameters\n ----------\n graph : networkx.MultiGraph\n contraction graph of the circuit. Has to support self loops\n and parallel edges. Parallel edges are needed to support\n multiple qubit operators on same qubits\n (which can be collapsed in one operation)\n\n Returns\n -------\n buckets : list of lists\n ' buckets = [] variables = sorted(graph.nodes(data=False)) for variable in variables: candidate_tensors = {} for edge in graph.edges(variables, data=True): (_, other_variable, edge_data) = edge tensor = edge_data['tensor'] key = (tensor['name'], tensor['indices'], tensor['data_key']) if (key not in candidate_tensors): indices_vars = tuple((Var(var, name=graph.nodes[var]['name'], size=graph.nodes[var]['size']) for var in tensor['indices'])) candidate_tensors[key] = Tensor(name=tensor['name'], indices=indices_vars, data_key=tensor['data_key']) bucket = [] for (key, tensor) in candidate_tensors.items(): sorted_tensor_indices = list(sorted(tensor.indices, key=int)) if (int(sorted_tensor_indices[0]) == variable): bucket.append(tensor) buckets.append(bucket) return buckets
def graph2buckets(graph): '\n Takes a Networkx MultiGraph and produces a corresponding\n bucket list. This is an inverse of the :py:meth:`buckets2graph`\n\n Parameters\n ----------\n graph : networkx.MultiGraph\n contraction graph of the circuit. Has to support self loops\n and parallel edges. Parallel edges are needed to support\n multiple qubit operators on same qubits\n (which can be collapsed in one operation)\n\n Returns\n -------\n buckets : list of lists\n ' buckets = [] variables = sorted(graph.nodes(data=False)) for variable in variables: candidate_tensors = {} for edge in graph.edges(variables, data=True): (_, other_variable, edge_data) = edge tensor = edge_data['tensor'] key = (tensor['name'], tensor['indices'], tensor['data_key']) if (key not in candidate_tensors): indices_vars = tuple((Var(var, name=graph.nodes[var]['name'], size=graph.nodes[var]['size']) for var in tensor['indices'])) candidate_tensors[key] = Tensor(name=tensor['name'], indices=indices_vars, data_key=tensor['data_key']) bucket = [] for (key, tensor) in candidate_tensors.items(): sorted_tensor_indices = list(sorted(tensor.indices, key=int)) if (int(sorted_tensor_indices[0]) == variable): bucket.append(tensor) buckets.append(bucket) return buckets<|docstring|>Takes a Networkx MultiGraph and produces a corresponding bucket list. This is an inverse of the :py:meth:`buckets2graph` Parameters ---------- graph : networkx.MultiGraph contraction graph of the circuit. Has to support self loops and parallel edges. Parallel edges are needed to support multiple qubit operators on same qubits (which can be collapsed in one operation) Returns ------- buckets : list of lists<|endoftext|>
f1ed768417060a7add3d04c99b342f8ed0efbc32e23b0a5f04d88ac7a3778d26
def reorder_buckets(old_buckets, permutation): '\n Transforms bucket list according to the new order given by\n permutation. The variables are renamed and buckets are reordered\n to hold only gates acting on variables with strongly increasing\n index.\n\n Parameters\n ----------\n old_buckets : list of lists\n old buckets\n permutation : list\n permutation of variables\n\n Returns\n -------\n new_buckets : list of lists\n buckets reordered according to permutation\n label_dict : dict\n dictionary of new variable objects\n (as IDs of variables have been changed after reordering)\n in the form {old: new}\n ' if (len(old_buckets) != len(permutation)): raise ValueError('Wrong permutation: len(permutation) != len(buckets)') perm_dict = {} for (n, idx) in enumerate(permutation): if idx.name.startswith('v'): perm_dict[idx] = idx.copy(n) else: perm_dict[idx] = idx.copy(n, name=idx.name) n_variables = len(old_buckets) new_buckets = [] for ii in range(n_variables): new_buckets.append([]) for bucket in old_buckets: for tensor in bucket: new_indices = [perm_dict[idx] for idx in tensor.indices] bucket_idx = sorted(new_indices, key=int)[0].identity new_buckets[bucket_idx].append(tensor.copy(indices=new_indices)) return (new_buckets, perm_dict)
Transforms bucket list according to the new order given by permutation. The variables are renamed and buckets are reordered to hold only gates acting on variables with strongly increasing index. Parameters ---------- old_buckets : list of lists old buckets permutation : list permutation of variables Returns ------- new_buckets : list of lists buckets reordered according to permutation label_dict : dict dictionary of new variable objects (as IDs of variables have been changed after reordering) in the form {old: new}
qtree/optimizer.py
reorder_buckets
Huawei-HiQ/qtree
1
python
def reorder_buckets(old_buckets, permutation): '\n Transforms bucket list according to the new order given by\n permutation. The variables are renamed and buckets are reordered\n to hold only gates acting on variables with strongly increasing\n index.\n\n Parameters\n ----------\n old_buckets : list of lists\n old buckets\n permutation : list\n permutation of variables\n\n Returns\n -------\n new_buckets : list of lists\n buckets reordered according to permutation\n label_dict : dict\n dictionary of new variable objects\n (as IDs of variables have been changed after reordering)\n in the form {old: new}\n ' if (len(old_buckets) != len(permutation)): raise ValueError('Wrong permutation: len(permutation) != len(buckets)') perm_dict = {} for (n, idx) in enumerate(permutation): if idx.name.startswith('v'): perm_dict[idx] = idx.copy(n) else: perm_dict[idx] = idx.copy(n, name=idx.name) n_variables = len(old_buckets) new_buckets = [] for ii in range(n_variables): new_buckets.append([]) for bucket in old_buckets: for tensor in bucket: new_indices = [perm_dict[idx] for idx in tensor.indices] bucket_idx = sorted(new_indices, key=int)[0].identity new_buckets[bucket_idx].append(tensor.copy(indices=new_indices)) return (new_buckets, perm_dict)
def reorder_buckets(old_buckets, permutation): '\n Transforms bucket list according to the new order given by\n permutation. The variables are renamed and buckets are reordered\n to hold only gates acting on variables with strongly increasing\n index.\n\n Parameters\n ----------\n old_buckets : list of lists\n old buckets\n permutation : list\n permutation of variables\n\n Returns\n -------\n new_buckets : list of lists\n buckets reordered according to permutation\n label_dict : dict\n dictionary of new variable objects\n (as IDs of variables have been changed after reordering)\n in the form {old: new}\n ' if (len(old_buckets) != len(permutation)): raise ValueError('Wrong permutation: len(permutation) != len(buckets)') perm_dict = {} for (n, idx) in enumerate(permutation): if idx.name.startswith('v'): perm_dict[idx] = idx.copy(n) else: perm_dict[idx] = idx.copy(n, name=idx.name) n_variables = len(old_buckets) new_buckets = [] for ii in range(n_variables): new_buckets.append([]) for bucket in old_buckets: for tensor in bucket: new_indices = [perm_dict[idx] for idx in tensor.indices] bucket_idx = sorted(new_indices, key=int)[0].identity new_buckets[bucket_idx].append(tensor.copy(indices=new_indices)) return (new_buckets, perm_dict)<|docstring|>Transforms bucket list according to the new order given by permutation. The variables are renamed and buckets are reordered to hold only gates acting on variables with strongly increasing index. Parameters ---------- old_buckets : list of lists old buckets permutation : list permutation of variables Returns ------- new_buckets : list of lists buckets reordered according to permutation label_dict : dict dictionary of new variable objects (as IDs of variables have been changed after reordering) in the form {old: new}<|endoftext|>
efebf8b730d9ccc478bd47d70e00a8161a9440df62093e605b1ee66d609e2e29
def test_bucket_graph_conversion(filename): '\n Test the conversion between Buckets and the contraction multigraph\n ' import qtree.graph_model as gm (n_qubits, circuit) = ops.read_circuit_file(filename) (buckets, data_dict, bra_vars, ket_vars) = circ2buckets(n_qubits, circuit) (graph, *_) = gm.importers.circ2graph(n_qubits, circuit, omit_terminals=False) graph_from_buckets = gm.importers.buckets2graph(buckets) buckets_from_graph = graph2buckets(graph) buckets_equal = True for (b1, b2) in zip(buckets, buckets_from_graph): if (sorted(b1) != sorted(b2)): buckets_equal = False break print('C->B, C->G->B: Buckets equal? : {}'.format(buckets_equal)) print('C->G, C->B->G: Graphs equal? : {}'.format(nx.is_isomorphic(graph, graph_from_buckets)))
Test the conversion between Buckets and the contraction multigraph
qtree/optimizer.py
test_bucket_graph_conversion
Huawei-HiQ/qtree
1
python
def test_bucket_graph_conversion(filename): '\n \n ' import qtree.graph_model as gm (n_qubits, circuit) = ops.read_circuit_file(filename) (buckets, data_dict, bra_vars, ket_vars) = circ2buckets(n_qubits, circuit) (graph, *_) = gm.importers.circ2graph(n_qubits, circuit, omit_terminals=False) graph_from_buckets = gm.importers.buckets2graph(buckets) buckets_from_graph = graph2buckets(graph) buckets_equal = True for (b1, b2) in zip(buckets, buckets_from_graph): if (sorted(b1) != sorted(b2)): buckets_equal = False break print('C->B, C->G->B: Buckets equal? : {}'.format(buckets_equal)) print('C->G, C->B->G: Graphs equal? : {}'.format(nx.is_isomorphic(graph, graph_from_buckets)))
def test_bucket_graph_conversion(filename): '\n \n ' import qtree.graph_model as gm (n_qubits, circuit) = ops.read_circuit_file(filename) (buckets, data_dict, bra_vars, ket_vars) = circ2buckets(n_qubits, circuit) (graph, *_) = gm.importers.circ2graph(n_qubits, circuit, omit_terminals=False) graph_from_buckets = gm.importers.buckets2graph(buckets) buckets_from_graph = graph2buckets(graph) buckets_equal = True for (b1, b2) in zip(buckets, buckets_from_graph): if (sorted(b1) != sorted(b2)): buckets_equal = False break print('C->B, C->G->B: Buckets equal? : {}'.format(buckets_equal)) print('C->G, C->B->G: Graphs equal? : {}'.format(nx.is_isomorphic(graph, graph_from_buckets)))<|docstring|>Test the conversion between Buckets and the contraction multigraph<|endoftext|>
1e2f8e79da9d33c8ef0f183f17a14fd5117ab2dfe9118719166a43349ba44d63
def __init__(self, identity, size=2, name=None): '\n Initialize the variable\n identity: int\n Index identifier. We use mainly integers here to\n make it play nicely with graphical models.\n size: int, optional\n Size of the index. Default 2\n name: str, optional\n Optional name tag. Defaults to "v[{identity}]"\n ' self._identity = identity self._size = size if (name is None): name = f'v_{identity}' self._name = name self.__hash = hash((identity, name, size))
Initialize the variable identity: int Index identifier. We use mainly integers here to make it play nicely with graphical models. size: int, optional Size of the index. Default 2 name: str, optional Optional name tag. Defaults to "v[{identity}]"
qtree/optimizer.py
__init__
Huawei-HiQ/qtree
1
python
def __init__(self, identity, size=2, name=None): '\n Initialize the variable\n identity: int\n Index identifier. We use mainly integers here to\n make it play nicely with graphical models.\n size: int, optional\n Size of the index. Default 2\n name: str, optional\n Optional name tag. Defaults to "v[{identity}]"\n ' self._identity = identity self._size = size if (name is None): name = f'v_{identity}' self._name = name self.__hash = hash((identity, name, size))
def __init__(self, identity, size=2, name=None): '\n Initialize the variable\n identity: int\n Index identifier. We use mainly integers here to\n make it play nicely with graphical models.\n size: int, optional\n Size of the index. Default 2\n name: str, optional\n Optional name tag. Defaults to "v[{identity}]"\n ' self._identity = identity self._size = size if (name is None): name = f'v_{identity}' self._name = name self.__hash = hash((identity, name, size))<|docstring|>Initialize the variable identity: int Index identifier. We use mainly integers here to make it play nicely with graphical models. size: int, optional Size of the index. Default 2 name: str, optional Optional name tag. Defaults to "v[{identity}]"<|endoftext|>
517287e6924de7c91aefde201939f85158218d2060d09ad11c58693812d3d9b2
def __init__(self, name, indices, data_key=None, data=None): "\n Initialize the tensor\n name: str,\n the name of the tensor. Used only for display/convenience.\n May be not unique.\n indices: tuple,\n Indices of the tensor\n shape: tuple,\n shape of a tensor\n data_key: int\n Key to find tensor's data in the global storage\n data: np.array\n Actual data of the tensor. Default None.\n Usually is not supplied at initialization.\n " self._name = name self._indices = tuple(indices) self._data_key = data_key self._data = data self._order_key = hash((self.data_key, self.name))
Initialize the tensor name: str, the name of the tensor. Used only for display/convenience. May be not unique. indices: tuple, Indices of the tensor shape: tuple, shape of a tensor data_key: int Key to find tensor's data in the global storage data: np.array Actual data of the tensor. Default None. Usually is not supplied at initialization.
qtree/optimizer.py
__init__
Huawei-HiQ/qtree
1
python
def __init__(self, name, indices, data_key=None, data=None): "\n Initialize the tensor\n name: str,\n the name of the tensor. Used only for display/convenience.\n May be not unique.\n indices: tuple,\n Indices of the tensor\n shape: tuple,\n shape of a tensor\n data_key: int\n Key to find tensor's data in the global storage\n data: np.array\n Actual data of the tensor. Default None.\n Usually is not supplied at initialization.\n " self._name = name self._indices = tuple(indices) self._data_key = data_key self._data = data self._order_key = hash((self.data_key, self.name))
def __init__(self, name, indices, data_key=None, data=None): "\n Initialize the tensor\n name: str,\n the name of the tensor. Used only for display/convenience.\n May be not unique.\n indices: tuple,\n Indices of the tensor\n shape: tuple,\n shape of a tensor\n data_key: int\n Key to find tensor's data in the global storage\n data: np.array\n Actual data of the tensor. Default None.\n Usually is not supplied at initialization.\n " self._name = name self._indices = tuple(indices) self._data_key = data_key self._data = data self._order_key = hash((self.data_key, self.name))<|docstring|>Initialize the tensor name: str, the name of the tensor. Used only for display/convenience. May be not unique. indices: tuple, Indices of the tensor shape: tuple, shape of a tensor data_key: int Key to find tensor's data in the global storage data: np.array Actual data of the tensor. Default None. Usually is not supplied at initialization.<|endoftext|>
4c0b81c240b4173c1030341dd30aa9c6c05d7c10863cfa858a2351fd130377a1
def make_phone_masks(length, resample, num_frames_per_utt): 'Randomly select frames for each utterance.\n\n Args:\n length: The length of each utterance.\n resample: If 0, return the beginning frame; otherwise random select a frame.\n resample is designed to try to make every frame has the same probability to be sampled.\n num_frames_per_utt: #frames selected. if -1, then select all frames\n :return: a mat with [n_selected_frames, 2], each row is the index of the selected frame\n ' n_utts = length.shape[0] if (num_frames_per_utt == (- 1)): mat = [] for i in range(n_utts): for j in range(length[i]): mat.append([i, j]) mat = np.array(mat, dtype=np.int32) else: mat = np.zeros(((length.shape[0] * num_frames_per_utt), 2), dtype=np.int32) for i in range(n_utts): mat[((i * num_frames_per_utt):((i + 1) * num_frames_per_utt), 0)] = i tmp = [] for _ in range(num_frames_per_utt): while True: a = np.random.randint(0, length[i], dtype=np.int32) if (a not in tmp): tmp.append(a) break mat[((i * num_frames_per_utt):((i + 1) * num_frames_per_utt), 1)] = tmp return mat
Randomly select frames for each utterance. Args: length: The length of each utterance. resample: If 0, return the beginning frame; otherwise random select a frame. resample is designed to try to make every frame has the same probability to be sampled. num_frames_per_utt: #frames selected. if -1, then select all frames :return: a mat with [n_selected_frames, 2], each row is the index of the selected frame
model/multitask_v1/common.py
make_phone_masks
LCF2764/tf-kaldi-speaker
154
python
def make_phone_masks(length, resample, num_frames_per_utt): 'Randomly select frames for each utterance.\n\n Args:\n length: The length of each utterance.\n resample: If 0, return the beginning frame; otherwise random select a frame.\n resample is designed to try to make every frame has the same probability to be sampled.\n num_frames_per_utt: #frames selected. if -1, then select all frames\n :return: a mat with [n_selected_frames, 2], each row is the index of the selected frame\n ' n_utts = length.shape[0] if (num_frames_per_utt == (- 1)): mat = [] for i in range(n_utts): for j in range(length[i]): mat.append([i, j]) mat = np.array(mat, dtype=np.int32) else: mat = np.zeros(((length.shape[0] * num_frames_per_utt), 2), dtype=np.int32) for i in range(n_utts): mat[((i * num_frames_per_utt):((i + 1) * num_frames_per_utt), 0)] = i tmp = [] for _ in range(num_frames_per_utt): while True: a = np.random.randint(0, length[i], dtype=np.int32) if (a not in tmp): tmp.append(a) break mat[((i * num_frames_per_utt):((i + 1) * num_frames_per_utt), 1)] = tmp return mat
def make_phone_masks(length, resample, num_frames_per_utt): 'Randomly select frames for each utterance.\n\n Args:\n length: The length of each utterance.\n resample: If 0, return the beginning frame; otherwise random select a frame.\n resample is designed to try to make every frame has the same probability to be sampled.\n num_frames_per_utt: #frames selected. if -1, then select all frames\n :return: a mat with [n_selected_frames, 2], each row is the index of the selected frame\n ' n_utts = length.shape[0] if (num_frames_per_utt == (- 1)): mat = [] for i in range(n_utts): for j in range(length[i]): mat.append([i, j]) mat = np.array(mat, dtype=np.int32) else: mat = np.zeros(((length.shape[0] * num_frames_per_utt), 2), dtype=np.int32) for i in range(n_utts): mat[((i * num_frames_per_utt):((i + 1) * num_frames_per_utt), 0)] = i tmp = [] for _ in range(num_frames_per_utt): while True: a = np.random.randint(0, length[i], dtype=np.int32) if (a not in tmp): tmp.append(a) break mat[((i * num_frames_per_utt):((i + 1) * num_frames_per_utt), 1)] = tmp return mat<|docstring|>Randomly select frames for each utterance. Args: length: The length of each utterance. resample: If 0, return the beginning frame; otherwise random select a frame. resample is designed to try to make every frame has the same probability to be sampled. num_frames_per_utt: #frames selected. if -1, then select all frames :return: a mat with [n_selected_frames, 2], each row is the index of the selected frame<|endoftext|>
a97239dfc965190724a051cf15c26533f84cafa3f9702049d80ed6d8d73764cb
def __init__(self, config) -> None: 'Store local reference to device config.' self.config = config self.params = None self.ports = None self.users = None
Store local reference to device config.
src/vapyx/vapix.py
__init__
sthysel/vapyx
0
python
def __init__(self, config) -> None: self.config = config self.params = None self.ports = None self.users = None
def __init__(self, config) -> None: self.config = config self.params = None self.ports = None self.users = None<|docstring|>Store local reference to device config.<|endoftext|>
da856bef2be6ad30caa29268ff4719a97ba972c6a23d00f4e16bf157d6f03dc3
def initialize_params(self, preload_data=True) -> None: '\n Load device parameters and initialize parameter management.\n Preload data can be disabled to selectively load params afterwards.\n ' params = '' if preload_data: params = self.request('get', param_url) self.params = Params(params, self.request)
Load device parameters and initialize parameter management. Preload data can be disabled to selectively load params afterwards.
src/vapyx/vapix.py
initialize_params
sthysel/vapyx
0
python
def initialize_params(self, preload_data=True) -> None: '\n Load device parameters and initialize parameter management.\n Preload data can be disabled to selectively load params afterwards.\n ' params = if preload_data: params = self.request('get', param_url) self.params = Params(params, self.request)
def initialize_params(self, preload_data=True) -> None: '\n Load device parameters and initialize parameter management.\n Preload data can be disabled to selectively load params afterwards.\n ' params = if preload_data: params = self.request('get', param_url) self.params = Params(params, self.request)<|docstring|>Load device parameters and initialize parameter management. Preload data can be disabled to selectively load params afterwards.<|endoftext|>
f63a2729ef2bd45a62a88d65d83b479a21e478f9e3ac5713d7db761450997092
def initialize_ports(self) -> None: 'Load IO port parameters for device' if (not self.params): self.initialize_params(preload_data=False) self.params.update_ports() self.ports = Ports(self.params, self.request)
Load IO port parameters for device
src/vapyx/vapix.py
initialize_ports
sthysel/vapyx
0
python
def initialize_ports(self) -> None: if (not self.params): self.initialize_params(preload_data=False) self.params.update_ports() self.ports = Ports(self.params, self.request)
def initialize_ports(self) -> None: if (not self.params): self.initialize_params(preload_data=False) self.params.update_ports() self.ports = Ports(self.params, self.request)<|docstring|>Load IO port parameters for device<|endoftext|>
84346bb30c7072d64222f2a7b9888889ba75457cdab60e4832de23a2a994ed56
def initialize_users(self) -> None: 'Load device user data and initialize user management.' users = self.request('get', pwdgrp_url) self.users = Users(users, self.request)
Load device user data and initialize user management.
src/vapyx/vapix.py
initialize_users
sthysel/vapyx
0
python
def initialize_users(self) -> None: users = self.request('get', pwdgrp_url) self.users = Users(users, self.request)
def initialize_users(self) -> None: users = self.request('get', pwdgrp_url) self.users = Users(users, self.request)<|docstring|>Load device user data and initialize user management.<|endoftext|>
bda7524ecac1292ed44cd1d040450539b953311c5a301687e7e85579b3efb4be
def request(self, method, path, **kwargs): 'Prepare HTTP request.' if (method == 'get'): session_method = self.config.session.get elif (method == 'post'): session_method = self.config.session.post else: raise AxisException url = (self.config.url + path) result = session_request(session_method, url, **kwargs) logger.debug(f'Response: {result} from {self.config.host}') if result.startswith('# Error:'): result = '' return result
Prepare HTTP request.
src/vapyx/vapix.py
request
sthysel/vapyx
0
python
def request(self, method, path, **kwargs): if (method == 'get'): session_method = self.config.session.get elif (method == 'post'): session_method = self.config.session.post else: raise AxisException url = (self.config.url + path) result = session_request(session_method, url, **kwargs) logger.debug(f'Response: {result} from {self.config.host}') if result.startswith('# Error:'): result = return result
def request(self, method, path, **kwargs): if (method == 'get'): session_method = self.config.session.get elif (method == 'post'): session_method = self.config.session.post else: raise AxisException url = (self.config.url + path) result = session_request(session_method, url, **kwargs) logger.debug(f'Response: {result} from {self.config.host}') if result.startswith('# Error:'): result = return result<|docstring|>Prepare HTTP request.<|endoftext|>
c57ab5d3dca661108aff26d28f8799305a4dec92b1780440d048cf1bab8c9cfd
def get_qstar(inv, extrapolation=None): '\n Get invariant value (Q*)\n ' return inv.get_qstar(extrapolation)
Get invariant value (Q*)
src/sas/sascalc/invariant/invariant_mapper.py
get_qstar
m2cci-NMZ/sasview
0
python
def get_qstar(inv, extrapolation=None): '\n \n ' return inv.get_qstar(extrapolation)
def get_qstar(inv, extrapolation=None): '\n \n ' return inv.get_qstar(extrapolation)<|docstring|>Get invariant value (Q*)<|endoftext|>
3740040d25e181cb1f85f9f96a5c804a16175e089ee9608fd2792a8dafe4f045
def get_qstar_with_error(inv, extrapolation=None): '\n Get invariant value with uncertainty\n ' return inv.get_qstar_with_error(extrapolation)
Get invariant value with uncertainty
src/sas/sascalc/invariant/invariant_mapper.py
get_qstar_with_error
m2cci-NMZ/sasview
0
python
def get_qstar_with_error(inv, extrapolation=None): '\n \n ' return inv.get_qstar_with_error(extrapolation)
def get_qstar_with_error(inv, extrapolation=None): '\n \n ' return inv.get_qstar_with_error(extrapolation)<|docstring|>Get invariant value with uncertainty<|endoftext|>
74020196a8d154888818aaa9cee35ecfa213f8af65f1652284b7d315528f8690
def get_volume_fraction(inv, contrast, extrapolation=None): '\n Get volume fraction\n ' return inv.get_volume_fraction(contrast, extrapolation)
Get volume fraction
src/sas/sascalc/invariant/invariant_mapper.py
get_volume_fraction
m2cci-NMZ/sasview
0
python
def get_volume_fraction(inv, contrast, extrapolation=None): '\n \n ' return inv.get_volume_fraction(contrast, extrapolation)
def get_volume_fraction(inv, contrast, extrapolation=None): '\n \n ' return inv.get_volume_fraction(contrast, extrapolation)<|docstring|>Get volume fraction<|endoftext|>
83625de9304bd0148ba9512850bfd7056f15a7c9a77020cf15401de3130447bc
def get_volume_fraction_with_error(inv, contrast, extrapolation=None): '\n Get volume fraction with uncertainty\n ' return inv.get_volume_fraction_with_error(contrast, extrapolation)
Get volume fraction with uncertainty
src/sas/sascalc/invariant/invariant_mapper.py
get_volume_fraction_with_error
m2cci-NMZ/sasview
0
python
def get_volume_fraction_with_error(inv, contrast, extrapolation=None): '\n \n ' return inv.get_volume_fraction_with_error(contrast, extrapolation)
def get_volume_fraction_with_error(inv, contrast, extrapolation=None): '\n \n ' return inv.get_volume_fraction_with_error(contrast, extrapolation)<|docstring|>Get volume fraction with uncertainty<|endoftext|>
dd39103d4da7b95d9a0ed00640a82858f821a919739285f0462e1601572c3745
def get_surface(inv, contrast, porod_const, extrapolation=None): '\n Get surface with uncertainty\n ' return inv.get_surface(contrast=contrast, porod_const=porod_const, extrapolation=extrapolation)
Get surface with uncertainty
src/sas/sascalc/invariant/invariant_mapper.py
get_surface
m2cci-NMZ/sasview
0
python
def get_surface(inv, contrast, porod_const, extrapolation=None): '\n \n ' return inv.get_surface(contrast=contrast, porod_const=porod_const, extrapolation=extrapolation)
def get_surface(inv, contrast, porod_const, extrapolation=None): '\n \n ' return inv.get_surface(contrast=contrast, porod_const=porod_const, extrapolation=extrapolation)<|docstring|>Get surface with uncertainty<|endoftext|>
b7acb0f756edeffb6ca6afe7c1cf8946c12d1c5bfc101a34cbb481e92879d7e8
def get_surface_with_error(inv, contrast, porod_const, extrapolation=None): '\n Get surface with uncertainty\n ' return inv.get_surface_with_error(contrast=contrast, porod_const=porod_const, extrapolation=extrapolation)
Get surface with uncertainty
src/sas/sascalc/invariant/invariant_mapper.py
get_surface_with_error
m2cci-NMZ/sasview
0
python
def get_surface_with_error(inv, contrast, porod_const, extrapolation=None): '\n \n ' return inv.get_surface_with_error(contrast=contrast, porod_const=porod_const, extrapolation=extrapolation)
def get_surface_with_error(inv, contrast, porod_const, extrapolation=None): '\n \n ' return inv.get_surface_with_error(contrast=contrast, porod_const=porod_const, extrapolation=extrapolation)<|docstring|>Get surface with uncertainty<|endoftext|>
bc85ffbc5b1c00e6243fd36ac4dee7d16eec405bcb6c52444ae50ce7f0f5ba8e
def train(self, examples): '\n examples: list of examples, each example is of form (board, pi, v)\n ' (input_boards, target_pis, target_vs) = list(zip(*examples)) input_boards = np.asarray(input_boards) target_pis = np.asarray(target_pis) target_vs = np.asarray(target_vs) self.nnet.model.fit(x=input_boards, y=[target_pis, target_vs], batch_size=args.batch_size, epochs=args.epochs)
examples: list of examples, each example is of form (board, pi, v)
cubicup/keras/NNet.py
train
l45k/alpha-zero-general
0
python
def train(self, examples): '\n \n ' (input_boards, target_pis, target_vs) = list(zip(*examples)) input_boards = np.asarray(input_boards) target_pis = np.asarray(target_pis) target_vs = np.asarray(target_vs) self.nnet.model.fit(x=input_boards, y=[target_pis, target_vs], batch_size=args.batch_size, epochs=args.epochs)
def train(self, examples): '\n \n ' (input_boards, target_pis, target_vs) = list(zip(*examples)) input_boards = np.asarray(input_boards) target_pis = np.asarray(target_pis) target_vs = np.asarray(target_vs) self.nnet.model.fit(x=input_boards, y=[target_pis, target_vs], batch_size=args.batch_size, epochs=args.epochs)<|docstring|>examples: list of examples, each example is of form (board, pi, v)<|endoftext|>
1d30efebec471f71d8008bbb5e097c87ac26f2890d9c4178133dac2884506a3f
def predict(self, board): '\n board: np array with board\n ' start = time.time() board = board[(np.newaxis, :)] (pi, v) = self.nnet.model.predict(board) return (pi[0], v[0])
board: np array with board
cubicup/keras/NNet.py
predict
l45k/alpha-zero-general
0
python
def predict(self, board): '\n \n ' start = time.time() board = board[(np.newaxis, :)] (pi, v) = self.nnet.model.predict(board) return (pi[0], v[0])
def predict(self, board): '\n \n ' start = time.time() board = board[(np.newaxis, :)] (pi, v) = self.nnet.model.predict(board) return (pi[0], v[0])<|docstring|>board: np array with board<|endoftext|>
1569888e1f74cc7f7daa831e5946624154629d8364f6a86c4a2999ebd37d8d25
def __init__(self, context, name, parent, *, calibrationPort, **razorArgs): '\n Constructor.\n\n context : visr.SignalFlowContext\n Standard visr.Component construction argument, a structure holding the block size and the sampling frequency\n name : string\n Name of the component, Standard visr.Component construction argument\n parent : visr.CompositeComponent\n Containing component if there is one, None if this is a top-level component of the signal flow.\n calibrationPort: int\n A UDP port number. Packets sent to this port trigger the calibration.\n razorArg: keyword list\n Set of parameters to the RazorAHRS. See this class for parameter documentation.\n ' super(RazorAHRSWithUdpCalibrationTrigger, self).__init__(context, name, parent) self.trackingOutput = visr.ParameterOutput('orientation', self, pml.ListenerPosition.staticType, pml.DoubleBufferingProtocol.staticType, pml.EmptyParameterConfig()) razorArgs['calibrationInput'] = True self.tracker = RazorAHRS(context, 'Tracker', self, **razorArgs) self.triggerReceiver = UdpReceiver(context, 'CalibrationTriggerReceiver', self, port=calibrationPort) self.parameterConnection(self.triggerReceiver.parameterPort('messageOutput'), self.tracker.parameterPort('calibration')) self.parameterConnection(self.tracker.parameterPort('orientation'), self.trackingOutput)
Constructor. context : visr.SignalFlowContext Standard visr.Component construction argument, a structure holding the block size and the sampling frequency name : string Name of the component, Standard visr.Component construction argument parent : visr.CompositeComponent Containing component if there is one, None if this is a top-level component of the signal flow. calibrationPort: int A UDP port number. Packets sent to this port trigger the calibration. razorArg: keyword list Set of parameters to the RazorAHRS. See this class for parameter documentation.
src/python/packages/visr_bst/tracker/razor_ahrs_with_udp_calibration_trigger.py
__init__
s3a-spatialaudio/VISR
17
python
def __init__(self, context, name, parent, *, calibrationPort, **razorArgs): '\n Constructor.\n\n context : visr.SignalFlowContext\n Standard visr.Component construction argument, a structure holding the block size and the sampling frequency\n name : string\n Name of the component, Standard visr.Component construction argument\n parent : visr.CompositeComponent\n Containing component if there is one, None if this is a top-level component of the signal flow.\n calibrationPort: int\n A UDP port number. Packets sent to this port trigger the calibration.\n razorArg: keyword list\n Set of parameters to the RazorAHRS. See this class for parameter documentation.\n ' super(RazorAHRSWithUdpCalibrationTrigger, self).__init__(context, name, parent) self.trackingOutput = visr.ParameterOutput('orientation', self, pml.ListenerPosition.staticType, pml.DoubleBufferingProtocol.staticType, pml.EmptyParameterConfig()) razorArgs['calibrationInput'] = True self.tracker = RazorAHRS(context, 'Tracker', self, **razorArgs) self.triggerReceiver = UdpReceiver(context, 'CalibrationTriggerReceiver', self, port=calibrationPort) self.parameterConnection(self.triggerReceiver.parameterPort('messageOutput'), self.tracker.parameterPort('calibration')) self.parameterConnection(self.tracker.parameterPort('orientation'), self.trackingOutput)
def __init__(self, context, name, parent, *, calibrationPort, **razorArgs): '\n Constructor.\n\n context : visr.SignalFlowContext\n Standard visr.Component construction argument, a structure holding the block size and the sampling frequency\n name : string\n Name of the component, Standard visr.Component construction argument\n parent : visr.CompositeComponent\n Containing component if there is one, None if this is a top-level component of the signal flow.\n calibrationPort: int\n A UDP port number. Packets sent to this port trigger the calibration.\n razorArg: keyword list\n Set of parameters to the RazorAHRS. See this class for parameter documentation.\n ' super(RazorAHRSWithUdpCalibrationTrigger, self).__init__(context, name, parent) self.trackingOutput = visr.ParameterOutput('orientation', self, pml.ListenerPosition.staticType, pml.DoubleBufferingProtocol.staticType, pml.EmptyParameterConfig()) razorArgs['calibrationInput'] = True self.tracker = RazorAHRS(context, 'Tracker', self, **razorArgs) self.triggerReceiver = UdpReceiver(context, 'CalibrationTriggerReceiver', self, port=calibrationPort) self.parameterConnection(self.triggerReceiver.parameterPort('messageOutput'), self.tracker.parameterPort('calibration')) self.parameterConnection(self.tracker.parameterPort('orientation'), self.trackingOutput)<|docstring|>Constructor. context : visr.SignalFlowContext Standard visr.Component construction argument, a structure holding the block size and the sampling frequency name : string Name of the component, Standard visr.Component construction argument parent : visr.CompositeComponent Containing component if there is one, None if this is a top-level component of the signal flow. calibrationPort: int A UDP port number. Packets sent to this port trigger the calibration. razorArg: keyword list Set of parameters to the RazorAHRS. See this class for parameter documentation.<|endoftext|>
304a9d09f23a4032ced4bfa6857b284a7c89157342a249cc0ecbab5a2ac6c8d3
def __init__(self, diskdev): '\n Constructor\n\n Args:\n diskdev: Linux device name to get parameters for\n ' pass
Constructor Args: diskdev: Linux device name to get parameters for
sonic_platform_base/sonic_ssd/ssd_base.py
__init__
theasianpianist/sonic-platform-common
25
python
def __init__(self, diskdev): '\n Constructor\n\n Args:\n diskdev: Linux device name to get parameters for\n ' pass
def __init__(self, diskdev): '\n Constructor\n\n Args:\n diskdev: Linux device name to get parameters for\n ' pass<|docstring|>Constructor Args: diskdev: Linux device name to get parameters for<|endoftext|>
d560e494e2233188c60b19eb25d4ec3873e2ddb74d9a9f17f60ee5e1029afc1b
def get_health(self): '\n Retrieves current disk health in percentages\n\n Returns:\n A float number of current ssd health\n e.g. 83.5\n ' raise NotImplementedError
Retrieves current disk health in percentages Returns: A float number of current ssd health e.g. 83.5
sonic_platform_base/sonic_ssd/ssd_base.py
get_health
theasianpianist/sonic-platform-common
25
python
def get_health(self): '\n Retrieves current disk health in percentages\n\n Returns:\n A float number of current ssd health\n e.g. 83.5\n ' raise NotImplementedError
def get_health(self): '\n Retrieves current disk health in percentages\n\n Returns:\n A float number of current ssd health\n e.g. 83.5\n ' raise NotImplementedError<|docstring|>Retrieves current disk health in percentages Returns: A float number of current ssd health e.g. 83.5<|endoftext|>
62f1e039c504bdadb98d849b5bbfd98122dfb570b876669aa622da71b80d7c13
def get_temperature(self): '\n Retrieves current disk temperature in Celsius\n\n Returns:\n A float number of current temperature in Celsius\n e.g. 40.1\n ' raise NotImplementedError
Retrieves current disk temperature in Celsius Returns: A float number of current temperature in Celsius e.g. 40.1
sonic_platform_base/sonic_ssd/ssd_base.py
get_temperature
theasianpianist/sonic-platform-common
25
python
def get_temperature(self): '\n Retrieves current disk temperature in Celsius\n\n Returns:\n A float number of current temperature in Celsius\n e.g. 40.1\n ' raise NotImplementedError
def get_temperature(self): '\n Retrieves current disk temperature in Celsius\n\n Returns:\n A float number of current temperature in Celsius\n e.g. 40.1\n ' raise NotImplementedError<|docstring|>Retrieves current disk temperature in Celsius Returns: A float number of current temperature in Celsius e.g. 40.1<|endoftext|>
c1e27006bb1c020cb26d9fafb1f6a7e1d929a44013d69d63aacdf4a691d712e6
def get_model(self): '\n Retrieves model for the given disk device\n\n Returns:\n A string holding disk model as provided by the manufacturer\n ' raise NotImplementedError
Retrieves model for the given disk device Returns: A string holding disk model as provided by the manufacturer
sonic_platform_base/sonic_ssd/ssd_base.py
get_model
theasianpianist/sonic-platform-common
25
python
def get_model(self): '\n Retrieves model for the given disk device\n\n Returns:\n A string holding disk model as provided by the manufacturer\n ' raise NotImplementedError
def get_model(self): '\n Retrieves model for the given disk device\n\n Returns:\n A string holding disk model as provided by the manufacturer\n ' raise NotImplementedError<|docstring|>Retrieves model for the given disk device Returns: A string holding disk model as provided by the manufacturer<|endoftext|>
0bf8b70505903cdbd78fb85f998458fde26cd5e774e7e85566f2f545e9d56605
def get_firmware(self): '\n Retrieves firmware version for the given disk device\n\n Returns:\n A string holding disk firmware version as provided by the manufacturer\n ' raise NotImplementedError
Retrieves firmware version for the given disk device Returns: A string holding disk firmware version as provided by the manufacturer
sonic_platform_base/sonic_ssd/ssd_base.py
get_firmware
theasianpianist/sonic-platform-common
25
python
def get_firmware(self): '\n Retrieves firmware version for the given disk device\n\n Returns:\n A string holding disk firmware version as provided by the manufacturer\n ' raise NotImplementedError
def get_firmware(self): '\n Retrieves firmware version for the given disk device\n\n Returns:\n A string holding disk firmware version as provided by the manufacturer\n ' raise NotImplementedError<|docstring|>Retrieves firmware version for the given disk device Returns: A string holding disk firmware version as provided by the manufacturer<|endoftext|>
d9e756784f9290620795e92f7cb921c778945da13f186ebdd2f4110f38cfb6f1
def get_serial(self): '\n Retrieves serial number for the given disk device\n\n Returns:\n A string holding disk serial number as provided by the manufacturer\n ' raise NotImplementedError
Retrieves serial number for the given disk device Returns: A string holding disk serial number as provided by the manufacturer
sonic_platform_base/sonic_ssd/ssd_base.py
get_serial
theasianpianist/sonic-platform-common
25
python
def get_serial(self): '\n Retrieves serial number for the given disk device\n\n Returns:\n A string holding disk serial number as provided by the manufacturer\n ' raise NotImplementedError
def get_serial(self): '\n Retrieves serial number for the given disk device\n\n Returns:\n A string holding disk serial number as provided by the manufacturer\n ' raise NotImplementedError<|docstring|>Retrieves serial number for the given disk device Returns: A string holding disk serial number as provided by the manufacturer<|endoftext|>
a612c5aabece6fa68df2be6d7debf5342ce5d85721dbd87fe0af813aa0b22dea
def get_vendor_output(self): '\n Retrieves vendor specific data for the given disk device\n\n Returns:\n A string holding some vendor specific disk information\n ' raise NotImplementedError
Retrieves vendor specific data for the given disk device Returns: A string holding some vendor specific disk information
sonic_platform_base/sonic_ssd/ssd_base.py
get_vendor_output
theasianpianist/sonic-platform-common
25
python
def get_vendor_output(self): '\n Retrieves vendor specific data for the given disk device\n\n Returns:\n A string holding some vendor specific disk information\n ' raise NotImplementedError
def get_vendor_output(self): '\n Retrieves vendor specific data for the given disk device\n\n Returns:\n A string holding some vendor specific disk information\n ' raise NotImplementedError<|docstring|>Retrieves vendor specific data for the given disk device Returns: A string holding some vendor specific disk information<|endoftext|>
9d8138dd38fac579c3549e9d4fba8c44583b5a3b55af57ee6f1e53efd4057dbc
@property @abstractmethod def encoding_low(self) -> float: '\n Lower boundary of encoding space\n '
Lower boundary of encoding space
gym_physx/encoders/base_encoder.py
encoding_low
ischubert/gym-physx
1
python
@property @abstractmethod def encoding_low(self) -> float: '\n \n '
@property @abstractmethod def encoding_low(self) -> float: '\n \n '<|docstring|>Lower boundary of encoding space<|endoftext|>
39b0e6d0fd3f57253f33fd1ed01ad954c6df257ca36b4be06c6db824f6edcead
@property @abstractmethod def encoding_high(self) -> float: '\n Upper boundary of encoding space\n '
Upper boundary of encoding space
gym_physx/encoders/base_encoder.py
encoding_high
ischubert/gym-physx
1
python
@property @abstractmethod def encoding_high(self) -> float: '\n \n '
@property @abstractmethod def encoding_high(self) -> float: '\n \n '<|docstring|>Upper boundary of encoding space<|endoftext|>
cc01a681568411e78e9ad502fb06157d65ff4a941544b00aa44570525dd3dae5
@property @abstractmethod def hidden_dim(self) -> int: '\n Encoding dimension\n '
Encoding dimension
gym_physx/encoders/base_encoder.py
hidden_dim
ischubert/gym-physx
1
python
@property @abstractmethod def hidden_dim(self) -> int: '\n \n '
@property @abstractmethod def hidden_dim(self) -> int: '\n \n '<|docstring|>Encoding dimension<|endoftext|>
7f318b35576558c114881a6af3082e8131718947650cf78bec65c23556f34a12
@abstractmethod def encode(self, plan: np.ndarray) -> np.ndarray: '\n Encode goal and return\n '
Encode goal and return
gym_physx/encoders/base_encoder.py
encode
ischubert/gym-physx
1
python
@abstractmethod def encode(self, plan: np.ndarray) -> np.ndarray: '\n \n '
@abstractmethod def encode(self, plan: np.ndarray) -> np.ndarray: '\n \n '<|docstring|>Encode goal and return<|endoftext|>
63f380ae8a22cb4cd902126896995a72417f971d9ae17e2dcbf75d0e5b5e0647
def count_deck_classifications(class_counts): 'Return histogram of classifications from dealing out one deck.\n class_counts: starting histogram\n ' deck = Deck() deck.shuffle() for i in range(7): hand = PokerHand() deck.move_cards(hand, 7) hand_class = hand.classify() class_counts[hand_class] = (class_counts.get(hand_class, 0) + 1)
Return histogram of classifications from dealing out one deck. class_counts: starting histogram
chap18/PokerHand.py
count_deck_classifications
theChad/ThinkPython
0
python
def count_deck_classifications(class_counts): 'Return histogram of classifications from dealing out one deck.\n class_counts: starting histogram\n ' deck = Deck() deck.shuffle() for i in range(7): hand = PokerHand() deck.move_cards(hand, 7) hand_class = hand.classify() class_counts[hand_class] = (class_counts.get(hand_class, 0) + 1)
def count_deck_classifications(class_counts): 'Return histogram of classifications from dealing out one deck.\n class_counts: starting histogram\n ' deck = Deck() deck.shuffle() for i in range(7): hand = PokerHand() deck.move_cards(hand, 7) hand_class = hand.classify() class_counts[hand_class] = (class_counts.get(hand_class, 0) + 1)<|docstring|>Return histogram of classifications from dealing out one deck. class_counts: starting histogram<|endoftext|>
f102973ad4bc269fb6958c29b5d885a4ef900bb57af61c37dbc9640ff4f5161d
def count_many_classifications(n=10000): 'Return histogram of classifications across dealing out n decks\n n: number of decks\n ' class_counts = {} for i in range(n): count_deck_classifications(class_counts) return class_counts
Return histogram of classifications across dealing out n decks n: number of decks
chap18/PokerHand.py
count_many_classifications
theChad/ThinkPython
0
python
def count_many_classifications(n=10000): 'Return histogram of classifications across dealing out n decks\n n: number of decks\n ' class_counts = {} for i in range(n): count_deck_classifications(class_counts) return class_counts
def count_many_classifications(n=10000): 'Return histogram of classifications across dealing out n decks\n n: number of decks\n ' class_counts = {} for i in range(n): count_deck_classifications(class_counts) return class_counts<|docstring|>Return histogram of classifications across dealing out n decks n: number of decks<|endoftext|>
63334c852b1df8f803b0ec56c8944eeda2e435115e1e69fc9642d57053688bda
def hand_rankings(class_counts): 'Print a table of the probability of various hands\n class_counts: histogram of hand classifications\n ' total = sum(class_counts.values()) print('Prob ', 'Classification') print('------', '--------------') for classification in (PokerHand.classifications + [None]): print('{:>6.2%}'.format((class_counts.get(classification, 0) / total)), classification)
Print a table of the probability of various hands class_counts: histogram of hand classifications
chap18/PokerHand.py
hand_rankings
theChad/ThinkPython
0
python
def hand_rankings(class_counts): 'Print a table of the probability of various hands\n class_counts: histogram of hand classifications\n ' total = sum(class_counts.values()) print('Prob ', 'Classification') print('------', '--------------') for classification in (PokerHand.classifications + [None]): print('{:>6.2%}'.format((class_counts.get(classification, 0) / total)), classification)
def hand_rankings(class_counts): 'Print a table of the probability of various hands\n class_counts: histogram of hand classifications\n ' total = sum(class_counts.values()) print('Prob ', 'Classification') print('------', '--------------') for classification in (PokerHand.classifications + [None]): print('{:>6.2%}'.format((class_counts.get(classification, 0) / total)), classification)<|docstring|>Print a table of the probability of various hands class_counts: histogram of hand classifications<|endoftext|>
3def8af83e54093dccd30a52a81b076b8f6e280b671c8eab66f1e7655e04a791
def suit_hist(self): 'Builds a histogram of the suits that appear in the hand.\n\n Stores the result in attribute suits.\n ' self.suits = {} for card in self.cards: self.suits[card.suit] = (self.suits.get(card.suit, 0) + 1)
Builds a histogram of the suits that appear in the hand. Stores the result in attribute suits.
chap18/PokerHand.py
suit_hist
theChad/ThinkPython
0
python
def suit_hist(self): 'Builds a histogram of the suits that appear in the hand.\n\n Stores the result in attribute suits.\n ' self.suits = {} for card in self.cards: self.suits[card.suit] = (self.suits.get(card.suit, 0) + 1)
def suit_hist(self): 'Builds a histogram of the suits that appear in the hand.\n\n Stores the result in attribute suits.\n ' self.suits = {} for card in self.cards: self.suits[card.suit] = (self.suits.get(card.suit, 0) + 1)<|docstring|>Builds a histogram of the suits that appear in the hand. Stores the result in attribute suits.<|endoftext|>
32994b32a746b257493eede16ad5d9bfe76e9f409d5a1499263687eae936a31b
def rank_hist(self): 'Builds a histogram of the ranks that papear in the hand.\n\n Stores the result in attribute ranks.\n ' self.ranks = {} for card in self.cards: self.ranks[card.rank] = (self.ranks.get(card.rank, 0) + 1)
Builds a histogram of the ranks that papear in the hand. Stores the result in attribute ranks.
chap18/PokerHand.py
rank_hist
theChad/ThinkPython
0
python
def rank_hist(self): 'Builds a histogram of the ranks that papear in the hand.\n\n Stores the result in attribute ranks.\n ' self.ranks = {} for card in self.cards: self.ranks[card.rank] = (self.ranks.get(card.rank, 0) + 1)
def rank_hist(self): 'Builds a histogram of the ranks that papear in the hand.\n\n Stores the result in attribute ranks.\n ' self.ranks = {} for card in self.cards: self.ranks[card.rank] = (self.ranks.get(card.rank, 0) + 1)<|docstring|>Builds a histogram of the ranks that papear in the hand. Stores the result in attribute ranks.<|endoftext|>
b7c88d9600d30168a13df488fa3aa1c27dbb63c81dcd32d941446d6060a43d7a
def has_flush(self): 'Returns True if the hand has a flush, False otherwise.\n \n Note that this works correctly for hands with more than 5 cards.\n ' self.suit_hist() for val in self.suits.values(): if (val >= 5): return True return False
Returns True if the hand has a flush, False otherwise. Note that this works correctly for hands with more than 5 cards.
chap18/PokerHand.py
has_flush
theChad/ThinkPython
0
python
def has_flush(self): 'Returns True if the hand has a flush, False otherwise.\n \n Note that this works correctly for hands with more than 5 cards.\n ' self.suit_hist() for val in self.suits.values(): if (val >= 5): return True return False
def has_flush(self): 'Returns True if the hand has a flush, False otherwise.\n \n Note that this works correctly for hands with more than 5 cards.\n ' self.suit_hist() for val in self.suits.values(): if (val >= 5): return True return False<|docstring|>Returns True if the hand has a flush, False otherwise. Note that this works correctly for hands with more than 5 cards.<|endoftext|>
d954ee20b50c245f57294008204f346b0abddfc93efeceedef61ee81ca176e0c
def has_kind(self, n): 'Returns True if the hand has n of a kind.\n n: integer\n ' self.rank_hist() for val in self.ranks.values(): if (val >= n): return True return False
Returns True if the hand has n of a kind. n: integer
chap18/PokerHand.py
has_kind
theChad/ThinkPython
0
python
def has_kind(self, n): 'Returns True if the hand has n of a kind.\n n: integer\n ' self.rank_hist() for val in self.ranks.values(): if (val >= n): return True return False
def has_kind(self, n): 'Returns True if the hand has n of a kind.\n n: integer\n ' self.rank_hist() for val in self.ranks.values(): if (val >= n): return True return False<|docstring|>Returns True if the hand has n of a kind. n: integer<|endoftext|>
fe84a8ddadc545c3e06d36d2946d2201f27f19ab38409218dceedd514f2fc9af
def has_pair(self): 'Returns True if the hand has a pair' return self.has_kind(2)
Returns True if the hand has a pair
chap18/PokerHand.py
has_pair
theChad/ThinkPython
0
python
def has_pair(self): return self.has_kind(2)
def has_pair(self): return self.has_kind(2)<|docstring|>Returns True if the hand has a pair<|endoftext|>
b5aa2e52cfacfa4b36f96fa442e3071de6d34566bfd22227211a14f101b28b2f
def has_two_pair(self): 'Returns True if the hand has two pair' self.rank_hist() pairs = 0 for val in self.ranks.values(): if (val >= 2): pairs += 1 return (pairs >= 2)
Returns True if the hand has two pair
chap18/PokerHand.py
has_two_pair
theChad/ThinkPython
0
python
def has_two_pair(self): self.rank_hist() pairs = 0 for val in self.ranks.values(): if (val >= 2): pairs += 1 return (pairs >= 2)
def has_two_pair(self): self.rank_hist() pairs = 0 for val in self.ranks.values(): if (val >= 2): pairs += 1 return (pairs >= 2)<|docstring|>Returns True if the hand has two pair<|endoftext|>
d9b0bf8fe5d0664cc946b36f0962a3c85859ae3876ae867ebb2dfb488c1bab5f
def has_three_of_a_kind(self): 'Returns True if the hand has three of a kind' return self.has_kind(3)
Returns True if the hand has three of a kind
chap18/PokerHand.py
has_three_of_a_kind
theChad/ThinkPython
0
python
def has_three_of_a_kind(self): return self.has_kind(3)
def has_three_of_a_kind(self): return self.has_kind(3)<|docstring|>Returns True if the hand has three of a kind<|endoftext|>
12be2aaeb176bd77a05f14e2583878817f752018e6e7cd0d57f76ceed12c73a9
def has_straight(self): 'Returns True if the hand has a straight' self.rank_hist() sorted_ranks = sorted(self.ranks) if (sorted_ranks[0] == 1): sorted_ranks.append(14) num_ranks = len(sorted_ranks) straight = 1 for i in range((num_ranks - 1)): if ((sorted_ranks[(i + 1)] - sorted_ranks[i]) == 1): straight += 1 if (straight >= 5): return True else: straight = 1 return False
Returns True if the hand has a straight
chap18/PokerHand.py
has_straight
theChad/ThinkPython
0
python
def has_straight(self): self.rank_hist() sorted_ranks = sorted(self.ranks) if (sorted_ranks[0] == 1): sorted_ranks.append(14) num_ranks = len(sorted_ranks) straight = 1 for i in range((num_ranks - 1)): if ((sorted_ranks[(i + 1)] - sorted_ranks[i]) == 1): straight += 1 if (straight >= 5): return True else: straight = 1 return False
def has_straight(self): self.rank_hist() sorted_ranks = sorted(self.ranks) if (sorted_ranks[0] == 1): sorted_ranks.append(14) num_ranks = len(sorted_ranks) straight = 1 for i in range((num_ranks - 1)): if ((sorted_ranks[(i + 1)] - sorted_ranks[i]) == 1): straight += 1 if (straight >= 5): return True else: straight = 1 return False<|docstring|>Returns True if the hand has a straight<|endoftext|>
fef407c4c9308f0829be23acca51e608ffa13c86600e3b9d17620e38b4d11356
def has_full_house(self): 'Returns True if the hand has a full house' self.rank_hist() sorted_values = sorted(self.ranks.values()) return ((sorted_values[(- 1)] >= 3) and (sorted_values[(- 2)] >= 2))
Returns True if the hand has a full house
chap18/PokerHand.py
has_full_house
theChad/ThinkPython
0
python
def has_full_house(self): self.rank_hist() sorted_values = sorted(self.ranks.values()) return ((sorted_values[(- 1)] >= 3) and (sorted_values[(- 2)] >= 2))
def has_full_house(self): self.rank_hist() sorted_values = sorted(self.ranks.values()) return ((sorted_values[(- 1)] >= 3) and (sorted_values[(- 2)] >= 2))<|docstring|>Returns True if the hand has a full house<|endoftext|>