output
stringlengths
1
928k
instruction
stringlengths
7
928k
system
stringlengths
0
104k
def compile(self, source, dest, is_two_file=True, post=None, lang=None): """Compile the docstring into HTML and save as dest.""" makedirs(os.path.dirname(dest)) with io.open(dest, "w+", encoding="utf8") as out_file: with io.open(source, "r", encoding="utf8") as in_file: ...
Write a Python 3 function that can compile the docstring into HTML and save as dest.
You are a Python code analyst, evaluating scripts for potential improvements.
Create a new post.
Here you have a function in Python 3, explain what it does def create_post(self, path, **kw): content = kw.pop('content', None) onefile = kw.pop('onefile', False) # is_page is not used by create_post as of now. kw.pop('is_page', False) metadata = {} metadata.update(self.d...
As a Python code analyst, you investigate and solve complex coding mysteries
def _append_value(self, value, _file, _name): """Call this function to write contents. Keyword arguments: * value - dict, content to be dumped * _file - FileIO, output file * _name - str, name of current content dict """ if self._flag: _k...
Can you implement a function in Python 3 that appends a value to the contents of the current content dict.
As a Python code translator, you convert algorithms and pseudocode into Python.
def _append_array(self, value, _file): """Call this function to write array contents. Keyword arguments: * value - dict, content to be dumped * _file - FileIO, output file """ if not value: self._append_none(None, _file) return _...
Implement a function in Python 3 to append array contents to the file.
You are a Python code analyst, evaluating scripts for potential improvements.
Append branch contents to the file.
Can you generate the documentation for the following Python 3 function def _append_branch(self, value, _file): if not value: return # return self._append_none(None, _file) self._tctr += 1 _vlen = len(value) for (_vctr, (_item, _text)) in enumerate(value.items()):...
As a Python code analyst, you investigate and solve complex coding mysteries
def _append_bytes(self, value, _file): """Call this function to write bytes contents. Keyword arguments: * value - dict, content to be dumped * _file - FileIO, output file """ # binascii.b2a_base64(value) -> plistlib.Data # binascii.a2b_base64(Data) -> v...
Write a Python 3 function for appending bytes to the plistlib. Data object.
As a Python code analyst, you investigate and solve complex coding mysteries
def _append_number(self, value, _file): # pylint: disable=no-self-use """Call this function to write number contents. Keyword arguments: * value - dict, content to be dumped * _file - FileIO, output file """ _text = value _labs = ' {text}'.format(text=_...
Write a Python 3 function for appending number contents to the file.
As a Python code analyst, you investigate and solve complex coding mysteries
def _append_value(self, value, _file, _name): """Call this function to write contents. Keyword arguments: * value - dict, content to be dumped * _file - FileIO, output file * _name - str, name of current content dict """ _tabs = '\t' * self._tctr ...
Implement a function in Python 3 to append a value to the contents of the current object.
As a Python code translator, you convert algorithms and pseudocode into Python.
def _append_array(self, value, _file): """Call this function to write array contents. Keyword arguments: * value - dict, content to be dumped * _file - FileIO, output file """ _labs = ' [' _file.write(_labs) self._tctr += 1 for _item in...
Can you implement a function in Python 3 that appends array contents to the file.
You are a Python code generator, capable of creating scripts from specifications.
Append object contents to the file.
Can you generate the documentation for the following Python 3 function def _append_object(self, value, _file): _labs = ' {' _file.write(_labs) self._tctr += 1 for (_item, _text) in value.items(): _tabs = '\t' * self._tctr _cmma = ',' if self._vctr[self._tctr] els...
You are a Python code architect, reviewing and designing scalable and efficient code
def _append_string(self, value, _file): # pylint: disable=no-self-use """Call this function to write string contents. Keyword arguments: * value - dict, content to be dumped * _file - FileIO, output file """ _text = str(value).replace('"', '\\"') _labs ...
Implement a Python 3 function for appending string contents to file.
You are a Python code generator, capable of creating scripts from specifications.
Append bytes to the end of the list
How would you explain what the following Python 3 function does def _append_bytes(self, value, _file): # pylint: disable=no-self-use # binascii.b2a_base64(value) -> plistlib.Data # binascii.a2b_base64(Data) -> value(bytes) _text = ' '.join(textwrap.wrap(value.hex(), 2)) # _data = [H fo...
As a Python code analyst, you investigate and solve complex coding mysteries
Append date contents to the file.
Can you generate a brief explanation for the following Python 3 code def _append_date(self, value, _file): # pylint: disable=no-self-use _text = value.strftime('%Y-%m-%dT%H:%M:%S.%fZ') _labs = ' "{text}"'.format(text=_text) _file.write(_labs)
As a Python code composer, you craft elegant and concise scripts.
Start the stopwatch if it is paused.
Can you tell what is the following Python 3 function doing def start(self, verbose=None, end_in_new_line=None): if self._start_time is not None and self._end_time is None: # the stopwatch is already running return self if verbose is None: verbose = self.verbose_start ...
As a Python code composer, you craft elegant and concise scripts.
def pause(self): """Pause the stopwatch. If the stopwatch is already paused, nothing will happen. """ if self._end_time is not None: # the stopwatch is already paused return self._end_time = datetime.datetime.now() self._elapsed_time += self._end_...
Implement a Python 3 function for pausing the stopwatch. If the stopwatch is already paused, nothing will happen.
You are a Python code generator, capable of creating scripts from specifications.
def get_elapsed_time(self): """Get the elapsed time of the current split. """ if self._start_time is None or self._end_time is not None: # the stopwatch is paused return self._elapsed_time return self._elapsed_time + (datetime.datetime.now() - self._start_time)
Implement a Python 3 function for getting the elapsed time of the current split.
As a Python code analyst, you investigate and solve complex coding mysteries
Save the elapsed time of the current split and restart the stopwatch.
Here you have a function in Python 3, explain what it does def split(self, verbose=None, end_in_new_line=None): elapsed_time = self.get_elapsed_time() self.split_elapsed_time.append(elapsed_time) self._cumulative_elapsed_time += elapsed_time self._elapsed_time = datetime.timedelta() ...
As a Python code analyst, you investigate and solve complex coding mysteries
Wrapper for using bbduk to quality trim reads.
Can you generate a brief explanation for the following Python 3 code def bbduk_trim(forward_in, forward_out, reverse_in='NA', reverse_out='NA', returncmd=False, **kwargs): options = kwargs_to_string(kwargs) cmd = 'which bbduk.sh' try: subprocess.check_output(cmd.split()).decode('utf-8') except s...
As a Python code analyst, you investigate and solve complex coding mysteries
Find the genome size of an organsim based on the peaks file.
Can you tell what is the following Python 3 function doing def genome_size(peaks_file, haploid=True): size = 0 with open(peaks_file) as peaks: lines = peaks.readlines() for line in lines: if haploid: if '#haploid_genome_size' in line: size = int(line.split()[1]) ...
You are a Python code generator, capable of creating scripts from specifications.
Downloads multiple accounts from Gitkit server.
Can you tell what is the following Python 3 function doing def DownloadAccount(self, next_page_token=None, max_results=None): param = {} if next_page_token: param['nextPageToken'] = next_page_token if max_results: param['maxResults'] = max_results response = self._InvokeGitkitApi('downloadAc...
As a Python code composer, you craft elegant and concise scripts.
Uploads multiple accounts to Gitkit server.
Explain what the following Python 3 code does def UploadAccount(self, hash_algorithm, hash_key, accounts): param = { 'hashAlgorithm': hash_algorithm, 'signerKey': hash_key, 'users': accounts } # pylint does not recognize the return type of simplejson.loads # pylint: disable=maybe...
You are a Python code generator, capable of creating scripts from specifications.
def GetPublicCert(self): """Download Gitkit public cert. Returns: dict of public certs. """ cert_url = self.google_api_url + 'publicKeys' resp, content = self.http.request(cert_url) if resp.status == 200: return simplejson.loads(content) else: raise errors.GitkitServerEr...
Can you create a Python 3 function that downloads Gitkit public cert.
As a Python code translator, you convert algorithms and pseudocode into Python.
Invokes Gitkit API, with optional access token for service account. Args: method: string, the api method name. params: dict of optional parameters for the API. need_service_account: false if service account is not needed. Raises: GitkitClientError: if the request is bad. GitkitSe...
Can you generate the documentation for the following Python 3 function def _InvokeGitkitApi(self, method, params=None, need_service_account=True): body = simplejson.dumps(params) if params else None req = urllib_request.Request(self.google_api_url + method) req.add_header('Content-type', 'application/json')...
You are a Python code generator, capable of creating scripts from specifications.
Gets oauth2 access token for Gitkit API using service account.
How would you explain what the following Python 3 function does def _GetAccessToken(self): d = { 'assertion': self._GenerateAssertion(), 'grant_type': 'urn:ietf:params:oauth:grant-type:jwt-bearer', } try: body = parse.urlencode(d) except AttributeError: body = urllib.urle...
As a Python code analyst, you investigate and solve complex coding mysteries
Generates the signed Json Web Token that will be used in the request.
Here you have a function in Python 3, explain what it does def _GenerateAssertion(self): now = int(time.time()) payload = { 'aud': RpcHelper.TOKEN_ENDPOINT, 'scope': 'https://www.googleapis.com/auth/identitytoolkit', 'iat': now, 'exp': now + RpcHelper.MAX_TOKEN_LIFETIME_SECS, ...
You are a Python code analyst, evaluating scripts for potential improvements.
Raises error if API invocation failed.
Make a summary of the following Python 3 code def _CheckGitkitError(self, raw_response): try: response = simplejson.loads(raw_response) if 'error' not in response: return response else: error = response['error'] if 'code' in error: code = error['code'] i...
As a python code expert, you are capable of creating scripts from specifications.
def FromDictionary(cls, dictionary): """Initializes from user specified dictionary. Args: dictionary: dict of user specified attributes Returns: GitkitUser object """ if 'user_id' in dictionary: raise errors.GitkitClientError('use localId instead') if 'localId' not in dictiona...
Can you write a function in Python 3 where it initializes from user specified dictionary.
You are a Python code generator, capable of creating scripts from specifications.
Converts the object to a gitkit api request parameter dict.
Can you generate the documentation for the following Python 3 function def ToRequest(self): param = {} if self.email: param['email'] = self.email if self.user_id: param['localId'] = self.user_id if self.name: param['displayName'] = self.name if self.photo_url: param['photoUrl...
As a python code expert, you are capable of creating scripts from specifications.
Verifies a Gitkit token string.
Given the following Python 3 function, write the documentation def VerifyGitkitToken(self, jwt): certs = self.rpc_helper.GetPublicCert() crypt.MAX_TOKEN_LIFETIME_SECS = 30 * 86400 # 30 days parsed = None for aud in filter(lambda x: x is not None, [self.project_id, self.client_id]): try: p...
You are a Python code generator, capable of creating scripts from specifications.
Gets user info by email.
Explain what the following Python 3 code does def GetUserByEmail(self, email): user = self.rpc_helper.GetAccountInfoByEmail(email) return GitkitUser.FromApiResponse(user)
As a python code expert, you are capable of creating scripts from specifications.
Gets a user info by id.
Explain what the following Python 3 code does def GetUserById(self, local_id): user = self.rpc_helper.GetAccountInfoById(local_id) return GitkitUser.FromApiResponse(user)
You are a Python code analyst, evaluating scripts for potential improvements.
Uploads multiple users to Gitkit server.
Can you tell what is the following Python 3 function doing def UploadUsers(self, hash_algorithm, hash_key, accounts): return self.rpc_helper.UploadAccount(hash_algorithm, base64.urlsafe_b64encode(hash_key), [GitkitUser.ToRequest(i) fo...
As a Python code analyst, you investigate and solve complex coding mysteries
def GetAllUsers(self, pagination_size=10): """Gets all user info from Gitkit server. Args: pagination_size: int, how many users should be returned per request. The account info are retrieved in pagination. Yields: A generator to iterate all users. """ next_page_token, account...
Write a Python 3 function for getting all users from Gitkit server.
As a Python code analyst, you investigate and solve complex coding mysteries
Returns the out - of - band code for the specified action.
Can you generate a brief explanation for the following Python 3 code def GetOobResult(self, param, user_ip, gitkit_token=None): if 'action' in param: try: if param['action'] == GitkitClient.RESET_PASSWORD_ACTION: request = self._PasswordResetRequest(param, user_ip) oob_code, oob_li...
As a Python code translator, you convert algorithms and pseudocode into Python.
def _BuildOobLink(self, param, mode): """Builds out-of-band URL. Gitkit API GetOobCode() is called and the returning code is combined with Gitkit widget URL to building the out-of-band url. Args: param: dict of request. mode: string, Gitkit widget mode to handle the oob action after user ...
Implement a Python 3 function for building out - of - band url.
You are a Python code architect, reviewing and designing scalable and efficient code
def run_subprocess(command): """ command is the command to run, as a string. runs a subprocess, returns stdout and stderr from the subprocess as strings. """ x = Popen(command, shell=True, stdout=PIPE, stderr=PIPE) out, err = x.communicate() out = out.decode('utf-8') err = err.decode('ut...
Can you implement a function in Python 3 that runs a subprocess and returns stdout and stderr as strings.
You are a Python code architect, reviewing and designing scalable and efficient code
def kwargs_to_string(kwargs): """ Given a set of kwargs, turns them into a string which can then be passed to a command. :param kwargs: kwargs from a function call. :return: outstr: A string, which is '' if no kwargs were given, and the kwargs in string format otherwise. """ outstr = '' for ...
Create a Python 3 function for taking a set of kwargs and turns them into a string which can then be passed to a command.
As a Python code analyst, you investigate and solve complex coding mysteries
def read_mash_output(result_file): """ :param result_file: Tab-delimited result file generated by mash dist. :return: mash_results: A list with each entry in the result file as an entry, with attributes reference, query, distance, pvalue, and matching_hash """ with open(result_file) as handle: ...
How would you code a function in Python 3 to read the output of mash dist into a list of MashResult objects.
As a python code expert, you are capable of creating scripts from specifications.
Reads the mash screen result file and returns a list of ScreenResult objects.
Can you generate the documentation for the following Python 3 function def read_mash_screen(screen_result): with open(screen_result) as handle: lines = handle.readlines() results = list() for line in lines: result = ScreenResult(line) results.append(result) return results
As a Python code analyst, you investigate and solve complex coding mysteries
def run_cmd(cmd): """ Runs a command using subprocess, and returns both the stdout and stderr from that command If exit code from command is non-zero, raises subproess.CalledProcessError :param cmd: command to run as a string, as it would be called on the command line :return: out, err: Strings that...
Implement a Python 3 function for running a command using subprocess and returns both the stdout and stderr from that command.
You are a Python code analyst, evaluating scripts for potential improvements.
Writes stdout stderr and a command to a logfile
Can you generate the documentation for the following Python 3 function def write_to_logfile(logfile, out, err, cmd): with open(logfile, 'a+') as outfile: outfile.write('Command used: {}\n\n'.format(cmd)) outfile.write('STDOUT: {}\n\n'.format(out)) outfile.write('STDERR: {}\n\n'.format(err))
You are a Python code generator, capable of creating scripts from specifications.
Returns a list of pairs of fastq files that are paired.
Can you generate the documentation for the following Python 3 function def find_paired_reads(fastq_directory, forward_id='_R1', reverse_id='_R2'): pair_list = list() fastq_files = glob.glob(os.path.join(fastq_directory, '*.f*q*')) for name in sorted(fastq_files): if forward_id in name and os.path.i...
You are a Python code architect, reviewing and designing scalable and efficient code
Find unpaired reads in a directory.
Can you tell what is the following Python 3 function doing def find_unpaired_reads(fastq_directory, forward_id='_R1', reverse_id='_R2', find_fasta=False): read_list = list() if find_fasta is False: fastq_files = glob.glob(os.path.join(fastq_directory, '*.f*q*')) else: # Very misnamed! ...
As a Python code translator, you convert algorithms and pseudocode into Python.
Find the list of species - specific alleles for a given genus.
Can you tell what is the following Python 3 function doing def find_genusspecific_allele_list(profiles_file, target_genus): alleles = list() with open(profiles_file) as f: lines = f.readlines() for line in lines: line = line.rstrip() genus = line.split(':')[0] if genus == tar...
You are a Python code analyst, evaluating scripts for potential improvements.
def extract_rmlst_genes(pair, database, forward_out, reverse_out, threads=12, logfile=None): """ Given a pair of reads and an rMLST database, will extract reads that contain sequence from the database. :param pair: List containing path to forward reads at index 0 and path to reverse reads at index 1. :p...
Write a Python 3 function for giving a pair of reads and an rMLST database will extract the genes that are in the database.
As a Python code translator, you convert algorithms and pseudocode into Python.
Uses mash to find out if or not a sample has more than one cross - contamination.
Can you tell what is the following Python 3 function doing def find_cross_contamination(databases, pair, tmpdir='tmp', log='log.txt', threads=1): genera_present = list() out, err, cmd = mash.screen('{}/refseq.msh'.format(databases), pair[0], pair[1], threads=threads, w='', i='0.9...
You are a Python code generator, capable of creating scripts from specifications.
Returns True if a site has at least two bases of high quality and that it can be considered as a single base.
Can you generate the documentation for the following Python 3 function def number_of_bases_above_threshold(high_quality_base_count, base_count_cutoff=2, base_fraction_cutoff=None): # make a dict by dictionary comprehension where values are True or False for each base depending on whether the count meets the thresh...
As a Python code analyst, you investigate and solve complex coding mysteries
Finds if a position in a pileup column has more than one base present.
Given the following Python 3 function, write the documentation def find_if_multibase(column, quality_cutoff, base_cutoff, base_fraction_cutoff): # Sometimes the qualities come out to ridiculously high (>70) values. Looks to be because sometimes reads # are overlapping and the qualities get summed for overlappin...
You are a Python code architect, reviewing and designing scalable and efficient code
Gets contig names from a fasta file using SeqIO.
Can you generate the documentation for the following Python 3 function def get_contig_names(fasta_file): contig_names = list() for contig in SeqIO.parse(fasta_file, 'fasta'): contig_names.append(contig.id) return contig_names
As a python code expert, you are capable of creating scripts from specifications.
def read_contig(contig_name, bamfile_name, reference_fasta, quality_cutoff=20, base_cutoff=2, base_fraction_cutoff=None): """ Examines a contig to find if there are positions where more than one base is present. :param contig_name: Name of contig as a string. :param bamfile_name: Full path to bamfile. M...
Create a Python 3 function to read a contig from a BAM file and returns a dictionary of positions where more than one base is present.
You are a Python code architect, reviewing and designing scalable and efficient code
def find_rmlst_type(kma_report, rmlst_report): """ Uses a report generated by KMA to determine what allele is present for each rMLST gene. :param kma_report: The .res report generated by KMA. :param rmlst_report: rMLST report file to write information to. :return: a sorted list of loci present, in f...
Implement a function in Python 3 to find the loci present in the rMLST report file.
You are a Python code analyst, evaluating scripts for potential improvements.
def base_dict_to_string(base_dict): """ Converts a dictionary to a string. {'C': 12, 'A':4} gets converted to C:12;A:4 :param base_dict: Dictionary of bases and counts created by find_if_multibase :return: String representing that dictionary. """ outstr = '' # First, sort base_dict so that m...
Write a Python 3 script to convert a dictionary of bases and counts created by find_if_multibase to a string.
As a python code expert, you are capable of creating scripts from specifications.
def find_total_sequence_length(fasta_file): """ Totals up number of bases in a fasta file. :param fasta_file: Path to an uncompressed, fasta-formatted file. :return: Number of total bases in file, as an int. """ total_length = 0 for sequence in SeqIO.parse(fasta_file, 'fasta'): total...
How would you code a function in Python 3 to find the total length of the sequence in a file.
As a Python code translator, you convert algorithms and pseudocode into Python.
Estimate the percent contamination of a sample.
Can you generate a brief explanation for the following Python 3 code def estimate_percent_contamination(contamination_report_file): contam_levels = list() with open(contamination_report_file) as csvfile: reader = csv.DictReader(csvfile) for row in reader: lowest_count = 99999 ...
As a Python code translator, you convert algorithms and pseudocode into Python.
This function finds the contamination of a pair of reads.
How would you explain what the following Python 3 function does def find_contamination(pair, output_folder, databases_folder, forward_id='_R1', threads=1, keep_files=False, quality_cutoff=20, base_cutoff=2, base_fraction_cutoff=0.05, cgmlst_db=None, Xmx=None, tmpdir=None, d...
As a Python code analyst, you investigate and solve complex coding mysteries
def write_output(output_report, sample_name, multi_positions, genus, percent_contam, contam_stddev, total_gene_length, database_download_date, snp_cutoff=3, cgmlst=None): """ Function that writes the output generated by ConFindr to a report file. Appends to a file that already exists, or cr...
Create a Python 3 function for functioning that writes the output of ConFindr to a CSV file.
You are a Python code architect, reviewing and designing scalable and efficient code
Checks that the XMX string is acceptable by BBTools.
Can you tell what is the following Python 3 function doing def check_acceptable_xmx(xmx_string): acceptable_xmx = True acceptable_suffixes = ['K', 'M', 'G'] if xmx_string[-1].upper() not in acceptable_suffixes: acceptable_xmx = False logging.error('ERROR: Memory must be specified as K (kilob...
You are a Python code analyst, evaluating scripts for potential improvements.
Returns an instance of the Character set code field.
How would you explain what the following Python 3 function does def char_code(columns, name=None): if name is None: name = 'Char Code Field (' + str(columns) + ' columns)' if columns <= 0: raise BaseException() char_sets = None for char_set in _tables.get_data('character_set'): ...
As a Python code analyst, you investigate and solve complex coding mysteries
Creates a callable that accepts the user input.
Can you tell what is the following Python 3 function doing def make_choice_validator( choices, default_key=None, normalizer=None): """ Returns a callable that accepts the choices provided. Choices should be provided as a list of 2-tuples, where the first element is a string that should match us...
As a Python code composer, you craft elegant and concise scripts.
def prompt(question, validator=None, choices=None, default_key=NotImplemented, normalizer=str.lower, _stdin=None, _stdout=None): """ Prompt user for question, maybe choices, and get answer. Arguments: question The question to prompt. It will only be prompted o...
Write a Python 3 function that can prompt user for question maybe choices and get answer.
As a Python code analyst, you investigate and solve complex coding mysteries
def prompt_overwrite_json(original, new, target_path, dumps=json_dumps): """ Prompt end user with a diff of original and new json that may overwrite the file at the target_path. This function only displays a confirmation prompt and it is up to the caller to implement the actual functionality. Opti...
Write a Python 3 script for prompting end user with a diff of original and new json that may overwrite the file at the target_path.
You are a Python code architect, reviewing and designing scalable and efficient code
def locate_package_entry_file(working_dir, package_name): """ Locate a single npm package to return its browser or main entry. """ basedir = join(working_dir, 'node_modules', package_name) package_json = join(basedir, 'package.json') if not exists(package_json): logger.debug( ...
Can you create a Python 3 function that locates a single npm package to return its browser or main entry.
As a Python code analyst, you investigate and solve complex coding mysteries
Template tag to render a list of pictures.
Can you tell what is the following Python 3 function doing def render_pictures(context, selection='recent', amount=3): pictures = Image.objects.filter( folder__id__in=Gallery.objects.filter(is_published=True).values_list( 'folder__pk', flat=True)) if selection == 'recent': context.up...
As a Python code translator, you convert algorithms and pseudocode into Python.
Parses the VCF Header field and returns the number of samples in the VCF file
How would you explain what the following Python 3 function does def add_header(self, entry): info = entry.split('\t') self.n_individuals = len(info)-9 for i,v in enumerate(info[9:]): self.individuals[v] = i return self.n_individuals > 0
You are a Python code architect, reviewing and designing scalable and efficient code
def parse_entry(self, row): """Parse an individual VCF entry and return a VCFEntry which contains information about the call (such as alternative allele, zygosity, etc.) """ var_call = VCFEntry(self.individuals) var_call.parse_entry(row) return var_call
Implement a Python 3 function for parsing an individual VCF entry and return a VCFEntry which contains information about the call.
As a python code expert, you are capable of creating scripts from specifications.
Returns the vcf header
Here you have a function in Python 3, explain what it does def get_header(self, individual=-1): type_map = dict([(val,key) for key,val in self.meta.type_map.iteritems()]) extra = '\n'.join(['##{0}'.format(i) for i in self.meta.extra]) info = '\n'.join(['##INFO=<ID={0},Number={1},Type={2},Descrip...
You are a Python code architect, reviewing and designing scalable and efficient code
Parse and store the info field
Given the following Python 3 function, write the documentation def add_info(self, entry): entry = entry[8:-1] info = entry.split(',') if len(info) < 4: return False for v in info: key, value = v.split('=', 1) if key == 'ID': self.info[v...
You are a Python code analyst, evaluating scripts for potential improvements.
Parse and store the filter field
Can you generate a brief explanation for the following Python 3 code def add_filter(self, entry): entry = entry[10:-1] info = entry.split(',') if len(info) < 2: return False for v in info: key, value = v.split('=', 1) if key == 'ID': se...
As a python code expert, you are capable of creating scripts from specifications.
def add_alt(self, entry): """Parse and store the alternative allele field""" entry = entry[7:-1] info = entry.split(',') if len(info) < 2: return False for v in info: key, value = v.split('=', 1) if key == 'ID': self.alt[value] ...
Can you write a function in Python 3 where it parses and store the alternative allele field
You are a Python code architect, reviewing and designing scalable and efficient code
Returns the VCF entry as it appears in the vcf file
Here you have a function in Python 3, explain what it does def sample_string(self, individual=-1): base = str(self) extra = self.get_sample_info(individual=individual) extra = [':'.join([str(j) for j in i]) for i in zip(*extra.values())] return '\t'.join([base, '\t'.join(extra)])
As a Python code composer, you craft elegant and concise scripts.
def get_sample_info(self, individual=-1): """Returns the sample info of a given sample or all by default """ if isinstance(individual, str): individual = self.individuals[individual] extra = OrderedDict() for format_ in self.format: index = getattr(self, ...
Write a Python 3 function that can return the sample info of a given sample or all by default
You are a Python code analyst, evaluating scripts for potential improvements.
def get_alt(self, individual=0, nucleotides_only=True): """Returns the alternative alleles of the individual as a list""" #not i.startswith(',') is put in to handle cases like <DEL:ME:ALU> where we have no alternate allele #but some reference if isinstance(individual, str): i...
Write a Python 3 script to return the alternative alleles of the individual as a list
As a Python code composer, you craft elegant and concise scripts.
Returns the number of basepairs of each alternative allele
Can you tell what is the following Python 3 function doing def get_alt_length(self, individual=0): if isinstance(individual, str): individual = self.individuals[individual] return [len(self.alt[i-1].replace('.','')) for i in self.genotype[individual] if i > 0 and not self.alt[i-1].startswith...
As a Python code analyst, you investigate and solve complex coding mysteries
Returns the longest length of the variant. For deletions returns is negative and insertions are +.
Explain what the following Python 3 code does def get_alt_lengths(self): #this is a hack to store the # of individuals without having to actually store it out = [] for i in six.moves.range(len(self.genotype)): valid_alt = self.get_alt_length(individual=i) if not valid_alt...
As a Python code analyst, you investigate and solve complex coding mysteries
Returns a boolean list of SNP status ordered by samples
Here you have a function in Python 3, explain what it does def has_snp(self, individual=0): if isinstance(individual, str): individual = self.individuals[individual] alts = self.get_alt(individual=individual) if alts: return [i != self.ref and len(i) == len(self.ref) for ...
You are a Python code architect, reviewing and designing scalable and efficient code
This parses a VCF row and stores the relevant information
How would you explain what the following Python 3 function does def parse_entry(self, entry): entry = entry.split('\t') self.chrom, self.pos, self.id, self.ref, alt_, self.qual, filter_, info, self.format = entry[:9] self.samples = entry[9:] self.alt = alt_.split(',') if filter_ ...
You are a Python code architect, reviewing and designing scalable and efficient code
Add a child to the entry.
Explain what the following Python 3 code does def add_child(self, child): child_id = getattr(child, 'id', None) if child_id: if not hasattr(self, 'children'): self.children = {} if child_id not in self.children: self.children[child_id] = child
You are a Python code analyst, evaluating scripts for potential improvements.
def _iso_handler(obj): """ Transforms an object into it's ISO format, if possible. If the object can't be transformed, then an error is raised for the JSON parser. This is meant to be used on datetime instances, but will work with any object having a method called isoformat. :param obj: o...
Can you write a function in Python 3 where it handles the ISO formatting of an object.
As a python code expert, you are capable of creating scripts from specifications.
def encode(self, entity): """ Generate string of cwr format for all possible combinations of fields, accumulate and then elect the best. The best string it is who used most of all fields :param entity: :return: """ possible_results = [] entity_dict = self....
Create a Python 3 function for generating string of cwr format for all possible combinations of fields and entity.
You are a Python code architect, reviewing and designing scalable and efficient code
def argparser(self): """ For setting up the argparser for this instance. """ if self.__argparser is None: self.__argparser = self.argparser_factory() self.init_argparser(self.__argparser) return self.__argparser
How would you code a function in Python 3 to return the argparser for this instance.
You are a Python code analyst, evaluating scripts for potential improvements.
def argparser_factory(self): """ Produces argparser for this type of Runtime. """ return ArgumentParser( prog=self.prog, description=self.__doc__, add_help=False, )
How would you implement a function in Python 3 that produces an argparser for this type of Runtime.
As a Python code composer, you craft elegant and concise scripts.
Initialize the argparser for the internal version of the system.
Here you have a function in Python 3, explain what it does def init_argparser(self, argparser): def prepare_argparser(): if argparser in self.argparser_details: return False result = self.argparser_details[argparser] = ArgumentParserDetails( {}, {}, {}) ...
You are a Python code architect, reviewing and designing scalable and efficient code
This function is called by the argparse module to check if unrecognized arguments are present in the arguments list.
How would you explain what the following Python 3 function does def unrecognized_arguments_error(self, args, parsed, extras): # loop variants kwargs = vars(parsed) failed = list(extras) # initial values runtime, subparser, idx = (self, self.argparser, 0) # recursion not ...
As a Python code analyst, you investigate and solve complex coding mysteries
This method is used to log an error message for the specified target parser.
Can you generate a brief explanation for the following Python 3 code def error(self, argparser, target, message): warnings.warn( 'Runtime.error is deprecated and will be removed by calmjs-4.0.0', DeprecationWarning) details = self.get_argparser_details(argparser) argpars...
You are a Python code generator, capable of creating scripts from specifications.
This method is used to initialize the argument parser for the specific locale.
Can you tell what is the following Python 3 function doing def init_argparser_export_target( self, argparser, default=None, help='the export target', ): """ Subclass could override this by providing alternative keyword arguments and call this as it...
You are a Python code generator, capable of creating scripts from specifications.
def init_argparser_working_dir( self, argparser, explanation='', help_template=( 'the working directory; %(explanation)s' 'default is current working directory (%(cwd)s)'), ): """ Subclass could an extra expanation on how th...
Can you write a function in Python 3 where it initializes the argument parser for the working directory.
As a Python code analyst, you investigate and solve complex coding mysteries
def init_argparser_build_dir( self, argparser, help=( 'the build directory, where all sources will be copied to ' 'as part of the build process; if left unspecified, the ' 'default behavior is to create a new temporary directory ' 'that will be...
How would you implement a function in Python 3 that initializes the argument parser for the build directory.
As a Python code translator, you convert algorithms and pseudocode into Python.
Initializes the argument parser for optional advice.
Here you have a function in Python 3, explain what it does def init_argparser_optional_advice( self, argparser, default=[], help=( 'a comma separated list of packages to retrieve optional ' 'advice from; the provided packages should have registered ' 'the appr...
You are a Python code analyst, evaluating scripts for potential improvements.
def init_argparser(self, argparser): """ Other runtimes (or users of ArgumentParser) can pass their subparser into here to collect the arguments here for a subcommand. """ super(ToolchainRuntime, self).init_argparser(argparser) # it is possible for subclasses to...
Create a Python 3 function to initialize the argument parser for the current version of the toolchain.
As a Python code translator, you convert algorithms and pseudocode into Python.
def prepare_spec(self, spec, **kwargs): """ Prepare a spec for usage with the generic ToolchainRuntime. Subclasses should avoid overriding this; override create_spec instead. """ self.prepare_spec_debug_flag(spec, **kwargs) self.prepare_spec_export_target_checks...
Write a Python 3 function for preparing a spec for usage with the generic ToolchainRuntime.
As a python code expert, you are capable of creating scripts from specifications.
def kwargs_to_spec(self, **kwargs): """ Turn the provided kwargs into arguments ready for toolchain. """ spec = self.create_spec(**kwargs) self.prepare_spec(spec, **kwargs) return spec
Can you implement a function in Python 3 that turns the provided kwargs into a spec ready for toolchain.
As a Python code composer, you craft elegant and concise scripts.
Initialize the argument parser for the package_names option.
Can you generate the documentation for the following Python 3 function def init_argparser_package_names(self, argparser, help=( 'names of the python package to generate artifacts for; ' 'note that the metadata directory for the specified ' 'packages must be writable')): ...
As a Python code analyst, you investigate and solve complex coding mysteries
def init_argparser_source_registry( self, argparser, default=None, help=( 'comma separated list of registries to use for gathering ' 'JavaScript sources from the given Python packages' )): """ For setting up the source registry flag. """ ...
Create a Python 3 function to initialize the argument parser for the source registry flag.
You are a Python code generator, capable of creating scripts from specifications.
Initialize the given argument parser for loaderplugin registries.
Given the following Python 3 function, write the documentation def init_argparser_loaderplugin_registry( self, argparser, default=None, help=( 'the name of the registry to use for the handling of loader ' 'plugins that may be loaded from the given Python packages' ...
As a python code expert, you are capable of creating scripts from specifications.
def init_argparser(self, argparser): """ Other runtimes (or users of ArgumentParser) can pass their subparser into here to collect the arguments here for a subcommand. """ super(SourcePackageToolchainRuntime, self).init_argparser(argparser) self.init_argparser_s...
Write a Python 3 script for initializing the argument parser.
You are a Python code architect, reviewing and designing scalable and efficient code
def alphanum(columns, name=None, extended=False, isLast=False): """ Creates the grammar for an Alphanumeric (A) field, accepting only the specified number of characters. By default Alphanumeric fields accept only ASCII characters, excluding lowercases. If the extended flag is set to True, then non-...
Can you write a function in Python 3 where it returns a grammar for an Alphanumeric field.
As a Python code composer, you craft elegant and concise scripts.
Checks that the string is not empty.
Can you generate a brief explanation for the following Python 3 code def _check_not_empty(string): string = string.strip() if len(string) == 0: message = 'The string should not be empty' raise pp.ParseException(message)
You are a Python code generator, capable of creating scripts from specifications.
def numeric(columns, name=None): """ Creates the grammar for a Numeric (N) field, accepting only the specified number of characters. This version only allows integers. :param columns: number of columns for this field :param name: name for the field :return: grammar for the integer numeric ...
Create a Python 3 function for returning a grammar for a numeric field.
You are a Python code architect, reviewing and designing scalable and efficient code
Returns a grammar for a numeric field with the specified number of characters.
Here you have a function in Python 3, explain what it does def numeric_float(columns, nums_int, name=None): if name is None: name = 'Numeric Field' if columns <= 0: # Can't be empty or have negative size raise BaseException('Number of columns should be positive') if nums_int < 0: ...
As a Python code composer, you craft elegant and concise scripts.
Transforms a string into a float.
Make a summary of the following Python 3 code def _to_numeric_float(number, nums_int): index_end = len(number) - nums_int return float(number[:nums_int] + '.' + number[-index_end:])
You are a Python code analyst, evaluating scripts for potential improvements.