output
stringlengths
1
928k
instruction
stringlengths
7
928k
system
stringlengths
0
104k
def from_extension(extension): """ Look up the BioPython file type corresponding with input extension. Look up is case insensitive. """ if not extension.startswith('.'): raise ValueError("Extensions must begin with a period.") try: return EXTENSION_TO_TYPE[extension.lower()] ...
Write a Python 3 script to return the BioPython file type corresponding with the input extension.
As a python code expert, you are capable of creating scripts from specifications.
Returns a BioPython object corresponding to the file name.
Can you tell what is the following Python 3 function doing def from_filename(file_name): base, extension = os.path.splitext(file_name) if extension in COMPRESS_EXT: # Compressed file extension = os.path.splitext(base)[1] return from_extension(extension)
As a Python code analyst, you investigate and solve complex coding mysteries
Return a BioPython object from a file - like object.
Given the following Python 3 function, write the documentation def from_handle(fh, stream_default='fasta'): if fh in (sys.stdin, sys.stdout, sys.stderr): return stream_default return from_filename(fh.name)
As a Python code analyst, you investigate and solve complex coding mysteries
def parse_arguments(argv): """ Extract command-line arguments for different actions. """ parser = argparse.ArgumentParser(description='seqmagick - Manipulate ' + \ ' sequence files.', prog='seqmagick') parser.add_argument('-V', '--version', action='version', version='seqmagick v'...
How would you implement a function in Python 3 that parses command - line arguments for different actions.
You are a Python code analyst, evaluating scripts for potential improvements.
def ungap_index_map(sequence, gap_chars='-'): """ Returns a dict mapping from an index in the ungapped sequence to an index in the gapped sequence. >>> ungap_index_map('AC-TG-') {0: 0, 1: 1, 2: 3, 3: 4} """ counter = itertools.count(0).__next__ ungap_indexes = [ counter() if c n...
Write a Python 3 script for returning a dict mapping from an index in the ungapped sequence to an index in the gapped sequence.
As a Python code composer, you craft elegant and concise scripts.
def gap_index_map(sequence, gap_chars='-'): """ Opposite of ungap_index_map: returns mapping from gapped index to ungapped index. >>> gap_index_map('AC-TG-') {0: 0, 1: 1, 3: 2, 4: 3} """ return dict( (v, k) for k, v in list(ungap_index_map(sequence, gap_chars).items()))
Implement a Python 3 function for returning mapping from gapped index to ungapped index.
As a Python code composer, you craft elegant and concise scripts.
def _iupac_ambiguous_equal(ambig_base, unambig_base): """ Tests two bases for equality, accounting for IUPAC ambiguous DNA ambiguous base may be IUPAC ambiguous, unambiguous must be one of ACGT """ iupac_translation = { 'A': 'A', 'C': 'C', 'G': 'G', 'T': 'T', ...
Create a Python 3 function to test if two bases are equal.
You are a Python code generator, capable of creating scripts from specifications.
Returns the hamming distance between two strings.
Given the following Python 3 function, write the documentation def hamming_distance(s1, s2, equality_function=operator.eq): if not len(s1) == len(s2): raise ValueError("String lengths are not equal") # Number of non-matching characters: return sum(not equality_function(c1, c2) for c1, c2 in zip(s1,...
As a Python code analyst, you investigate and solve complex coding mysteries
def locate_primers(sequences, forward_primer, reverse_primer, reverse_complement, max_hamming_distance): """ Find forward and reverse primers in a set of sequences, return two tuples: (forward_start, forward_end), (reverse_start, reverse_end) """ forward_loc = None reverse_loc...
How would you implement a function in Python 3 that finds the forward and reverse primers in a set of sequences.
You are a Python code analyst, evaluating scripts for potential improvements.
def trim(sequences, start, end): """ Slice the input sequences from start to end """ logging.info("Trimming from %d to %d", start, end) return (sequence[start:end] for sequence in sequences)
Write a Python 3 function for slicing the input sequences from start to end
As a Python code analyst, you investigate and solve complex coding mysteries
This function performs the alignment processing.
Can you generate a brief explanation for the following Python 3 code def action(arguments): # Determine file format for input and output source_format = (arguments.source_format or fileformat.from_handle(arguments.source_file)) output_format = (arguments.output_format or ...
As a Python code analyst, you investigate and solve complex coding mysteries
def align(self, sequence): """ Aligns the primer to the given query sequence, returning a tuple of: hamming_distance, start, end Where hamming distance is the distance between the primer and aligned sequence, and start and end give the start and end index of the primer ...
Can you implement a function in Python 3 that aligns the primer to the input sequence returning a tuple of hamming distance start and end index.
You are a Python code generator, capable of creating scripts from specifications.
A simple function that only accepts records with a numeric start to CTYPE their sha - 1 hash.
Given the following Python 3 function, write the documentation def hash_starts_numeric(records): for record in records: seq_hash = hashlib.sha1(str(record.seq)).hexdigest() if seq_hash[0].isdigit(): yield record
As a python code expert, you are capable of creating scripts from specifications.
def atomic_write(path, mode='wt', permissions=None, file_factory=None, **kwargs): """ Open a file for atomic writing. Generates a temp file, renames to value of ``path``. Arguments: ``permissions``: Permissions to set (default: umask) ``file_factory``: If given, the handle yielded will be the ...
Write a Python 3 script to open a file for atomic writing. Generates a temp file, renames to value of ``path``. Arguments: ``permissions``: Permissions to set (default: umask) ``file_factory``: If given, the handle yielded will be the result of calling file_factory(path) Additional arguments are passed to tempfile.Name...
As a python code expert, you are capable of creating scripts from specifications.
A custom argparse type to deal with sequences ranges such as 5 : 500.
Can you generate a brief explanation for the following Python 3 code def cut_range(string): value_range = string.split(':') if len(value_range) == 1: start = int(value_range[0]) stop = start elif len(value_range) == 2: start, stop = tuple(int(i) if i else None for i in value_range) ...
As a python code expert, you are capable of creating scripts from specifications.
Require variables to be of the specified type, between minimum and maximum
How would you explain what the following Python 3 function does def typed_range(type_func, minimum, maximum): @functools.wraps(type_func) def inner(string): result = type_func(string) if not result >= minimum and result <= maximum: raise argparse.ArgumentTypeError( ...
You are a Python code analyst, evaluating scripts for potential improvements.
Returns an argparse. Action which appends a partially - applied function to dest.
Here you have a function in Python 3, explain what it does def partial_append_action(fn, argument_keys=None): if isinstance(argument_keys, str): argument_keys = [argument_keys] argument_keys = argument_keys or [] class PartialAppendAction(argparse.Action): def __init__(self, ...
As a Python code composer, you craft elegant and concise scripts.
Returns a function that checks that the argument is a positive number.
Given the following Python 3 function, write the documentation def positive_value(target_type): def inner(string): value = target_type(string) if not value >= 0: raise argparse.ArgumentTypeError("Invalid positive number: " + string) return value return in...
As a Python code composer, you craft elegant and concise scripts.
def add_options(parser): """ Add optional arguments to the parser """ partial_action = common.partial_append_action file_mods = parser.add_argument_group("Sequence File Modification") file_mods.add_argument('--line-wrap', dest='line_wrap', metavar='N', type=int, help='Adjust line wrap fo...
Create a Python 3 function for adding the options to the parser that will be used to filter the input sequences.
As a Python code translator, you convert algorithms and pseudocode into Python.
Build the parser for the command line.
Can you tell what is the following Python 3 function doing def build_parser(parser): add_options(parser) parser.add_argument('source_file', type=common.FileType('rt'), help="Input sequence file") parser.add_argument('dest_file', help="Output file") return parser
You are a Python code analyst, evaluating scripts for potential improvements.
Load a function from a python module using a file name function name
How would you explain what the following Python 3 function does def module_function(string): parts = string.split(':', 2) if len(parts) < 2: raise ValueError( "Illegal specification. Should be module:function[:parameter]") module_path, function_name = parts[:2] # Import the module ...
You are a Python code architect, reviewing and designing scalable and efficient code
Parse cgMLST alleles from cgMLST FASTA file.
Make a summary of the following Python 3 code def parse_cgmlst_alleles(cgmlst_fasta): out = defaultdict(list) for header, seq in parse_fasta(cgmlst_fasta): if not '|' in header: raise Exception('Unexpected format for cgMLST fasta file header. No "|" (pipe) delimiter present! Header="{}"'.for...
As a Python code composer, you craft elegant and concise scripts.
def parse_fasta(filepath): ''' Parse a fasta file returning a generator yielding tuples of fasta headers to sequences. Note: This function should give equivalent results to SeqIO from BioPython .. code-block:: python from Bio import SeqIO # biopython to dict of hea...
Can you implement a function in Python 3 that parses a fasta file returning a generator yielding tuples of header to sequences
You are a Python code architect, reviewing and designing scalable and efficient code
def fasta_format_check(fasta_path, logger): """ Check that a file is valid FASTA format. - First non-blank line needs to begin with a '>' header character. - Sequence can only contain valid IUPAC nucleotide characters Args: fasta_str (str): FASTA file contents string Raises: ...
Implement a function in Python 3 to check that a file is valid FASTA format.
As a Python code translator, you convert algorithms and pseudocode into Python.
def seq_int_arr(seqs): """Convert list of ACGT strings to matix of 1-4 ints Args: seqs (list of str): nucleotide sequences with only 'ACGT' characters Returns: numpy.array of int: matrix of integers from 1 to 4 inclusive representing A, C, G, and T str: nucleotide sequence string ...
Create a Python 3 function to convert list of ACGT strings to matix of 1 - 4 ints
As a Python code analyst, you investigate and solve complex coding mysteries
def group_alleles_by_start_end_Xbp(arr, bp=28): """Group alleles by matching ends Args: arr (numpy.array): 2D int matrix of alleles bp (int): length of ends to group by Returns: dict of lists: key of start + end strings to list of indices of alleles with matching ends """ s...
Can you create a Python 3 function that groups alleles by start and end indices
As a Python code translator, you convert algorithms and pseudocode into Python.
def min_row_dist_sum_idx(dists): """Find the index of the row with the minimum row distance sum This should return the index of the row index with the least distance overall to all other rows. Args: dists (np.array): must be square distance matrix Returns: int: index of row wit...
How would you implement a function in Python 3 that finds the index of the row with the minimum row distance sum This should return the index of the row with the least distance sum to all other rows.
As a Python code composer, you craft elegant and concise scripts.
def find_centroid_alleles(alleles, bp=28, t=0.025): """Reduce list of alleles to set of centroid alleles based on size grouping, ends matching and hierarchical clustering Workflow for finding centroid alleles: - grouping by size (e.g. 100bp, 101bp, 103bp, etc) - then grouped by `bp` nucleotides at end...
Can you implement a function in Python 3 that reduces list of alleles to set of centroid alleles based on size grouping ends matching and hierarchical clustering
You are a Python code analyst, evaluating scripts for potential improvements.
def mash_dist_trusted(fasta_path): """ Compute Mash distances of sketch file of genome fasta to RefSeq sketch DB. Args: mash_bin (str): Mash binary path Returns: (str): Mash STDOUT string """ args = [MASH_BIN, 'dist', MASH_SKETCH_FILE, fasta_...
Create a Python 3 function for computing Mash distances of sketch file of genome fasta to RefSeq sketch DB.
As a Python code translator, you convert algorithms and pseudocode into Python.
def nr_profiles(arr, genomes): """ Get a condensed cgMLST pairwise distance matrix for specified Genomes_ where condensed means redundant cgMLST profiles are only represented once in the distance matrix. Args: user_name (list): List of Genome_ names to retrieve condensed distance matrix for ...
How would you implement a function in Python 3 that returns a condensed cgMLST pairwise distance matrix for the specified genomes.
As a Python code analyst, you investigate and solve complex coding mysteries
This function is used to get the overall serovar from cgMLST cluster membership analysis and antigen BLAST results.
How would you explain what the following Python 3 function does def overall_serovar_call(serovar_prediction, antigen_predictor): assert isinstance(serovar_prediction, SerovarPrediction) assert isinstance(antigen_predictor, SerovarPredictor) h1 = antigen_predictor.h1 h2 = antigen_predictor.h2 sg = a...
You are a Python code architect, reviewing and designing scalable and efficient code
Append informative fields to cgMLST330 BLAST results DataFrame
Given the following Python 3 function, write the documentation def process_cgmlst_results(df): assert isinstance(df, pd.DataFrame) markers = [] alleles = [] for x in df['qseqid']: marker, allele = x.split('|') markers.append(marker) alleles.append(int(allele)) df.loc[:, 'mar...
As a Python code composer, you craft elegant and concise scripts.
Alleles to retrieve from genome fasta
Can you generate the documentation for the following Python 3 function def alleles_to_retrieve(df): contig_blastn_records = defaultdict(list) markers = df.marker.unique() for m in markers: dfsub = df[df.marker == m] for i, r in dfsub.iterrows(): if r.coverage < 1.0: ...
As a Python code composer, you craft elegant and concise scripts.
def matches_to_marker_results(df): """Perfect BLAST matches to marker results dict Parse perfect BLAST matches to marker results dict. Args: df (pandas.DataFrame): DataFrame of perfect BLAST matches Returns: dict: cgMLST330 marker names to matching allele numbers """ assert i...
Create a Python 3 function to parse perfect BLAST matches to marker results dict.
As a Python code composer, you craft elegant and concise scripts.
This method attempts to find the majority subspecies type within a curated group by cgMLST and returns the most common subspecies type within the cgMLST group.
Explain what the following Python 3 code does def cgmlst_subspecies_call(df_relatives): closest_distance = df_relatives['distance'].min() if closest_distance > CGMLST_SUBSPECIATION_DISTANCE_THRESHOLD: logging.warning('Min cgMLST distance (%s) above subspeciation distance threshold (%s)', c...
You are a Python code analyst, evaluating scripts for potential improvements.
Perform in silico cgMLST on an input genome Returns a dictionary containing the result of the BLAST on success Return None if no results were found
Make a summary of the following Python 3 code def run_cgmlst(blast_runner, full=False): from sistr.src.serovar_prediction.constants import genomes_to_serovar df_cgmlst_profiles = ref_cgmlst_profiles() logging.debug('{} distinct cgMLST330 profiles'.format(df_cgmlst_profiles.shape[0])) logging.info('Ru...
As a Python code analyst, you investigate and solve complex coding mysteries
Extract genome name from fasta file path
Given the following Python 3 function, write the documentation def genome_name_from_fasta_path(fasta_path): filename = os.path.basename(fasta_path) return re.sub(r'(\.fa$)|(\.fas$)|(\.fasta$)|(\.fna$)|(\.\w{1,}$)', '', filename)
You are a Python code generator, capable of creating scripts from specifications.
This function returns the extended start and end indices of the extended sequence that is used to extract the subject sequence from the blastn results dataframe.
Explain what the following Python 3 code does def extend_subj_match_vec(df): needs_revcomp = df.sstart > df.send add_to_end = df.qlen - df.qend add_to_start = df.qstart - 1 ssum2 = (df.send + df.sstart) / 2.0 sabs2 = np.abs(df.send - df.sstart) / 2.0 end_idx = ssum2 + sabs2 - 1 start_idx = s...
As a Python code analyst, you investigate and solve complex coding mysteries
Get all instance and class attributes of an object.
Can you tell what is the following Python 3 function doing def listattrs(x): return [attr for attr in dir(x) if not attr.startswith("__") and not callable(getattr(x, attr))]
As a Python code analyst, you investigate and solve complex coding mysteries
def to_dict(x, depth, exclude_keys=set(), depth_threshold=8): """Transform a nested object/dict/list into a regular dict json.dump(s) and pickle don't like to un/serialize regular Python objects so this function should handle arbitrarily nested objects to be serialized to regular string, float, int...
Can you create a Python 3 function that transforms a nested object into a regular dict and pickle don t like to serialize
As a Python code translator, you convert algorithms and pseudocode into Python.
def flatten_dict(x): """Flatten a dict Flatten an arbitrarily nested dict as output by to_dict .. note:: Keys in the flattened dict may get very long. Args: x (dict): Arbitrarily nested dict (maybe resembling a tree) with literal/scalar leaf values Retu...
Write a Python 3 script for flattening an arbitrarily nested dict as output by to_dict
As a python code expert, you are capable of creating scripts from specifications.
Returns a list of dict that looks like
Here you have a function in Python 3, explain what it does def df_first_row_to_dict(df): if df is not None: return [dict(r) for i, r in df.head(1).iterrows()][0]
As a Python code analyst, you investigate and solve complex coding mysteries
Check if a query sequence is truncated by the end of a subject sequence
Can you tell what is the following Python 3 function doing def is_blast_result_trunc(qstart, qend, sstart, send, qlen, slen): q_match_len = abs(qstart - qend) + 1 s_max = max(sstart, send) s_min = min(sstart, send) return (q_match_len < qlen) and (s_max >= slen or s_min <= 1)
You are a Python code analyst, evaluating scripts for potential improvements.
Check if a query sequence is truncated by the end of a subject sequence
Here you have a function in Python 3, explain what it does def trunc(qstart, qend, sstart, send, qlen, slen): ssum2 = (send + sstart) / 2.0 sabs2 = np.abs(send - sstart) / 2.0 smax = ssum2 + sabs2 smin = ssum2 - sabs2 q_match_len = np.abs(qstart - qend) + 1 return (q_matc...
You are a Python code architect, reviewing and designing scalable and efficient code
Return pandas DataFrame with perfect BLAST matches
Here you have a function in Python 3, explain what it does def perfect_matches(self): if self.is_missing: return None df_perfect_matches = self.df[(self.df['coverage'] == 1.0) & (self.df['pident'] == 100.0)] if df_perfect_matches.shape[0] == 0: return None return...
You are a Python code generator, capable of creating scripts from specifications.
Return the top result of the BLASTN analysis.
Can you generate the documentation for the following Python 3 function def top_result(self): if self.is_missing: return None df_perfect_matches = self.df[(self.df['coverage'] == 1.0) & (self.df['pident'] == 100.0)] if df_perfect_matches.shape[0]: self.is_perfect_match =...
As a Python code translator, you convert algorithms and pseudocode into Python.
def sketch_fasta(fasta_path, outdir): """Create a Mash sketch from an input fasta file Args: fasta_path (str): input fasta file path. Genome name in fasta filename outdir (str): output directory path to write Mash sketch file to Returns: str: output Mash sketch file path """ ...
Write a Python 3 script to create a Mash sketch from an input fasta file.
As a Python code analyst, you investigate and solve complex coding mysteries
def merge_sketches(outdir, sketch_paths): """Merge new Mash sketches with current Mash sketches Args: outdir (str): output directory to write merged Mash sketch file sketch_paths (list of str): Mash sketch file paths for input fasta files Returns: str: output path for Mash sketch f...
How would you implement a function in Python 3 that merges new Mash sketches with current Mash sketches
As a Python code translator, you convert algorithms and pseudocode into Python.
Implementation of :meth:`~simplekv.KeyValueStore.put`. Will store the value in the backing store. After a successful or unsuccessful store, the cache will be invalidated by deleting the key from it.
Can you generate the documentation for the following Python 3 function def put(self, key, data): try: return self._dstore.put(key, data) finally: self.cache.delete(key)
As a Python code translator, you convert algorithms and pseudocode into Python.
Implementation of :meth:`~simplekv.KeyValueStore.put_file`. Will store the value in the backing store. After a successful or unsuccessful store, the cache will be invalidated by deleting the key from it.
How would you explain what the following Python 3 function does def put_file(self, key, file): try: return self._dstore.put_file(key, file) finally: self.cache.delete(key)
You are a Python code analyst, evaluating scripts for potential improvements.
def get_file(self, key, file): """Write contents of key to file Like :meth:`.KeyValueStore.put_file`, this method allows backends to implement a specialized function if data needs to be written to disk or streamed. If *file* is a string, contents of *key* are written to a newly...
Can you implement a function in Python 3 that writes contents of key to file VatEntry
As a python code expert, you are capable of creating scripts from specifications.
def put_file(self, key, file): """Store into key from file on disk Stores data from a source into key. *file* can either be a string, which will be interpretet as a filename, or an object with a *read()* method. If the passed object has a *fileno()* method, it may be used to sp...
Create a Python 3 function for storing data from a source file into a key on disk.
You are a Python code architect, reviewing and designing scalable and efficient code
def _check_valid_key(self, key): """Checks if a key is valid and raises a ValueError if its not. When in need of checking a key for validity, always use this method if possible. :param key: The key to be checked """ if not isinstance(key, key_type): raise Va...
Can you implement a function in Python 3 that checks if a key is valid and raises a ValueError if it is not.
As a python code expert, you are capable of creating scripts from specifications.
Write key to file - like object file.
Can you generate a brief explanation for the following Python 3 code def _get_file(self, key, file): bufsize = 1024 * 1024 # note: we do not use a context manager here or close the source. # the source goes out of scope shortly after, taking care of the issue # this allows us to support...
You are a Python code generator, capable of creating scripts from specifications.
Write key to file.
Can you generate a brief explanation for the following Python 3 code def _get_filename(self, key, filename): with open(filename, 'wb') as dest: return self._get_file(key, dest)
You are a Python code architect, reviewing and designing scalable and efficient code
Like : meth : ~simplekv. KeyValueStore. put but with an optional ttl_secs parameter.
How would you explain what the following Python 3 function does def put(self, key, data, ttl_secs=None): self._check_valid_key(key) if not isinstance(data, bytes): raise IOError("Provided data is not of type bytes") return self._put(key, data, self._valid_ttl(ttl_secs))
You are a Python code generator, capable of creating scripts from specifications.
def put_file(self, key, file, ttl_secs=None): """Like :meth:`~simplekv.KeyValueStore.put_file`, but with an additional parameter: :param ttl_secs: Number of seconds until the key expires. See above for valid values. :raises exceptions.ValueError: If ...
Write a Python 3 script for liking : meth : ~simplekv. KeyValueStore. put_file but with an optional ttl_secs parameter.
As a python code expert, you are capable of creating scripts from specifications.
def copy(self, source, dest): """Copies a key. The destination is overwritten if does exist. :param source: The source key to copy :param dest: The destination for the copy :returns: The destination key :raises: exceptions.ValueError: If the source or target key are not valid ...
Can you write a function in Python 3 where it copies a key. The destination key is overwritten if does exist.
As a Python code composer, you craft elegant and concise scripts.
Implementation of NAPALM method open.
Make a summary of the following Python 3 code def open(self): try: if self.transport in ('http', 'https'): connection = pyeapi.client.connect( transport=self.transport, host=self.hostname, username=self.username, ...
As a Python code translator, you convert algorithms and pseudocode into Python.
Implementation of NAPALM method compare_config.
Can you generate the documentation for the following Python 3 function def compare_config(self): if self.config_session is None: return '' else: commands = ['show session-config named %s diffs' % self.config_session] result = self.device.run_commands(commands, encodin...
You are a Python code analyst, evaluating scripts for potential improvements.
Implementation of NAPALM method discard_config.
Given the following Python 3 function, write the documentation def discard_config(self): if self.config_session is not None: commands = [] commands.append('configure session {}'.format(self.config_session)) commands.append('abort') self.device.run_commands(command...
As a python code expert, you are capable of creating scripts from specifications.
Return the SNMP information for the current EOS version.
Can you generate the documentation for the following Python 3 function def get_snmp_information(self): # Default values snmp_dict = { 'chassis_id': '', 'location': '', 'contact': '', 'community': {} } commands = [ 'show snmp c...
As a Python code translator, you convert algorithms and pseudocode into Python.
def get_bgp_neighbors_detail(self, neighbor_address=''): """Implementation of get_bgp_neighbors_detail""" def _parse_per_peer_bgp_detail(peer_output): """This function parses the raw data per peer and returns a json structure per peer. """ int_fields = ['...
Write a Python 3 function that can return a json structure of BGP neighbors.
As a Python code analyst, you investigate and solve complex coding mysteries
get_config implementation for EOS.
Given the following Python 3 function, write the documentation def get_config(self, retrieve="all"): get_startup = retrieve == "all" or retrieve == "startup" get_running = retrieve == "all" or retrieve == "running" get_candidate = (retrieve == "all" or retrieve == "candidate") and self.config_se...
You are a Python code analyst, evaluating scripts for potential improvements.
Map boto - specific exceptions to simplekv - API.
Can you generate the documentation for the following Python 3 function def map_boto_exceptions(key=None, exc_pass=()): from boto.exception import BotoClientError, BotoServerError, \ StorageResponseError try: yield except StorageResponseError as e: if e.code == 'NoSuchKey': ...
You are a Python code architect, reviewing and designing scalable and efficient code
def _check_valid_key(self, key): """Checks if a key is valid and raises a ValueError if its not. When in need of checking a key for validity, always use this method if possible. :param key: The key to be checked """ if not isinstance(key, key_type) and key is not None: ...
Implement a Python 3 function for checking if a key is valid and raises a ValueError if it is not.
You are a Python code architect, reviewing and designing scalable and efficient code
Compute the md5 digest of a file in base64 encoding.
How would you explain what the following Python 3 function does def _file_md5(file_): md5 = hashlib.md5() chunk_size = 128 * md5.block_size for chunk in iter(lambda: file_.read(chunk_size), b''): md5.update(chunk) file_.seek(0) byte_digest = md5.digest() return base64.b64encode(byte_dige...
As a Python code translator, you convert algorithms and pseudocode into Python.
def _byte_buffer_md5(buffer_): """ Computes the md5 digest of a byte buffer in base64 encoding. """ md5 = hashlib.md5(buffer_) byte_digest = md5.digest() return base64.b64encode(byte_digest).decode()
How would you code a function in Python 3 to compute the md5 digest of a byte buffer in base64 encoding.
As a Python code translator, you convert algorithms and pseudocode into Python.
Map Azure - specific exceptions to the simplekv - API.
Make a summary of the following Python 3 code def map_azure_exceptions(key=None, exc_pass=()): from azure.common import AzureMissingResourceHttpError, AzureHttpError,\ AzureException try: yield except AzureMissingResourceHttpError as ex: if ex.__class__.__name__ not in exc_pass: ...
You are a Python code analyst, evaluating scripts for potential improvements.
def read(self, size=-1): """Returns 'size' amount of bytes or less if there is no more data. If no size is given all data is returned. size can be >= 0.""" if self.closed: raise ValueError("I/O operation on closed file") with map_azure_exceptions(key=self.key): if...
Can you write a function in Python 3 where it reads the next size bytes from the file.
You are a Python code analyst, evaluating scripts for potential improvements.
Move to a new offset either relative or absolute.
Make a summary of the following Python 3 code def seek(self, offset, whence=0): if self.closed: raise ValueError("I/O operation on closed file") if whence == 0: if offset < 0: raise IOError('seek would move position outside the file') self.pos = offset...
As a python code expert, you are capable of creating scripts from specifications.
Mounts an object on a tree using the given path components.
How would you explain what the following Python 3 function does def _on_tree(repo, tree, components, obj): # pattern-matching: if len(components) == 1: if isinstance(obj, Blob): mode = 0o100644 elif isinstance(obj, Tree): mode = 0o040000 elif obj is None: ...
You are a Python code analyst, evaluating scripts for potential improvements.
def build_transgenic_lines(self): """ init class | "transgenic_line_source_name":"stock_number" a Class add superClass | rdfs:subClassOf ilxtr:transgenicLine add *order* | ilxtr:useObjectProperty ilxtr:<order> add name | rdfs:label "name" add def |...
How would you code a function in Python 3 to build the Transgenic Line Classes.
As a Python code translator, you convert algorithms and pseudocode into Python.
example datagetter function make any local modifications here
Given the following Python 3 function, write the documentation def datagetter(cls): with open('myfile', 'rt') as f: rows = [r for r in csv.reader(f)] dothing = lambda _: [i for i, v in enumerate(_)] rows = [dothing(_) for _ in rows] raise NotImplementedError('You need to impl...
You are a Python code analyst, evaluating scripts for potential improvements.
example datagetter function make any local modifications here
Explain what the following Python 3 code does def dataproc(cls, graph, data): for thing in data: graph.add_trip(*thing) raise NotImplementedError('You need to implement this yourlself!')
As a Python code composer, you craft elegant and concise scripts.
def _connect(self): """Connect to ec2 resource.""" resource = None try: resource = boto3.resource( 'ec2', aws_access_key_id=self.access_key_id, aws_secret_access_key=self.secret_access_key, region_name=self.region ...
Can you implement a function in Python 3 that connects to ec2 resource.
As a Python code composer, you craft elegant and concise scripts.
def _get_instance(self): """Retrieve instance matching instance_id.""" resource = self._connect() try: instance = resource.Instance(self.running_instance_id) except Exception: raise EC2CloudException( 'Instance with ID: {instance_id} not found.'.f...
Write a Python 3 script to retrieve instance matching instance_id.
As a python code expert, you are capable of creating scripts from specifications.
def _get_instance_state(self): """ Attempt to retrieve the state of the instance. Raises: EC2CloudException: If the instance cannot be found. """ instance = self._get_instance() state = None try: state = instance.state['Name'] exc...
Write a Python 3 script for returning the state of the instance.
You are a Python code generator, capable of creating scripts from specifications.
def _get_user_data(self): """ Return formatted bash script string. The public ssh key is added by cloud init to the instance based on the ssh user and private key file. """ key = ipa_utils.generate_public_ssh_key( self.ssh_private_key_file ).decode() ...
Can you implement a function in Python 3 that returns formatted bash script string.
You are a Python code generator, capable of creating scripts from specifications.
Launch an instance of the given image.
Can you tell what is the following Python 3 function doing def _launch_instance(self): resource = self._connect() instance_name = ipa_utils.generate_instance_name('ec2-ipa-test') kwargs = { 'InstanceType': self.instance_type or EC2_DEFAULT_TYPE, 'ImageId': self.image_id,...
As a Python code analyst, you investigate and solve complex coding mysteries
Retrieve instance ip and cache it.
Can you generate the documentation for the following Python 3 function def _set_instance_ip(self): instance = self._get_instance() # ipv6 try: ipv6 = instance.network_interfaces[0].ipv6_addresses[0] except (IndexError, TypeError): ipv6 = None self.instan...
You are a Python code analyst, evaluating scripts for potential improvements.
def _set_init_system(self, client): """Determine the init system of distribution.""" if not self.init_system: try: out = ipa_utils.execute_ssh_command( client, 'ps -p 1 -o comm=' ) except Exception as e: ...
Create a Python 3 function to determine the init system of distribution.
As a Python code analyst, you investigate and solve complex coding mysteries
Install package on instance.
How would you explain what the following Python 3 function does def install_package(self, client, package): install_cmd = "{sudo} '{install} {package}'".format( sudo=self.get_sudo_exec_wrapper(), install=self.get_install_cmd(), package=package ) try: ...
You are a Python code generator, capable of creating scripts from specifications.
Execute reboot command on instance.
Explain what the following Python 3 code does def reboot(self, client): self._set_init_system(client) reboot_cmd = "{sudo} '{stop_ssh};{reboot}'".format( sudo=self.get_sudo_exec_wrapper(), stop_ssh=self.get_stop_ssh_service_cmd(), reboot=self.get_reboot_cmd() ...
You are a Python code analyst, evaluating scripts for potential improvements.
def update(self, client): """Execute update command on instance.""" update_cmd = "{sudo} '{refresh};{update}'".format( sudo=self.get_sudo_exec_wrapper(), refresh=self.get_refresh_repo_cmd(), update=self.get_update_cmd() ) out = '' try: ...
How would you implement a function in Python 3 that executes update command on instance.
You are a Python code generator, capable of creating scripts from specifications.
def annotate(self, content, includeCat=None, excludeCat=None, minLength=None, longestOnly=None, includeAbbrev=None, includeAcronym=None, includeNumbers=None, output='text/plain; charset=utf-8'): """ Annotate text from: /annotations Arguments: content: The content to annotate ...
Write a Python 3 script to annotate text from the specified content with the specified categories.
As a Python code analyst, you investigate and solve complex coding mysteries
def reachableFrom(self, id, hint=None, relationships=None, lbls=None, callback=None, output='application/json'): """ Get all the nodes reachable from a starting point, traversing the provided edges. from: /graph/reachablefrom/{id} Arguments: id: The type of the edge hint: A ...
How would you implement a function in Python 3 that gets all the nodes reachable from a starting point.
You are a Python code analyst, evaluating scripts for potential improvements.
Iterate over the edges in a SciGraph response.
Can you generate a brief explanation for the following Python 3 code def ordered(start, edges, predicate=None, inverse=False): s, o = 'sub', 'obj' if inverse: s, o = o, s for edge in edges: if predicate is not None and edge['pred'] != predicate: print('sco...
As a Python code translator, you convert algorithms and pseudocode into Python.
def tcsort(item): # FIXME SUCH WOW SO INEFFICIENT O_O """ get len of transitive closure assume type items is tree... """ return len(item[1]) + sum(tcsort(kv) for kv in item[1].items())
Create a Python 3 function to get len of transitive closure assume type items is tree...
You are a Python code analyst, evaluating scripts for potential improvements.
def get_node(start, tree, pnames): """ for each parent find a single branch to root """ def get_first_branch(node): if node not in pnames: # one way to hit a root return [] if pnames[node]: # mmmm names fp = pnames[node][0] if cycle_check(node, fp, pnames): ...
Create a Python 3 function to find a single node in the tree
As a Python code composer, you craft elegant and concise scripts.
This function dematerialize a tree from a parent node.
Make a summary of the following Python 3 code def dematerialize(parent_name, parent_node): # FIXME we need to demat more than just leaves! #FIXME still an issue: Fornix, Striatum, Diagonal Band """ Remove nodes higher in the tree that occur further down the SAME branch. If they occur down OTHER branchs...
As a Python code composer, you craft elegant and concise scripts.
def inv_edges(json): """Switch obj/sub for a set of edges (makes fixing known inverse edges MUCH easier)""" for edge in json['edges']: sub, obj = edge['sub'], edge['obj'] edge['sub'] = obj edge['obj'] = sub edge['pred'] += 'INVERTED'
Can you implement a function in Python 3 that switches obj and sub for a set of edges
You are a Python code architect, reviewing and designing scalable and efficient code
def collect_results(results_file): """Return the result (pass/fail) for json file.""" with open(results_file, 'r') as results: data = json.load(results) return data
Create a Python 3 function for returning the result for json file.
As a Python code composer, you craft elegant and concise scripts.
get the list of terms
Make a summary of the following Python 3 code def get_terms(self): ''' GROUP BY is a shortcut to only getting the first in every list of group ''' if not self.terms.empty: return self.terms if self.from_backup: self.terms = open_pickle(TERMS_BACKUP_PATH) retur...
You are a Python code architect, reviewing and designing scalable and efficient code
def get_terms_complete(self) -> pd.DataFrame: ''' Gets complete entity data like term/view ''' if not self.terms_complete.empty: return self.terms_complete if self.from_backup: self.terms_complete = open_pickle(TERMS_COMPLETE_BACKUP_PATH) return self.terms_com...
Write a Python 3 script to get complete entity data like term view
As a Python code analyst, you investigate and solve complex coding mysteries
def get_ilx2superclass(self, clean:bool=True): ''' clean: for list of literals only ''' ilx2superclass = defaultdict(list) header = ['Index'] + list(self.fetch_superclasses().columns) for row in self.fetch_superclasses().itertuples(): row = {header[i]:val for i, val in enumer...
Create a Python 3 function for returning a dictionary mapping term_ilx to list of superclasses.
As a Python code composer, you craft elegant and concise scripts.
Returns a dictionary mapping tid to list of annotations.
Explain what the following Python 3 code does def get_tid2annotations(self, clean:bool=True): ''' clean: for list of literals only ''' tid2annotations = defaultdict(list) header = ['Index'] + list(self.fetch_annotations().columns) for row in self.fetch_annotations().itertuples(): ...
You are a Python code generator, capable of creating scripts from specifications.
def get_tid2synonyms(self, clean:bool=True): ''' clean: for list of literals only ''' tid2synonyms = {} header = ['Index'] + list(self.fetch_synonyms().columns) for row in self.fetch_synonyms().itertuples(): row = {header[i]:val for i, val in enumerate(row)} if cl...
Write a Python 3 script to return a dictionary of the TID - > Synonym - > list of lists of literals only
You are a Python code architect, reviewing and designing scalable and efficient code
Returns a dictionary mapping ILX to Synonym objects.
Can you tell what is the following Python 3 function doing def get_ilx2synonyms(self, clean:bool=True): ''' clean: for list of literals only ''' ilx2synonyms = defaultdict(list) header = ['Index'] + list(self.fetch_synonyms().columns) for row in self.fetch_synonyms().itertuples(): ...
As a Python code translator, you convert algorithms and pseudocode into Python.
def superclasses_bug_fix(data): ''' PHP returns "id" in superclass but only accepts superclass_tid ''' for i, value in enumerate(data['superclasses']): data['superclasses'][i]['superclass_tid'] = data['superclasses'][i].pop('id') return data
Can you create a Python 3 function that fixes superclass_tid in superclass_tid
As a Python code composer, you craft elegant and concise scripts.