docstring
stringlengths
52
499
function
stringlengths
67
35.2k
__index_level_0__
int64
52.6k
1.16M
Change the instance count of an existing VM Scale Set. Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. resource_group (str): Azure resource group name. vmss_name (str): Name of the virtual machine scale set. capacit...
def scale_vmss(access_token, subscription_id, resource_group, vmss_name, capacity): endpoint = ''.join([get_rm_endpoint(), '/subscriptions/', subscription_id, '/resourceGroups/', resource_group, '/providers/Microsoft.Compute/virtualMachine...
608,090
Start a virtual machine. Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. resource_group (str): Azure resource group name. vm_name (str): Name of the virtual machine. Returns: HTTP response.
def start_vm(access_token, subscription_id, resource_group, vm_name): endpoint = ''.join([get_rm_endpoint(), '/subscriptions/', subscription_id, '/resourceGroups/', resource_group, '/providers/Microsoft.Compute/virtualMachines/', ...
608,091
Update a virtual machine with a new JSON body. E.g. do a GET, change something, call this. Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. resource_group (str): Azure resource group name. vm_name (str): Name of the virtual ...
def update_vm(access_token, subscription_id, resource_group, vm_name, body): endpoint = ''.join([get_rm_endpoint(), '/subscriptions/', subscription_id, '/resourceGroups/', resource_group, '/providers/Microsoft.Compute/virtualMachines/', vm...
608,092
Update a VMSS with a new JSON body. E.g. do a GET, change something, call this. Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. resource_group (str): Azure resource group name. vm_name (str): Name of the virtual machine. ...
def update_vmss(access_token, subscription_id, resource_group, vmss_name, body): endpoint = ''.join([get_rm_endpoint(), '/subscriptions/', subscription_id, '/resourceGroups/', resource_group, '/providers/Microsoft.Compute/virtualMachineSca...
608,093
Return the object ID for the Graph user who owns the access token. Args: access_token (str): A Microsoft Graph access token. (Not an Azure access token.) If not provided, attempt to get it from MSI_ENDPOINT. Returns: An object ID string for a user or service princip...
def get_object_id_from_graph(access_token=None): if access_token is None: access_token = get_graph_token_from_msi() endpoint = 'https://' + GRAPH_RESOURCE_HOST + '/v1.0/me/' headers = {'Authorization': 'Bearer ' + access_token, 'Host': GRAPH_RESOURCE_HOST} ret = requests.get(endpoint, head...
608,097
Get the default, or named, subscription id from CLI's local cache. Args: name (str): Optional subscription name. If this is set, the subscription id of the named subscription is returned from the CLI cache if present. If not set, the subscription id of the default subscription is retu...
def get_subscription_from_cli(name=None): home = os.path.expanduser('~') azure_profile_path = home + os.sep + '.azure' + os.sep + 'azureProfile.json' if os.path.isfile(azure_profile_path) is False: print('Error from get_subscription_from_cli(): Cannot find ' + azure_profile_path) ...
608,098
List available locations for a subscription. Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. Returns: HTTP response. JSON list of locations.
def list_locations(access_token, subscription_id): endpoint = ''.join([get_rm_endpoint(), '/subscriptions/', subscription_id, '/locations?api-version=', BASE_API]) return do_get(endpoint, access_token)
608,099
Get the access keys for the specified Cosmos DB account. Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. rgname (str): Azure resource group name. account_name (str): Name of the Cosmos DB account. Returns: HTTP...
def get_cosmosdb_account_keys(access_token, subscription_id, rgname, account_name): endpoint = ''.join([get_rm_endpoint(), '/subscriptions/', subscription_id, '/resourcegroups/', rgname, '/providers/Microsoft.DocumentDB/databaseAccounts/',...
608,102
Deletes a key vault in the named resource group. Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. rgname (str): Azure resource group name. vault_name (str): Name of the new key vault. Returns: HTTP response. 200...
def delete_keyvault(access_token, subscription_id, rgname, vault_name): endpoint = ''.join([get_rm_endpoint(), '/subscriptions/', subscription_id, '/resourcegroups/', rgname, '/providers/Microsoft.KeyVault/vaults/', vault_name, ...
608,104
Gets details about the named key vault. Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. rgname (str): Azure resource group name. vault_name (str): Name of the key vault. Returns: HTTP response. JSON body of key...
def get_keyvault(access_token, subscription_id, rgname, vault_name): endpoint = ''.join([get_rm_endpoint(), '/subscriptions/', subscription_id, '/resourcegroups/', rgname, '/providers/Microsoft.KeyVault/vaults/', vault_name, ...
608,105
Lists key vaults in the named resource group. Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. rgname (str): Azure resource group name. Returns: HTTP response. 200 OK.
def list_keyvaults(access_token, subscription_id, rgname): endpoint = ''.join([get_rm_endpoint(), '/subscriptions/', subscription_id, '/resourcegroups/', rgname, '/providers/Microsoft.KeyVault/vaults', '?api-version...
608,106
Lists key vaults belonging to this subscription. Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. Returns: HTTP response. 200 OK.
def list_keyvaults_sub(access_token, subscription_id): endpoint = ''.join([get_rm_endpoint(), '/subscriptions/', subscription_id, '/providers/Microsoft.KeyVault/vaults', '?api-version=', KEYVAULT_API]) return do_get_next(endpoint, acce...
608,107
Adds a secret to a key vault using the key vault URI. Creates a new version if the secret already exists. Args: access_token (str): A valid Azure authentication token. vault_uri (str): Vault URI e.g. https://myvault.vault.azure.net. secret_name (str): Name of the secret to add. ...
def set_keyvault_secret(access_token, vault_uri, secret_name, secret_value): endpoint = ''.join([vault_uri, '/secrets/', secret_name, '?api-version=', '7.0']) current_time = datetime.datetime.now().isoformat() attributes = {'created': current_time, ...
608,108
Deletes a secret from a key vault using the key vault URI. Args: access_token (str): A valid Azure authentication token. vault_uri (str): Vault URI e.g. https://myvault.azure.net. secret_name (str): Name of the secret to add. Returns: HTTP response. 200 OK.
def delete_keyvault_secret(access_token, vault_uri, secret_name): endpoint = ''.join([vault_uri, '/secrets/', secret_name, '?api-version=', '7.0']) return do_delete(endpoint, access_token)
608,109
List the autoscale settings in a subscription. Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. Returns: HTTP response. JSON body of autoscale settings.
def list_autoscale_settings(access_token, subscription_id): endpoint = ''.join([get_rm_endpoint(), '/subscriptions/', subscription_id, '/providers/microsoft.insights/', '/autoscaleSettings?api-version=', INSIGHTS_API]) return do_get(en...
608,112
List the Microsoft Insights components in a resource group. Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. resource_group (str): Azure resource group name. Returns: HTTP response. JSON body of components.
def list_insights_components(access_token, subscription_id, resource_group): endpoint = ''.join([get_rm_endpoint(), '/subscriptions/', subscription_id, '/resourceGroups/', resource_group, '/providers/microsoft.insights/', ...
608,113
List the monitoring metric definitions for a resource. Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. resource_group (str): Azure resource group name. resource_provider (str): Type of resource provider. resource_ty...
def list_metric_defs_for_resource(access_token, subscription_id, resource_group, resource_provider, resource_type, resource_name): endpoint = ''.join([get_rm_endpoint(), '/subscriptions/', subscription_id, '/resourceGroups/', res...
608,114
Get the monitoring metrics for a resource. Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. resource_group (str): Azure resource group name. resource_type (str): Type of resource. resource_name (str): Name of resourc...
def get_metrics_for_resource(access_token, subscription_id, resource_group, resource_provider, resource_type, resource_name): endpoint = ''.join([get_rm_endpoint(), '/subscriptions/', subscription_id, '/resourceGroups/', resource_grou...
608,115
Get the insights evens for a subsctipion since the specific timestamp. Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. start_timestamp (str): timestamp to get events from. E.g. '2017-05-01T00:00:00.0000000Z'. Returns: H...
def get_events_for_subscription(access_token, subscription_id, start_timestamp): endpoint = ''.join([get_rm_endpoint(), '/subscriptions/', subscription_id, '/providers/microsoft.insights/eventtypes/management/values?api-version=', INSIGHTS...
608,116
get an Azure access token using the adal library. Args: tenant_id (str): Tenant id of the user's account. application_id (str): Application id of a Service Principal account. application_secret (str): Application secret (password) of the Service Principal account. Returns: An A...
def get_access_token(tenant_id, application_id, application_secret): context = adal.AuthenticationContext( get_auth_endpoint() + tenant_id, api_version=None) token_response = context.acquire_token_with_client_credentials( get_resource_endpoint(), application_id, application_secret) retu...
608,125
List available VM image offers from a publisher. Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. location (str): Azure data center location. E.g. westus. publisher (str): Publisher name, e.g. Canonical. Returns: ...
def list_offers(access_token, subscription_id, location, publisher): endpoint = ''.join([get_rm_endpoint(), '/subscriptions/', subscription_id, '/providers/Microsoft.Compute/', 'locations/', location, '/publishers/'...
608,128
List available VM image skus for a publisher offer. Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. location (str): Azure data center location. E.g. westus. publisher (str): VM image publisher. E.g. MicrosoftWindowsServer. ...
def list_skus(access_token, subscription_id, location, publisher, offer): endpoint = ''.join([get_rm_endpoint(), '/subscriptions/', subscription_id, '/providers/Microsoft.Compute/', 'locations/', location, '/publish...
608,129
List available versions for a given publisher's sku. Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. location (str): Azure data center location. E.g. westus. publisher (str): VM image publisher. E.g. MicrosoftWindowsServer....
def list_sku_versions(access_token, subscription_id, location, publisher, offer, sku): endpoint = ''.join([get_rm_endpoint(), '/subscriptions/', subscription_id, '/providers/Microsoft.Compute/', 'locations/', location, ...
608,130
Delete a container group from a resource group. Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. resource_group (str): Azure resource group name. container_group_name (str): Name of container instance group. Returns: ...
def delete_container_instance_group(access_token, subscription_id, resource_group, container_group_name): endpoint = ''.join([get_rm_endpoint(), '/subscriptions/', subscription_id, '/resourcegroups/', resource_group, ...
608,138
Get the JSON definition of a container group. Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. resource_group (str): Azure resource group name. container_group_name (str): Name of container instance group. Returns: ...
def get_container_instance_group(access_token, subscription_id, resource_group, container_group_name): endpoint = ''.join([get_rm_endpoint(), '/subscriptions/', subscription_id, '/resourcegroups/', resource_group, ...
608,139
Get the container logs for containers in a container group. Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. resource_group (str): Azure resource group name. container_group_name (str): Name of container instance group. ...
def get_container_instance_logs(access_token, subscription_id, resource_group, container_group_name, container_name=None): if container_name is None: container_name = container_group_name endpoint = ''.join([get_rm_endpoint(), '/subscriptions/...
608,140
List the container groups in a resource group. Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. resource_group (str): Azure resource group name. Returns: HTTP response. JSON list of container groups and their properties...
def list_container_instance_groups(access_token, subscription_id, resource_group): endpoint = ''.join([get_rm_endpoint(), '/subscriptions/', subscription_id, '/resourcegroups/', resource_group, '/providers/Microsoft.ContainerInstance/Conta...
608,141
List the container groups in a subscription. Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. Returns: HTTP response. JSON list of container groups and their properties.
def list_container_instance_groups_sub(access_token, subscription_id): endpoint = ''.join([get_rm_endpoint(), '/subscriptions/', subscription_id, '/providers/Microsoft.ContainerInstance/ContainerGroups', '?api-version=', CONTAINER_API]) ...
608,142
Create a resource group in the specified location. Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. rgname (str): Azure resource group name. location (str): Azure data center location. E.g. westus. Returns: HTTP...
def create_resource_group(access_token, subscription_id, rgname, location): endpoint = ''.join([get_rm_endpoint(), '/subscriptions/', subscription_id, '/resourcegroups/', rgname, '?api-version=', RESOURCE_API]) rg_body = {'location': l...
608,143
Delete the named resource group. Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. rgname (str): Azure resource group name. Returns: HTTP response.
def delete_resource_group(access_token, subscription_id, rgname): endpoint = ''.join([get_rm_endpoint(), '/subscriptions/', subscription_id, '/resourcegroups/', rgname, '?api-version=', RESOURCE_API]) return do_delete(endpoint, access_...
608,144
Capture the specified resource group as a template Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. rgname (str): Azure resource group name. Returns: HTTP response. JSON body.
def export_template(access_token, subscription_id, rgname): endpoint = ''.join([get_rm_endpoint(), '/subscriptions/', subscription_id, '/resourcegroups/', rgname, '/exportTemplate', '?api-version=', RESOURCE_API]) ...
608,145
Get details about the named resource group. Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. rgname (str): Azure resource group name. Returns: HTTP response. JSON body.
def get_resource_group(access_token, subscription_id, rgname): endpoint = ''.join([get_rm_endpoint(), '/subscriptions/', subscription_id, '/resourceGroups/', rgname, '?api-version=', RESOURCE_API]) return do_get(endpoint, access_token)
608,146
List the resource groups in a subscription. Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. Returns: HTTP response.
def list_resource_groups(access_token, subscription_id): endpoint = ''.join([get_rm_endpoint(), '/subscriptions/', subscription_id, '/resourceGroups/', '?api-version=', RESOURCE_API]) return do_get(endpoint, access_token)
608,147
Load an FCS file from a bytes-like object. Args: data: buffer containing contents of an FCS file. Returns: FCSParser instance with data loaded
def from_data(cls, data): obj = cls() with contextlib.closing(BytesIO(data)) as file_handle: obj.load_file(file_handle) return obj
608,187
Read the header of the FCS file. The header specifies where the annotation, data and analysis are located inside the binary file. Args: file_handle: buffer containing FCS file. nextdata_offset: byte offset of a set header from file start specified by $NEXTDATA
def read_header(self, file_handle, nextdata_offset=0): header = {'FCS format': file_handle.read(6)} file_handle.read(4) # 4 space characters after the FCS format for field in ('text start', 'text end', 'data start', 'data end', 'analysis start', 'analysis end'):...
608,188
Read the ANALYSIS segment of the FCS file and store it in self.analysis. Warning: This has never been tested with an actual fcs file that contains an analysis segment. Args: file_handle: buffer containing FCS data
def read_analysis(self, file_handle): start = self.annotation['__header__']['analysis start'] end = self.annotation['__header__']['analysis end'] if start != 0 and end != 0: file_handle.seek(start, 0) self._analysis = file_handle.read(end - start) else: ...
608,191
Unravels section type dictionary into flat list of sections with section type set as an attribute. Args: section_data(dict): Data return from py:method::get_sections Returns: list: Flat list of sections with ``sectionType`` set to type (i.e. recitation, ...
def unravel_sections(section_data): sections = [] for type, subsection_list in section_data.items(): for section in subsection_list: section['sectionType'] = type sections.append(section) return sections
608,358
Unravels staff role dictionary into flat list of staff members with ``role`` set as an attribute. Args: staff_data(dict): Data return from py:method::get_staff Returns: list: Flat list of staff members with ``role`` set to role type (i.e. course_admin, ...
def unravel_staff(staff_data): staff_list = [] for role, staff_members in staff_data['data'].items(): for member in staff_members: member['role'] = role staff_list.append(member) return staff_list
608,359
Return gradebookid for a given gradebook uuid. Args: gbuuid (str): gradebook uuid, i.e. ``STELLAR:/project/gbngtest`` Raises: PyLmodUnexpectedData: No gradebook id returned requests.RequestException: Exception connection error ValueError: Unable to decod...
def get_gradebook_id(self, gbuuid): gradebook = self.get('gradebook', params={'uuid': gbuuid}) if 'data' not in gradebook: failure_messsage = ('Error in get_gradebook_id ' 'for {0} - no data'.format( gradebook ...
608,360
Get group data based on uuid. Args: uuid (str): optional uuid. defaults to self.cuuid Raises: PyLmodUnexpectedData: No data was returned. requests.RequestException: Exception connection error Returns: dict: group json
def get_group(self, uuid=None): if uuid is None: uuid = self.uuid group_data = self.get('group', params={'uuid': uuid}) return group_data
608,375
Get group id based on uuid. Args: uuid (str): optional uuid. defaults to self.cuuid Raises: PyLmodUnexpectedData: No group data was returned. requests.RequestException: Exception connection error Returns: int: numeric group id
def get_group_id(self, uuid=None): group_data = self.get_group(uuid) try: return group_data['response']['docs'][0]['id'] except (KeyError, IndexError): failure_message = ('Error in get_group response data - ' 'got {0}'.format(group_...
608,376
Get membership data based on uuid. Args: uuid (str): optional uuid. defaults to self.cuuid Raises: PyLmodUnexpectedData: No data was returned. requests.RequestException: Exception connection error Returns: dict: membership json
def get_membership(self, uuid=None): group_id = self.get_group_id(uuid=uuid) uri = 'group/{group_id}/member' mbr_data = self.get(uri.format(group_id=group_id), params=None) return mbr_data
608,377
Determine if an email is associated with a role. Args: email (str): user email role_name (str): user role uuid (str): optional uuid. defaults to self.cuuid Raises: PyLmodUnexpectedData: Unexpected data was returned. requests.RequestException:...
def email_has_role(self, email, role_name, uuid=None): mbr_data = self.get_membership(uuid=uuid) docs = [] try: docs = mbr_data['response']['docs'] except KeyError: failure_message = ('KeyError in membership data - ' 'got {0...
608,378
Get course id based on uuid. Args: uuid (str): course uuid, i.e. /project/mitxdemosite Raises: PyLmodUnexpectedData: No course data was returned. requests.RequestException: Exception connection error Returns: int: numeric course id
def get_course_id(self, course_uuid): course_data = self.get( 'courseguide/course?uuid={uuid}'.format( uuid=course_uuid or self.course_id ), params=None ) try: return course_data['response']['docs'][0]['id'] except ...
608,379
Initialize Base instance. Args: cert (unicode): File path to the certificate used to authenticate access to LMod Web service urlbase (str): The URL of the LMod Web service. i.e. ``learning-modules.mit.edu`` or ``learning-modules-test.mit.e...
def __init__( self, cert, urlbase='https://learning-modules.mit.edu:8443/', ): # pem with private and public key application certificate for access self.cert = cert self.urlbase = urlbase if not urlbase.endswith('/'): self.url...
608,381
Convert to json if it isn't already a string. Args: data (str): data to convert to json
def _data_to_json(data): if type(data) not in [str, unicode]: data = json.dumps(data) return data
608,382
Generate URL from urlbase and service. Args: service (str): The endpoint service to use, i.e. gradebook Returns: str: URL to where the request should be made
def _url_format(self, service): base_service_url = '{base}{service}'.format( base=self.urlbase, service=service ) return base_service_url
608,383
Routine to do low-level REST operation, with retry. Args: func (callable): API function to call url (str): service URL endpoint kwargs (dict): addition parameters Raises: requests.RequestException: Exception connection error ValueError: Unabl...
def rest_action(self, func, url, **kwargs): try: response = func(url, timeout=self.TIMEOUT, **kwargs) except requests.RequestException, err: log.exception( "[PyLmod] Error - connection error in " "rest_action, err=%s", err ) ...
608,384
Generic DELETE operation for Learning Modules API. Args: service (str): The endpoint service to use, i.e. gradebook Raises: requests.RequestException: Exception connection error ValueError: Unable to decode response content Returns: list: the js...
def delete(self, service): url = self._url_format(service) return self.rest_action( self._session.delete, url )
608,387
Mark the job as failed, and record the traceback and exception. Args: job_id: The job_id of the job that failed. exception: The exception object thrown by the job. traceback: The traceback, if any. Note (aron): Not implemented yet. We need to find a way for the co...
def mark_job_as_failed(self, job_id, exception, traceback): session = self.sessionmaker() job, orm_job = self._update_job_state( job_id, State.FAILED, session=session) # Note (aron): looks like SQLAlchemy doesn't automatically # save any pickletype fields even if we...
608,577
Start or cancel a job, based on the msg. If msg.type == MessageType.START_JOB, then start the job given by msg.job. If msg.type == MessageType.CANCEL_JOB, then try to cancel the job given by msg.job.job_id. Args: msg (barbequeue.messaging.classes.Message): Returns: None
def handle_incoming_message(self, msg): if msg.type == MessageType.START_JOB: job = msg.message['job'] self.schedule_job(job) elif msg.type == MessageType.CANCEL_JOB: job_id = msg.message['job_id'] self.cancel(job_id)
608,585
Call the function normally. But if the function raises an error, attach the str(traceback) into the function.traceback attribute, then reraise the error. Args: f: The function to run. Returns: A function that wraps f, attaching the traceback if an error occurred.
def _reraise_with_traceback(f): def wrap(*args, **kwargs): try: return f(*args, **kwargs) except Exception as e: traceback_str = traceback.format_exc() e.traceback = traceback_str raise e return wrap
608,594
Shut down the worker message handler and scheduler threads. Args: wait: If true, block until both threads have successfully shut down. If False, return immediately. Returns: None
def shutdown(self, wait=True): self.scheduler_thread.stop() self.worker_message_handler_thread.stop() if wait: self.scheduler_thread.join() self.worker_message_handler_thread.join()
608,604
Read messages that are placed in self.incoming_mailbox, and then update the job states corresponding to each message. Args: timeout: How long to wait for an incoming message, if the mailbox is empty right now. Returns: None
def handle_worker_messages(self, timeout): msgs = self.messaging_backend.popn(self.incoming_mailbox, n=20) for msg in msgs: self.handle_single_message(msg)
608,607
Compute the planar cross section of a mesh. This returns a set of polylines. Args: verts: Nx3 array of the vertices position faces: Nx3 array of the faces, containing vertex indices plane_orig: 3-vector indicating the plane origin plane_normal: 3-vector indicating the plane norm...
def cross_section(verts, tris, plane_orig, plane_normal, **kwargs): mesh = TriangleMesh(verts, tris) plane = Plane(plane_orig, plane_normal) return cross_section_mesh(mesh, plane, **kwargs)
608,674
Gives the force of solution j on solution i. Variable name in GSA paper given in () args: grav: The gravitational constant. (G) mass_i: The mass of solution i (derived from fitness). (M_i) mass_j: The mass of solution j (derived from fitness). (M_j) position_i: The position of ...
def _gsa_force(grav, mass_i, mass_j, position_i, position_j): position_diff = numpy.subtract(position_j, position_i) distance = numpy.linalg.norm(position_diff) # The first 3 terms give the magnitude of the force # The last term is a vector that provides the direction # Epsilon prevents divid...
608,721
Return a randomly weighted sum of the force vectors. args: force_vectors: A list of force vectors on solution i. returns: numpy.array; The total force on solution i.
def _gsa_total_force(force_vectors, vector_length): if len(force_vectors) == 0: return [0.0] * vector_length # The GSA algorithm specifies that the total force in each dimension # is a random sum of the individual forces in that dimension. # For this reason we sum the dimensions individuall...
608,722
Scale values in vector to the range [0, 1]. Args: vector: A list of real values.
def _rescale(vector): # Subtract min, making smallest value 0 min_val = min(vector) vector = [v - min_val for v in vector] # Divide by max, making largest value 1 max_val = float(max(vector)) try: return [v / max_val for v in vector] except ZeroDivisionError: # All values are ...
608,745
Get the fitness for every solution in a population. Args: problem: Problem; The problem that defines fitness. population: list; List of potential solutions. pool: None/multiprocessing.Pool; Pool of processes for parallel decoding and evaluation.
def _get_fitnesses(self, problem, population, cache_encoded=True, cache_solution=False, pool=None): fitnesses = [None] * len(population) ############################# # De...
608,768
Initialize general optimization attributes and bookkeeping Args: solution_size: The number of values in each solution. population_size: The number of solutions in every generation.
def __init__(self, solution_size, population_size=20): super(StandardOptimizer, self).__init__() # Set general algorithm paramaters self._solution_size = solution_size self._population_size = population_size # Parameters for metaheuristic optimization self._hyp...
608,775
Run an optimizer through a problem multiple times. Args: optimizer: Optimizer; The optimizer to benchmark. problem: Problem; The problem to benchmark on. runs: int > 0; Number of times that optimize is called on problem. Returns: dict; A dictionary of various statistics.
def benchmark(optimizer, problem, runs=20, **kwargs): stats = {'runs': []} # Disable logging, to avoid spamming the user # TODO: Maybe we shouldn't disable by default? kwargs = copy.copy(kwargs) kwargs['logging_func'] = None # Determine effectiveness of metaheuristic over many runs # ...
608,777
Combine stats for multiple optimizers to obtain one mean and sd. Useful for combining stats for the same optimizer class and multiple problems. Args: all_stats: dict; output from compare.
def aggregate(all_stats): aggregate_stats = {'means': [], 'standard_deviations': []} for optimizer_key in all_stats: # runs is the mean, for add_mean_sd function mean_stats = copy.deepcopy(all_stats[optimizer_key]['mean']) mean_stats['name'] = optimizer_key aggregate_stats['...
608,778
Obtain the mean of stats. Args: stats: dict; A set of stats, structured as above. key: str; Optional key to determine where list of runs is found in stats
def _mean_of_runs(stats, key='runs'): num_runs = len(stats[key]) first = stats[key][0] mean = {} for stat_key in first: # Skip non numberic attributes if isinstance(first[stat_key], numbers.Number): mean[stat_key] = sum(run[stat_key] fo...
608,780
Obtain the standard deviation of stats. Args: stats: dict; A set of stats, structured as above. mean: dict; Mean for each key in stats. key: str; Optional key to determine where list of runs is found in stats
def _sd_of_runs(stats, mean, key='runs'): num_runs = len(stats[key]) first = stats[key][0] standard_deviation = {} for stat_key in first: # Skip non numberic attributes if isinstance(first[stat_key], numbers.Number): standard_deviation[stat_key] = math.sqrt( ...
608,781
Make a new population after each optimization iteration. Args: population: The population current population of solutions. fitnesses: The fitness associated with each solution in the population Returns: list; a list of solutions.
def next_population(self, population, fitnesses): # Update probability vector self._probability_vec = _adjust_probability_vec_best( population, fitnesses, self._probability_vec, self._adjust_rate) # Mutate probability vector _mutate_probability_vec(self._probability...
608,786
Create an object that optimizes a given fitness function with random strings. Args: solution_size: The number of bits in every solution. population_size: The number of solutions in every iteration.
def __init__(self, solution_size, population_size=20): super(_RandomOptimizer, self).__init__(solution_size, population_size)
608,800
Make a new population after each optimization iteration. Args: population: The population current population of solutions. fitnesses: The fitness associated with each solution in the population Returns: list; a list of solutions.
def next_population(self, population, fitnesses): return common.make_population(self._population_size, self._generate_solution)
608,801
Create an object that optimizes a given fitness function. Args: solution_size: The number of bits in every solution. population_size: The number of solutions in every iteration.
def __init__(self, solution_size, population_size=20): super(ExhaustiveBinary, self).__init__(solution_size, population_size) self._next_int = 0
608,804
Make a new population after each optimization iteration. Args: population: The population current population of solutions. fitnesses: The fitness associated with each solution in the population Returns: list; a list of solutions.
def next_population(self, population, fitnesses): return [self._next_solution() for _ in range(self._population_size)]
608,805
For some x, predict the bn(x) for each base Arguments: x: np.array; Vector of dimension 1 add_intercept: bool; should we add the intercept to the final array Returns: np.array, of shape (len(x), n_bases + (add_intercept))
def predict(self, x, add_intercept=False): # sanity check if x.min() < self.start: raise Warning("x.min() < self.start") if x.max() > self.end: raise Warning("x.max() > self.end") return get_X_spline(x=x, knots=self.knots, ...
609,254
Recall at a certain precision threshold Args: y_true: true labels y_pred: predicted labels precision: resired precision level at which where to compute the recall
def recall_at_precision(y_true, y_pred, precision): y_true, y_pred = _mask_value_nan(y_true, y_pred) precision, recall, _ = skm.precision_recall_curve(y_true, y_pred) return recall[np.searchsorted(precision - precision, 0)]
609,263
Predict the response variable :py:attr:`y` for new input data (:py:attr:`X_feat`, :py:attr:`X_seq`). Args: X_feat: Feature design matrix. Same format as :py:attr:`X_feat` in :py:meth:`train` X_seq: Sequenc design matrix. Same format as :py:attr:`X_seq` in :py:meth:`train`
def predict(self, X_feat, X_seq): # insert one dimension - backcompatiblity X_seq = np.expand_dims(X_seq, axis=1) return self._get_other_var(X_feat, X_seq, variable="y_pred")
609,404
Add a signature block to marfile, a MarReader object. Productversion and channel are preserved, but any existing signatures are overwritten. Args: src_fileobj (file object): The input MAR file to add a signature to dest_fileobj (file object): File object to write new MAR file to. Must be open ...
def add_signature_block(src_fileobj, dest_fileobj, signing_algorithm, signature=None): algo_id = {'sha1': 1, 'sha384': 2}[signing_algorithm] if not signature: signature = make_dummy_signature(algo_id) src_fileobj.seek(0) mardata = mar.parse_stream(src_fileobj) # Header header = ma...
609,718
Add `path` to the MAR file. If `path` is a file, it will be added directly. If `path` is a directory, it will be traversed recursively and all files inside will be added. Args: path (str): path to file or directory on disk to add to this MAR file ...
def add(self, path, compress=None): if os.path.isdir(path): self.add_dir(path, compress) else: self.add_file(path, compress)
609,720
Add all files under directory `path` to the MAR file. Args: path (str): path to directory to add to this MAR file compress (str): One of 'xz', 'bz2', or None. Defaults to None.
def add_dir(self, path, compress): if not os.path.isdir(path): raise ValueError('{} is not a directory'.format(path)) for root, dirs, files in os.walk(path): for f in files: self.add_file(os.path.join(root, f), compress)
609,721
Add the contents of a file object to the MAR file. Args: fileobj (file-like object): open file object path (str): name of this file in the MAR file compress (str): One of 'xz', 'bz2', or None. Defaults to None. flags (int): permission of this file in the MAR file...
def add_fileobj(self, fileobj, path, compress, flags=None): f = file_iter(fileobj) flags = flags or os.stat(path) & 0o777 return self.add_stream(f, path, compress, flags)
609,722
Add the contents of an iterable to the MAR file. Args: stream (iterable): yields blocks of data path (str): name of this file in the MAR file compress (str): One of 'xz', 'bz2', or None. Defaults to None. flags (int): permission of this file in the MAR file
def add_stream(self, stream, path, compress, flags): self.data_fileobj.seek(self.last_offset) if compress == 'bz2': stream = bz2_compress_stream(stream) elif compress == 'xz': stream = xz_compress_stream(stream) elif compress is None: pass ...
609,723
Add a single file to the MAR file. Args: path (str): path to a file to add to this MAR file. compress (str): One of 'xz', 'bz2', or None. Defaults to None.
def add_file(self, path, compress): if not os.path.isfile(path): raise ValueError('{} is not a file'.format(path)) self.fileobj.seek(self.last_offset) with open(path, 'rb') as f: flags = os.stat(path).st_mode & 0o777 self.add_fileobj(f, path, compres...
609,724
Write signature data to the MAR file. Args: signatures (list): list of signature tuples of the form (algorithm_id, signature_data)
def write_signatures(self, signatures): self.fileobj.seek(self.signature_offset) sig_entries = [dict(algorithm_id=id_, size=len(sig), signature=sig) for (id_, sig) in signatures] sigs = sigs_header.build(dic...
609,728
Write the additional information to the MAR header. Args: productversion (str): product and version string channel (str): channel string
def write_additional(self, productversion, channel): self.fileobj.seek(self.additional_offset) extras = extras_header.build(dict( count=1, sections=[dict( channel=six.u(channel), productversion=six.u(productversion), size=l...
609,729
Get public keys for the given keyfiles. Args: keyfiles: List of filenames with public keys, or :mozilla- prefixed key names signature_type: one of 'sha1' or 'sha384' Returns: List of public keys as strings
def get_keys(keyfiles, signature_type): builtin_keys = { ('release', 'sha1'): [mardor.mozilla.release1_sha1, mardor.mozilla.release2_sha1], ('release', 'sha384'): [mardor.mozilla.release1_sha384, mardor.mozilla.release2_sha384], ('nightly', 'sha1'): [mardor.mozilla.nightly1_sha1, mardor...
609,734
Initialize a new MarReader object. Note: Files should always be opened in binary mode. Args: fileobj (file object): A file-like object open in read mode where the MAR data will be read from. This object must also be seekable (i.e. support .seek(...
def __init__(self, fileobj): self.fileobj = fileobj self.mardata = mar.parse_stream(self.fileobj)
609,743
Extract the entire MAR file into a directory. Args: destdir (str): A local directory on disk into which the contents of this MAR file will be extracted. Required parent directories will be created as necessary. decompress (obj, optional): Controls whether...
def extract(self, destdir, decompress='auto'): for e in self.mardata.index.entries: name = e.name entry_path = safejoin(destdir, name) entry_dir = os.path.dirname(entry_path) mkdir(entry_dir) with open(entry_path, 'wb') as f: w...
609,747
Verify that this MAR file has a valid signature. Args: verify_key (str): PEM formatted public key Returns: True if the MAR file's signature matches its contents False otherwise; this includes cases where there is no signature.
def verify(self, verify_key): if not self.mardata.signatures or not self.mardata.signatures.sigs: # This MAR file can't be verified since it has no signatures return False hashers = [] for sig in self.mardata.signatures.sigs: hashers.append((sig.algo...
609,752
Determine if a MAR file has an additional section block or not. It does this by looking at where file data starts in the file. If this starts immediately after the signature data, then no additional sections are present. Args: ctx (context): construct parsing context Returns: True if ...
def _has_extras(ctx): if not ctx.index.entries: return False return ctx.data_offset > 8 and ctx.data_offset > (ctx.signatures.offset_end + 8)
609,755
Read data from MAR file that is required for MAR signatures. Args: fileboj (file-like object): file-like object to read the MAR data from filesize (int): the total size of the file Yields: blocks of bytes representing the data required to generate or validate signatures.
def get_signature_data(fileobj, filesize): # Read everything except the signature entries # The first 8 bytes are covered, as is everything from the beginning # of the additional section to the end of the file. The signature # algorithm id and size fields are also covered. fileobj.seek(0) ...
609,759
Sign the given hash with the given private key. Args: private_key (str): PEM enoded private key hash (byte str): hash to sign hash_algo (str): name of hash algorithm used Returns: byte string representing the signature
def sign_hash(private_key, hash, hash_algo): hash_algo = _hash_algorithms[hash_algo] return get_privatekey(private_key).sign( hash, padding.PKCS1v15(), utils.Prehashed(hash_algo), )
609,761
Verify the given signature is correct for the given hash and public key. Args: public_key (str): PEM encoded public key signature (bytes): signature to verify hash (bytes): hash of data hash_algo (str): hash algorithm used Returns: True if the signature is valid, False ...
def verify_signature(public_key, signature, hash, hash_algo): hash_algo = _hash_algorithms[hash_algo] try: return get_publickey(public_key).verify( signature, hash, padding.PKCS1v15(), utils.Prehashed(hash_algo), ) is None except InvalidSi...
609,762
Generate an RSA keypair. Args: bits (int): number of bits to use for the key. Returns: (private_key, public_key) - both as PEM encoded strings
def make_rsa_keypair(bits): private_key = rsa.generate_private_key( public_exponent=65537, key_size=bits, backend=default_backend(), ) private_pem = private_key.private_bytes( encoding=serialization.Encoding.PEM, format=serialization.PrivateFormat.TraditionalOpen...
609,763
Make a directory and its parents. Args: path (str): path to create Returns: None Raises: OSError if the directory cannot be created.
def mkdir(path): try: os.makedirs(path) # sanity check if not os.path.isdir(path): # pragma: no cover raise IOError('path is not a directory') except OSError as e: # EEXIST if e.errno == 17 and os.path.isdir(path): return raise
609,764
Yield blocks from `iterable` until exactly len(size) have been returned. Args: iterable (iterable): Any iterable that yields sliceable objects that have length. size (int): How much data to consume Yields: blocks from `iterable` such that sum(len(bl...
def takeexactly(iterable, size): total = 0 for block in iterable: n = min(len(block), size - total) block = block[:n] if block: yield block total += len(block) if total >= size: break if total < size: raise ValueError('not enough d...
609,765
Write data from `src` into `dst`. Args: src (iterable): iterable that yields blocks of data to write dst (file-like object): file-like object that must support .write(block) Returns: number of bytes written to `dst`
def write_to_file(src, dst): n = 0 for block in src: dst.write(block) n += len(block) return n
609,766
Compress data from `src`. Args: src (iterable): iterable that yields blocks of data to compress level (int): compression level (1-9) default is 9 Yields: blocks of compressed data
def bz2_compress_stream(src, level=9): compressor = bz2.BZ2Compressor(level) for block in src: encoded = compressor.compress(block) if encoded: yield encoded yield compressor.flush()
609,767
Decompress data from `src`. Args: src (iterable): iterable that yields blocks of compressed data Yields: blocks of uncompressed data
def bz2_decompress_stream(src): dec = bz2.BZ2Decompressor() for block in src: decoded = dec.decompress(block) if decoded: yield decoded
609,768
Compress data from `src`. Args: src (iterable): iterable that yields blocks of data to compress Yields: blocks of compressed data
def xz_compress_stream(src): compressor = lzma.LZMACompressor( check=lzma.CHECK_CRC64, filters=[ {"id": lzma.FILTER_X86}, {"id": lzma.FILTER_LZMA2, "preset": lzma.PRESET_DEFAULT}, ]) for block in src: encoded = compressor.compress(block) ...
609,769
Decompress data from `src`. Args: src (iterable): iterable that yields blocks of compressed data Yields: blocks of uncompressed data
def xz_decompress_stream(src): dec = lzma.LZMADecompressor() for block in src: decoded = dec.decompress(block) if decoded: yield decoded if dec.unused_data: # pragma: nocover; can't figure out how to test this raise IOError('Read unused data at end of compressed st...
609,770
Decompress data from `src` if required. If the first block of `src` appears to be compressed, then the entire stream will be uncompressed. Otherwise the stream will be passed along as-is. Args: src (iterable): iterable that yields blocks of data Yields: blocks of uncompressed data
def auto_decompress_stream(src): block = next(src) compression = guess_compression(block) if compression == 'bz2': src = bz2_decompress_stream(chain([block], src)) elif compression == 'xz': src = xz_decompress_stream(chain([block], src)) else: src = chain([block], src) ...
609,771
Safely joins paths together. The result will always be a subdirectory under `base`, otherwise ValueError is raised. Args: base (str): base path elements (list of strings): path elements to join to base Returns: elements joined to base
def safejoin(base, *elements): # TODO: do we really want to be absolute here? base = os.path.abspath(base) path = os.path.join(base, *elements) path = os.path.normpath(path) if not path_is_inside(path, base): raise ValueError('target path is outside of the base path') return path
609,773
Write nexus files to {workdir}/{name}/[0-N].nex, If the directory already exists an exception will be raised unless you use the force flag which will remove all files in the directory. Parameters: ----------- force (bool): If True then all files in {workdir}/{name}...
def write_nexus_files(self, force=False, quiet=False): ## clear existing files existing = glob.glob(os.path.join(self.workdir, self.name, "*.nex")) if any(existing): if force: for rfile in existing: os.remove(rfile) else: ...
610,065
Writes bpp files (.ctl, .seq, .imap) to the working directory. Parameters: ------------ randomize_order (bool): whether to randomize the locus order, this will allow you to sample different subsets of loci in different replicates when using the filters.maxl...
def write_bpp_files(self, randomize_order=False, quiet=False): ## remove any old jobs with this same job name self._name = self.name oldjobs = glob.glob(os.path.join(self.workdir, self._name+"*.ctl.txt")) for job in oldjobs: os.remove(job) ## check params t...
610,160