output stringlengths 1 928k | instruction stringlengths 7 928k | system stringlengths 0 104k |
|---|---|---|
def fetch(self, fetch_notes=None):
""" update remote values (called automatically at __init__) """
if fetch_notes is None:
fetch_notes = self.fetch_notes
values, notes_index = get_sheet_values(self.name, self.sheet_name,
spreadsheet_serv... | Write a Python 3 script for
fetching the values from the remote data store | You are a Python code analyst, evaluating scripts for potential improvements. |
Add types to the set of classes that are not in the hierarchy. | Here you have a function in Python 3, explain what it does
def add_types(graph, phenotypes): # TODO missing expression phenotypes! also basket type somehow :(
collect = defaultdict(set)
def recurse(id_, start, level=0):
#print(level)
for t in graph.g.triples((None, None, id_)):
if ... | As a python code expert, you are capable of creating scripts from specifications. |
Make the phenotype of the neuron. | Here you have a function in Python 3, explain what it does
def _rest_make_phenotypes():
#phenotype sources
neuroner = Path(devconfig.git_local_base,
'neuroNER/resources/bluima/neuroner/hbp_morphology_ontology.obo').as_posix()
neuroner1 = Path(devconfig.git_local_base,
'neuro... | As a Python code analyst, you investigate and solve complex coding mysteries |
Allows changing the config on the fly | Can you tell what is the following Python 3 function doing
def config(self):
# TODO more efficient to read once and put watch on the file
config = {}
if self.config_file.exists():
with open(self.config_file.as_posix(), 'rt') as f: # 3.5/pypy3 can't open Path directly
... | You are a Python code architect, reviewing and designing scalable and efficient code |
Retrieve json dict from service account file. | How would you explain what the following Python 3 function does
def _get_service_account_info(self):
with open(self.service_account_file, 'r') as f:
info = json.load(f)
self.service_account_email = info.get('client_email')
if not self.service_account_email:
raise GCEClou... | You are a Python code architect, reviewing and designing scalable and efficient code |
Get authenticated GCE driver. | Given the following Python 3 function, write the documentation
def _get_driver(self):
ComputeEngine = get_driver(Provider.GCE)
return ComputeEngine(
self.service_account_email,
self.service_account_file,
project=self.service_account_project
) | You are a Python code analyst, evaluating scripts for potential improvements. |
Retrieve instance matching instance_id. | Given the following Python 3 function, write the documentation
def _get_instance(self):
try:
instance = self.compute_driver.ex_get_node(
self.running_instance_id,
zone=self.region
)
except ResourceNotFoundError as e:
raise GCECloudExcep... | You are a Python code analyst, evaluating scripts for potential improvements. |
def _get_ssh_public_key(self):
"""Generate SSH public key from private key."""
key = ipa_utils.generate_public_ssh_key(self.ssh_private_key_file)
return '{user}:{key} {user}'.format(
user=self.ssh_user,
key=key.decode()
) | Write a Python 3 script to
generate SSH public key from private key. | As a Python code analyst, you investigate and solve complex coding mysteries |
Launch an instance of the given image. | Here you have a function in Python 3, explain what it does
def _launch_instance(self):
metadata = {'key': 'ssh-keys', 'value': self.ssh_public_key}
self.running_instance_id = ipa_utils.generate_instance_name(
'gce-ipa-test'
)
self.logger.debug('ID of instance: %s' % self.runn... | You are a Python code generator, capable of creating scripts from specifications. |
def _validate_region(self):
"""Validate region was passed in and is a valid GCE zone."""
if not self.region:
raise GCECloudException(
'Zone is required for GCE cloud framework: '
'Example: us-west1-a'
)
try:
zone = self.compute... | Can you write a function in Python 3 where it
validates region was passed in and is a valid GCE zone. | You are a Python code generator, capable of creating scripts from specifications. |
Retrieve and set the instance ip address. | Can you generate the documentation for the following Python 3 function
def _set_instance_ip(self):
instance = self._get_instance()
if instance.public_ips:
self.instance_ip = instance.public_ips[0]
elif instance.private_ips:
self.instance_ip = instance.private_ips[0]
... | As a Python code analyst, you investigate and solve complex coding mysteries |
Grab the version of the ontology from the graph | Can you tell what is the following Python 3 function doing
def grab_rdflib_graph_version(g: Graph) -> str:
''' Crap-shot for ontology iri if its properly in the header and correctly formated '''
version = g.subject_objects( predicate = URIRef( OWL.versionIRI ) )
version = [o for s, o in version]... | As a python code expert, you are capable of creating scripts from specifications. |
def fix_ilx(self, ilx_id: str) -> str:
''' Database only excepts lower case and underscore version of ID '''
ilx_id = ilx_id.replace('http://uri.interlex.org/base/', '')
if ilx_id[:4] not in ['TMP:', 'tmp_', 'ILX:', 'ilx_']:
raise ValueError(
'Need to provide ilx ID w... | Create a Python 3 function to
fix ILX ID in database only excepts lower case and underscore version of ID | You are a Python code architect, reviewing and designing scalable and efficient code |
Used for getting the tail of the string from the end of the string. | How would you explain what the following Python 3 function does
def pull_int_tail(self, string: str) -> str:
''' Useful for IDs that have giberish in the front of the real ID '''
int_tail = ''
for element in string[::-1]:
try:
int(element)
int_tail = e... | As a python code expert, you are capable of creating scripts from specifications. |
Extracts the fragment from the given IRI | Can you tell what is the following Python 3 function doing
def extract_fragment(self, iri: str) -> str:
''' Pulls only for code/ID from the iri
I only add the str() conversion for the iri because rdflib objects need to be converted.
'''
fragment = str(iri).rsplit('/')[-1].split(':', 1)[... | As a Python code analyst, you investigate and solve complex coding mysteries |
def curie_search(self, curie:str) -> dict:
''' Returns the row in InterLex associated with the curie
Note:
Pressumed to not have duplicate curies in InterLex
Args:
curie: The "prefix:fragment_id" of the existing_id pertaining to the ontology
Returns:
... | Implement a Python 3 function for
searching the InterLex table for the specified curie and returns the row in InterLex associated with the curie. | You are a Python code generator, capable of creating scripts from specifications. |
def fragment_search(self, fragement:str) -> List[dict]:
''' Returns the rows in InterLex associated with the fragment
Note:
Pressumed to have duplicate fragements in InterLex
Args:
fragment: The fragment_id of the curie pertaining to the ontology
Returns:
... | Create a Python 3 function for
returning the rows in InterLex associated with the fragment_id | As a Python code analyst, you investigate and solve complex coding mysteries |
Returns the rows in InterLex associated with that label | Can you generate a brief explanation for the following Python 3 code
def label_search(self, label:str) -> List[dict]:
''' Returns the rows in InterLex associated with that label
Note:
Pressumed to have duplicated labels in InterLex
Args:
label: label of the entity you wa... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Check if the label_predicate is in the label2rows of the entity and if so get a full diff between the curie matches | Here you have a function in Python 3, explain what it does
def exhaustive_label_check( self,
ontology:pd.DataFrame,
label_predicate='rdfs:label',
diff:bool=True, ) -> Tuple[list]:
''' All entities with conflicting la... | As a Python code analyst, you investigate and solve complex coding mysteries |
def exhaustive_curie_check( self,
ontology:pd.DataFrame,
curie_predicate:str,
curie_prefix:str,
diff:bool=True, ) -> Tuple[list]:
''' All entities with conflicting curies gets a full d... | Write a Python 3 function that can
check if all entities with conflicting curies get a full diff to see if they belong. | As a Python code translator, you convert algorithms and pseudocode into Python. |
def exhaustive_fragment_check( self,
ontology:pd.DataFrame,
iri_curie_fragment_predicate:str = 'iri',
cross_reference_iris:bool = False,
cross_reference_fragments:bool = False,
... | Create a Python 3 function for
checking if entities with conflicting fragments get a full diff to see if they belong | You are a Python code architect, reviewing and designing scalable and efficient code |
This method is used to exhaustive the ontology ilx diff for each row of an ontology. | Explain what the following Python 3 code does
def exhaustive_ontology_ilx_diff_row_only( self, ontology_row: dict ) -> dict:
''' WARNING RUNTIME IS AWEFUL '''
results = []
header = ['Index'] + list(self.existing_ids.columns)
for row in self.existing_ids.itertuples():
row = {h... | As a Python code analyst, you investigate and solve complex coding mysteries |
def combo_exhaustive_label_definition_check( self,
ontology: pd.DataFrame,
label_predicate:str,
definition_predicates:str,
d... | Can you write a function in Python 3 where it
combines the label & definition exhaustive check out of convenience | As a python code expert, you are capable of creating scripts from specifications. |
def clear_cache(ip=None):
"""Clear the client cache or remove key matching the given ip."""
if ip:
with ignored(Exception):
client = CLIENT_CACHE[ip]
del CLIENT_CACHE[ip]
client.close()
else:
for client in CLIENT_CACHE.values():
with ignored(Ex... | Write a Python 3 function that can
clear the client cache or remove key matching the given ip. | As a Python code translator, you convert algorithms and pseudocode into Python. |
def establish_ssh_connection(ip,
ssh_private_key_file,
ssh_user,
port,
attempts=5,
timeout=None):
"""
Establish ssh connection and return paramiko client.
Raises:... | Create a Python 3 function for
establishing SSH connection to the instance. | You are a Python code architect, reviewing and designing scalable and efficient code |
def execute_ssh_command(client, cmd):
"""
Execute given command using paramiko.
Returns:
String output of cmd execution.
Raises:
IpaSSHException: If stderr returns a non-empty string.
"""
try:
stdin, stdout, stderr = client.exec_command(cmd)
err = stderr.read()
... | Implement a Python 3 function for
executing given command using paramiko. | You are a Python code generator, capable of creating scripts from specifications. |
Extract the archive in current path using the provided client. | Can you generate the documentation for the following Python 3 function
def extract_archive(client, archive_path, extract_path=None):
command = 'tar -xf {path}'.format(path=archive_path)
if extract_path:
command += ' -C {extract_path}'.format(extract_path=extract_path)
out = execute_ssh_command(cli... | You are a Python code analyst, evaluating scripts for potential improvements. |
def generate_public_ssh_key(ssh_private_key_file):
"""Generate SSH public key from private key file."""
try:
with open(ssh_private_key_file, "rb") as key_file:
key = key_file.read()
except FileNotFoundError:
raise IpaUtilsException(
'SSH private key file: %s cannot be... | How would you code a function in Python 3 to
generate SSH public key from private key file. | You are a Python code analyst, evaluating scripts for potential improvements. |
def get_config_values(config_path, section, default='default'):
"""
Parse ini config file and return a dict of values.
The provided section overrides any values in default section.
"""
values = {}
if not os.path.isfile(config_path):
raise IpaUtilsException(
'Config file not... | Write a Python 3 function that can
parse ini config file and return a dict of values. | As a Python code translator, you convert algorithms and pseudocode into Python. |
def get_ssh_client(ip,
ssh_private_key_file,
ssh_user='root',
port=22,
timeout=600,
wait_period=10):
"""Attempt to establish and test ssh connection."""
if ip in CLIENT_CACHE:
return CLIENT_CACHE[ip]
star... | Write a Python 3 script for
establishing and test SSH connection. | As a Python code composer, you craft elegant and concise scripts. |
def get_yaml_config(config_path):
"""
Load yaml config file and return dictionary.
Todo:
* This will need refactoring similar to the test search.
"""
config_path = os.path.expanduser(config_path)
if not os.path.isfile(config_path):
raise IpaUtilsException(
'Config fi... | Write a Python 3 script to
load yaml config file and return dictionary. | As a Python code composer, you craft elegant and concise scripts. |
def parse_sync_points(names, tests):
"""
Slice list of test names on sync points.
If test is test file find full path to file.
Returns:
A list of test file sets and sync point strings.
Examples:
['test_hard_reboot']
[set('test1', 'test2')]
[set('test1', 'test2'), 't... | Can you implement a function in Python 3 that
parses sync points into list of test files. | As a Python code composer, you craft elegant and concise scripts. |
Copy file to instance using Paramiko client connection. | Explain what the following Python 3 code does
def put_file(client, source_file, destination_file):
try:
sftp_client = client.open_sftp()
sftp_client.put(source_file, destination_file)
except Exception as error:
raise IpaUtilsException(
'Error copying file to instance: {0}.'.f... | You are a Python code architect, reviewing and designing scalable and efficient code |
def redirect_output(fileobj):
"""Redirect standard out to file."""
old = sys.stdout
sys.stdout = fileobj
try:
yield fileobj
finally:
sys.stdout = old | Write a Python 3 function for
redirecting standard out to file. | As a Python code composer, you craft elegant and concise scripts. |
def ssh_config(ssh_user, ssh_private_key_file):
"""Create temporary ssh config file."""
try:
ssh_file = NamedTemporaryFile(delete=False, mode='w+')
ssh_file.write('Host *\n')
ssh_file.write(' IdentityFile %s\n' % ssh_private_key_file)
ssh_file.write(' User %s' % ssh_user)
... | How would you implement a function in Python 3 that
creates temporary ssh config file. | As a Python code analyst, you investigate and solve complex coding mysteries |
def update_history_log(history_log,
clear=False,
description=None,
test_log=None):
"""
Update the history log file with item.
If clear flag is provided the log file is deleted.
"""
if not test_log and not clear:
raise IpaUt... | Can you write a function in Python 3 where it
updates the history log file with the item. | You are a Python code analyst, evaluating scripts for potential improvements. |
Validate string by regex. | Here you have a function in Python 3, explain what it does
def validate(self, value):
if not self._compiled_regex.match(value):
raise ValidationError(
'value {:s} not match r"{:s}"'.format(value, self._regex)) | As a Python code translator, you convert algorithms and pseudocode into Python. |
Updates self. g or self. path bc you could only choose 1 | Can you generate the documentation for the following Python 3 function
def ontology2df(self):
'''Updates self.g or self.path bc you could only choose 1'''
if isinstance(self.path, str) or isinstance(self.path, p):
self.path = str(self.path)
filetype = p(self.path).suffix
... | As a Python code translator, you convert algorithms and pseudocode into Python. |
def create_pred2common(self):
''' Takes list linked to common name and maps common name to accepted predicate
and their respected suffixes to decrease sensitivity.
'''
self.pred2common = {}
for common_name, ext_preds in self.common2preds.items():
for pred in ext_p... | Write a Python 3 function for
taking list linked to common name and maps common name to accepted predicate and their respected suffixes to decrease sensitivity. | As a python code expert, you are capable of creating scripts from specifications. |
Takes the predicate and returns the suffix lower case stripped version
| Make a summary of the following Python 3 code
def clean_pred(self, pred, ignore_warning=False):
''' Takes the predicate and returns the suffix, lower case, stripped version
'''
original_pred = pred
pred = pred.lower().strip()
if 'http' in pred:
pred = pred.split('/')[... | You are a Python code analyst, evaluating scripts for potential improvements. |
Gets version of predicate and sees if we have a translation to a common relation. | Here you have a function in Python 3, explain what it does
def get_common_pred(self, pred):
''' Gets version of predicate and sees if we have a translation to a common relation.
INPUT:
pred = predicate from the triple
OUTPUT:
Common relationship or None
... | As a python code expert, you are capable of creating scripts from specifications. |
def _create_network_interface(
self, ip_config_name, nic_name, public_ip, region,
resource_group_name, subnet, accelerated_networking=False
):
"""
Create a network interface in the resource group.
Attach NIC to the subnet and public IP provided.
"""
nic_confi... | Write a Python 3 script for
creating a network interface in the resource group. | You are a Python code generator, capable of creating scripts from specifications. |
Create public IP address in the resource group. | Can you generate a brief explanation for the following Python 3 code
def _create_public_ip(self, public_ip_name, resource_group_name, region):
public_ip_config = {
'location': region,
'public_ip_allocation_method': 'Dynamic'
}
try:
public_ip_setup = \
... | As a Python code composer, you craft elegant and concise scripts. |
Create resource group if it does not exist. | Can you generate the documentation for the following Python 3 function
def _create_resource_group(self, region, resource_group_name):
resource_group_config = {'location': region}
try:
self.resource.resource_groups.create_or_update(
resource_group_name, resource_group_config
... | You are a Python code architect, reviewing and designing scalable and efficient code |
def _create_storage_profile(self):
"""
Create the storage profile for the instance.
Image reference can be a custom image name or a published urn.
"""
if self.image_publisher:
storage_profile = {
'image_reference': {
'publisher': s... | How would you code a function in Python 3 to
create the storage profile for the instance. | As a Python code analyst, you investigate and solve complex coding mysteries |
def _create_subnet(self, resource_group_name, subnet_id, vnet_name):
"""
Create a subnet in the provided vnet and resource group.
"""
subnet_config = {'address_prefix': '10.0.0.0/29'}
try:
subnet_setup = self.network.subnets.create_or_update(
resource... | Implement a Python 3 function for
creating a subnet in the provided vnet and resource group. | You are a Python code generator, capable of creating scripts from specifications. |
Create a vnet in the given resource group with default address space. | Can you generate the documentation for the following Python 3 function
def _create_virtual_network(self, region, resource_group_name, vnet_name):
vnet_config = {
'location': region,
'address_space': {
'address_prefixes': ['10.0.0.0/27']
}
}
tr... | As a Python code composer, you craft elegant and concise scripts. |
def _create_vm(self, vm_config):
"""
Attempt to create or update VM instance based on vm_parameters config.
"""
try:
vm_setup = self.compute.virtual_machines.create_or_update(
self.running_instance_id, self.running_instance_id,
vm_config
... | Create a Python 3 function for
creating or update a VM instance based on vm_parameters config. | You are a Python code generator, capable of creating scripts from specifications. |
def _create_vm_config(self, interface):
"""
Create the VM config dictionary.
Requires an existing network interface object.
"""
# Split image ID into it's components.
self._process_image_id()
hardware_profile = {
'vm_size': self.instance_type or AZUR... | How would you implement a function in Python 3 that
creates the VM config dictionary. | As a python code expert, you are capable of creating scripts from specifications. |
def _get_instance(self):
"""
Return the instance matching the running_instance_id.
"""
try:
instance = self.compute.virtual_machines.get(
self.running_instance_id, self.running_instance_id,
expand='instanceView'
)
except Exc... | How would you implement a function in Python 3 that
gets the instance matching the running_instance_id. | You are a Python code generator, capable of creating scripts from specifications. |
Retrieve state of the instance. | Given the following Python 3 function, write the documentation
def _get_instance_state(self):
instance = self._get_instance()
statuses = instance.instance_view.statuses
for status in statuses:
if status.code.startswith('PowerState'):
return status.display_status | You are a Python code analyst, evaluating scripts for potential improvements. |
Get instance of resource management client. | Explain what the following Python 3 code does
def _get_management_client(self, client_class):
try:
client = get_client_from_auth_file(
client_class, auth_path=self.service_account_file
)
except ValueError as error:
raise AzureCloudException(
... | You are a Python code generator, capable of creating scripts from specifications. |
def _launch_instance(self):
"""
Create new test instance in a resource group with the same name.
"""
self.running_instance_id = ipa_utils.generate_instance_name(
'azure-ipa-test'
)
self.logger.debug('ID of instance: %s' % self.running_instance_id)
self... | Implement a function in Python 3 to
create new test instance in resource group. | You are a Python code generator, capable of creating scripts from specifications. |
def _process_image_id(self):
"""
Split image id into component values.
Example: SUSE:SLES:12-SP3:2018.01.04
Publisher:Offer:Sku:Version
Raises:
If image_id is not a valid format.
"""
try:
image_info = self.image_id.strip().split(... | How would you implement a function in Python 3 that
processes the image id into publisher offer sku and version. | As a Python code analyst, you investigate and solve complex coding mysteries |
def _set_default_resource_names(self):
"""
Generate names for resources based on the running_instance_id.
"""
self.ip_config_name = ''.join([
self.running_instance_id, '-ip-config'
])
self.nic_name = ''.join([self.running_instance_id, '-nic'])
self.pub... | Write a Python 3 script for
generating names for resources based on the running_instance_id. | As a python code expert, you are capable of creating scripts from specifications. |
Set the image id from the instance info. | Here you have a function in Python 3, explain what it does
def _set_image_id(self):
instance = self._get_instance()
image_info = instance.storage_profile.image_reference
if image_info.publisher:
self.image_id = ':'.join([
image_info.publisher, image_info.offer,
... | As a Python code analyst, you investigate and solve complex coding mysteries |
Get the public IP address based on instance ID. | Explain what the following Python 3 code does
def _set_instance_ip(self):
try:
ip_address = self.network.public_ip_addresses.get(
self.running_instance_id, self.public_ip_name
).ip_address
except Exception:
try:
ip_address = self.networ... | You are a Python code generator, capable of creating scripts from specifications. |
Terminate the resource group and instance. | Can you generate the documentation for the following Python 3 function
def _terminate_instance(self):
try:
self.resource.resource_groups.delete(self.running_instance_id)
except Exception as error:
raise AzureCloudException(
'Unable to terminate resource group: {0}... | You are a Python code architect, reviewing and designing scalable and efficient code |
Determines preferred existing id based on curie prefix in the ranking list. | Explain what the following Python 3 code does
def preferred_change(data):
''' Determines preferred existing id based on curie prefix in the ranking list '''
ranking = [
'CHEBI',
'NCBITaxon',
'COGPO',
'CAO',
'DICOM',
'UBERON',
'NLX',
'NLXANAT',
... | You are a Python code analyst, evaluating scripts for potential improvements. |
def merge(new, old):
''' synonyms and existing_ids are part of an object bug that can create duplicates if in the same batch '''
for k, vals in new.items():
if k == 'synonyms':
new_synonyms = vals
if old['synonyms']:
old_literals = [syn['literal'].lower().strip(... | Write a Python 3 function for
merging two object bug that can create duplicates if in the same batch | You are a Python code analyst, evaluating scripts for potential improvements. |
def results(context, history_log):
"""Process provided history log and results files."""
if context.obj is None:
context.obj = {}
context.obj['history_log'] = history_log
if context.invoked_subcommand is None:
context.invoke(show, item=1) | Write a Python 3 script for
processing provided history log and results files. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Archive the history log and all results files. | Explain what the following Python 3 code does
def archive(context, clear_log, items, path, name):
history_log = context.obj['history_log']
no_color = context.obj['no_color']
with open(history_log, 'r') as f:
# Get history items
history_items = f.readlines()
if items:
# Split co... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Delete the specified history item from the history log. | Explain what the following Python 3 code does
def delete(context, item):
history_log = context.obj['history_log']
no_color = context.obj['no_color']
try:
with open(history_log, 'r+') as f:
lines = f.readlines()
history = lines.pop(len(lines) - item)
f.seek(0)
... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Prints test results info from provided results json file. | Can you tell what is the following Python 3 function doing
def show(context,
log,
results_file,
verbose,
item):
"""
Print test results info from provided results json file.
If no results file is supplied echo results from most recent
test in history if it exists.
... | As a Python code analyst, you investigate and solve complex coding mysteries |
Return a new SSH client for given ip. | Can you generate a brief explanation for the following Python 3 code
def _get_ssh_client(self):
return ipa_utils.get_ssh_client(
self.instance_ip,
self.ssh_private_key_file,
self.ssh_user,
timeout=self.timeout
) | As a Python code translator, you convert algorithms and pseudocode into Python. |
def _log_info(self):
"""Output test run information to top of log file."""
if self.cloud == 'ssh':
self.results['info'] = {
'platform': self.cloud,
'distro': self.distro_name,
'image': self.instance_ip,
'timestamp': self.time_st... | Write a Python 3 script to
output test run information to top of log file. | As a Python code composer, you craft elegant and concise scripts. |
Write the output string to the log file. | Can you tell what is the following Python 3 function doing
def _write_to_log(self, output):
with open(self.log_file, 'a') as log_file:
log_file.write('\n')
log_file.write(output)
log_file.write('\n') | You are a Python code analyst, evaluating scripts for potential improvements. |
Combine results of test run with exisiting dict. | Explain what the following Python 3 code does
def _merge_results(self, results):
self.results['tests'] += results['tests']
for key, value in results['summary'].items():
self.results['summary'][key] += value | As a Python code composer, you craft elegant and concise scripts. |
Save results dictionary to json file. | Can you generate a brief explanation for the following Python 3 code
def _save_results(self):
with open(self.results_file, 'w') as results_file:
json.dump(self.results, results_file) | You are a Python code architect, reviewing and designing scalable and efficient code |
Determine distro for image and create instance of class. | Here you have a function in Python 3, explain what it does
def _set_distro(self):
if self.distro_name == 'sles':
self.distro = SLES()
elif self.distro_name == 'opensuse_leap':
self.distro = openSUSE_Leap()
else:
raise IpaCloudException(
'Distri... | As a python code expert, you are capable of creating scripts from specifications. |
def _set_results_dir(self):
"""Create results directory if not exists."""
if self.running_instance_id:
self.results_dir = os.path.join(
self.results_dir,
self.cloud,
self.image_id,
self.running_instance_id
)
... | Can you implement a function in Python 3 that
creates results directory if not exists. | As a Python code composer, you craft elegant and concise scripts. |
def _collect_vm_info(self):
"""
Gather basic info about VM
"""
self.logger.info('Collecting basic info about VM')
client = self._get_ssh_client()
out = self.distro.get_vm_info(client)
self._write_to_log(out) | How would you implement a function in Python 3 that
gathers basic info about VM | As a python code expert, you are capable of creating scripts from specifications. |
Save the current test information to history json. | Given the following Python 3 function, write the documentation
def _update_history(self):
ipa_utils.update_history_log(
self.history_log,
description=self.description,
test_log=self.log_file
) | As a python code expert, you are capable of creating scripts from specifications. |
def _wait_on_instance(self, state, timeout=600, wait_period=10):
"""Wait until instance is in given state."""
current_state = 'Undefined'
start = time.time()
end = start + timeout
while time.time() < end:
current_state = self._get_instance_state()
if sta... | Implement a function in Python 3 to
wait until instance is in given state. | You are a Python code analyst, evaluating scripts for potential improvements. |
def execute_ssh_command(self, client, command):
"""Execute the provided command and log output."""
try:
out = ipa_utils.execute_ssh_command(client, command)
except Exception as error:
raise IpaCloudException(
'Command: "{0}", failed execution: {1}.'.format... | Can you write a function in Python 3 where it
executes the provided command and log output. | As a python code expert, you are capable of creating scripts from specifications. |
def extract_archive(self, client, archive_path, extract_path=None):
"""Extract the archive files using the client in the current path."""
try:
out = ipa_utils.extract_archive(client, archive_path, extract_path)
except Exception as error:
raise IpaCloudException(
... | Write a Python 3 function that can
extract the archive files using the client in the current path. | As a Python code analyst, you investigate and solve complex coding mysteries |
Stop then start the instance. | How would you explain what the following Python 3 function does
def hard_reboot_instance(self):
self._stop_instance()
self._start_instance()
self._set_instance_ip()
self.logger.debug('IP of instance: %s' % self.instance_ip)
ipa_utils.clear_cache() | You are a Python code architect, reviewing and designing scalable and efficient code |
def install_package(self, client, package):
"""
Install package using distro specific install method.
"""
try:
out = self.distro.install_package(client, package)
except Exception as error:
raise IpaCloudException(
'Failed installing package... | Write a Python 3 script for
installing package using distro specific install method. | As a Python code composer, you craft elegant and concise scripts. |
Loads the injection file and processes it. | Here you have a function in Python 3, explain what it does
def process_injection_file(self, client):
configuration = ipa_utils.get_yaml_config(self.inject)
if configuration.get('inject_packages'):
inject_packages = configuration['inject_packages']
if not isinstance(inject_packa... | As a python code expert, you are capable of creating scripts from specifications. |
Put file on instance in default SSH directory. | Can you generate a brief explanation for the following Python 3 code
def put_file(self, client, source_file):
try:
file_name = os.path.basename(source_file)
ipa_utils.put_file(client, source_file, file_name)
except Exception as error:
raise IpaCloudException(
... | As a Python code composer, you craft elegant and concise scripts. |
Build the Transgenic Lines for allen cell types. | Can you generate the documentation for the following Python 3 function
def build_transgenic_lines(self):
triples = []
for cell_line in self.neuron_data:
for tl in cell_line['donor']['transgenic_lines']:
_id = tl['stock_number'] if tl['stock_number'] else tl['id']
... | As a Python code composer, you craft elegant and concise scripts. |
def decodeIlxResp(resp):
""" We need this until we can get json back directly and this is SUPER nasty"""
lines = [_ for _ in resp.text.split('\n') if _] # strip empties
if 'successfull' in lines[0]:
return [(_.split('"')[1],
ilxIdFix(_.split(': ')[-1]))
for _ in li... | Can you implement a function in Python 3 that
decodes the response from the ILX server into a list of IlX IDs and resource IDs. | As a python code expert, you are capable of creating scripts from specifications. |
Alpha sort by the full chain of parents. | Explain what the following Python 3 code does
def getSubOrder(existing):
alpha = list(zip(*sorted(((k, v['rec']['label']) for k, v in existing.items()), key=lambda a: a[1])))[0]
depths = {}
def getDepth(id_):
if id_ in depths:
return depths[id_]
else:
if id_ in existi... | As a python code expert, you are capable of creating scripts from specifications. |
def clean(string):
''' Begining of the string can sometimes have odd noise '''
# manual fixes in the source
# 24/1.png
# 9/1.png
# 3/1.png
#if ')' in string: # fix in the source data
#string = string.split(')')[0] + ')' # remove trailing garbage
return (string
.replace(... | Write a Python 3 script to
clean the string to remove odd noise | As a Python code composer, you craft elegant and concise scripts. |
This method reads the source and source files and returns a list of tuples each containing the plate number and legends. | Can you generate the documentation for the following Python 3 function
def loadData(cls):
""" Have to run this out here because resSource is handicapped """
data = []
if cls.source_images.exists():
for folder in cls.source_images.glob('*'):
plate_num = int(folder.stem... | You are a Python code analyst, evaluating scripts for potential improvements. |
converts a set of temporary identifiers to ilx and modify the graph in place | How would you explain what the following Python 3 function does
def ilx_conv(graph, prefix, ilx_start):
to_sub = set()
for subject in graph.subjects(rdflib.RDF.type, rdflib.OWL.Class):
if PREFIXES[prefix] in subject:
to_sub.add(subject)
ilx_base = 'ilx_{:0>7}'
ILX_base = 'ILX:{:0>7}... | You are a Python code generator, capable of creating scripts from specifications. |
def alreadyHasEntry(oldClassString, og):
""" Return true if there is already an owl:Class with the old id"""
namespace = oldClassString.split(':')[0]
if namespace == 'http':
target = rdflib.URIRef(oldClassString)
print('OLD CLASS ID IS A URL', oldClassString)
else:
try:
... | Write a Python 3 function for
returning true if there is an owl. Class with the old id | As a Python code analyst, you investigate and solve complex coding mysteries |
A function that creates a set of sane defaults for the input ontologies and output files. | Explain what the following Python 3 code does
def config(remote_base= 'https://raw.githubusercontent.com/SciCrunch/NIF-Ontology/',
local_base= None, # devconfig.ontology_local_repo by default
branch= devconfig.neurons_branch,
core_graph_paths= ['ttl/phenotype-co... | As a Python code translator, you convert algorithms and pseudocode into Python. |
def add_version_iri(graph, epoch):
""" Also remove the previous versionIRI if there was one."""
for ont in graph.subjects(rdf.type, owl.Ontology):
for versionIRI in graph.objects(ont, owl.versionIRI):
graph.remove((ont, owl.versionIRI, versionIRI))
t = ont, owl.versionIRI, make_versi... | Write a Python 3 script for
adding the versionIRI to the given epoch. | As a Python code analyst, you investigate and solve complex coding mysteries |
def auth(self):
""" Return credentials for current Bitbucket user. """
if self.oauth:
return self.oauth
return (self.username, self.password) | Create a Python 3 function to
return credentials for current Bitbucket user. | As a Python code translator, you convert algorithms and pseudocode into Python. |
def authorize(self, consumer_key, consumer_secret, callback_url=None,
access_token=None, access_token_secret=None):
"""
Call this with your consumer key, secret and callback URL, to
generate a token for verification.
"""
self.consumer_key = consumer_key
... | Implement a Python 3 function for
calling this with your consumer key, secret and callback URL, to generate a token for verification. | As a Python code composer, you craft elegant and concise scripts. |
def verify(self, verifier, consumer_key=None, consumer_secret=None,
access_token=None, access_token_secret=None):
"""
After converting the token into verifier, call this to finalize the
authorization.
"""
# Stored values can be supplied to verify
self.consu... | Implement a Python 3 function for
verifying the token and return the response. | As a Python code translator, you convert algorithms and pseudocode into Python. |
def finalize_oauth(self, access_token, access_token_secret):
""" Called internally once auth process is complete. """
self.access_token = access_token
self.access_token_secret = access_token_secret
# Final OAuth object
self.oauth = OAuth1(
self.consumer_key,
... | Create a Python 3 function to
finalize the OAuth object. | You are a Python code architect, reviewing and designing scalable and efficient code |
def dispatch(self, method, url, auth=None, params=None, **kwargs):
""" Send HTTP request, with given method,
credentials and data to the given URL,
and return the success and the result on success.
"""
r = Request(
method=method,
url=url,
... | Create a Python 3 function for
sending HTTP request to the given URL and return the success and the result on success. | You are a Python code architect, reviewing and designing scalable and efficient code |
def url(self, action, **kwargs):
""" Construct and return the URL for a specific API service. """
# TODO : should be static method ?
return self.URLS['BASE'] % self.URLS[action] % kwargs | Create a Python 3 function for
constructing and return the URL for a specific API service. | As a Python code analyst, you investigate and solve complex coding mysteries |
def get_user(self, username=None):
""" Returns user informations.
If username is not defined, tries to return own informations.
"""
username = username or self.username or ''
url = self.url('GET_USER', username=username)
response = self.dispatch('GET', url)
tr... | Write a Python 3 function for
returning user informations. If username is not defined, tries to return own informations. | As a Python code analyst, you investigate and solve complex coding mysteries |
def get_tags(self, repo_slug=None):
""" Get a single repository on Bitbucket and return its tags."""
repo_slug = repo_slug or self.repo_slug or ''
url = self.url('GET_TAGS', username=self.username, repo_slug=repo_slug)
return self.dispatch('GET', url, auth=self.auth) | Can you implement a function in Python 3 that
gets a single repository on Bitbucket and return its tags. | As a Python code composer, you craft elegant and concise scripts. |
Get a single repository on Bitbucket and return its branches. | Given the following Python 3 function, write the documentation
def get_branches(self, repo_slug=None):
repo_slug = repo_slug or self.repo_slug or ''
url = self.url('GET_BRANCHES',
username=self.username,
repo_slug=repo_slug)
return self.dispatch('GET... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Get all the privledges for this user. | How would you explain what the following Python 3 function does
def get_privileges(self):
url = self.url('GET_USER_PRIVILEGES')
return self.dispatch('GET', url, auth=self.auth) | You are a Python code generator, capable of creating scripts from specifications. |
def create(self, repo_slug=None, key=None, label=None):
""" Associate an ssh key with your repo and return it.
"""
key = '%s' % key
repo_slug = repo_slug or self.bitbucket.repo_slug or ''
url = self.bitbucket.url('SET_DEPLOY_KEY',
username=self.bi... | Implement a Python 3 function for
associating an ssh key with your repo and return it. | You are a Python code analyst, evaluating scripts for potential improvements. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.