code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
_labs = ' {' _file.write(_labs) self._tctr += 1 for (_item, _text) in value.items(): _tabs = '\t' * self._tctr _cmma = ',' if self._vctr[self._tctr] else '' _keys = '{cmma}\n{tabs}"{item}" :'.format(cmma=_cmma, tabs=_tabs, item=_item) ...
def _append_object(self, value, _file)
Call this function to write object contents. Keyword arguments: * value - dict, content to be dumped * _file - FileIO, output file
4.212078
4.248722
0.991375
def _append_string(self, value, _file): # pylint: disable=no-self-use _text = str(value).replace('"', '\\"') _labs = ' "{text}"'.format(text=_text) _file.write(_labs)
Call this function to write string contents. Keyword arguments: * value - dict, content to be dumped * _file - FileIO, output file
null
null
null
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 for H in iter( # functools.partial(io.Str...
Call this function to write bytes contents. Keyword arguments: * value - dict, content to be dumped * _file - FileIO, output file
null
null
null
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)
Call this function to write date contents. Keyword arguments: * value - dict, content to be dumped * _file - FileIO, output file
null
null
null
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 if verbose: if end_in_new_line is None: end_in_new_line = self.end_...
def start(self, verbose=None, end_in_new_line=None)
Start the stopwatch if it is paused. If the stopwatch is already started, then nothing will happen. Parameters ---------- verbose : Optional[bool] Wether to log. If `None`, use `verbose_start` set during initialization. end_in_new_line : Optional[bool]] ...
2.266644
2.04534
1.108199
if self._end_time is not None: # the stopwatch is already paused return self._end_time = datetime.datetime.now() self._elapsed_time += self._end_time - self._start_time
def pause(self)
Pause the stopwatch. If the stopwatch is already paused, nothing will happen.
3.561436
2.970614
1.198889
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)
def get_elapsed_time(self)
Get the elapsed time of the current split.
3.903898
3.690683
1.057771
elapsed_time = self.get_elapsed_time() self.split_elapsed_time.append(elapsed_time) self._cumulative_elapsed_time += elapsed_time self._elapsed_time = datetime.timedelta() if verbose is None: verbose = self.verbose_end if verbose: if end_i...
def split(self, verbose=None, end_in_new_line=None)
Save the elapsed time of the current split and restart the stopwatch. The current elapsed time will be appended to :attr:`split_elapsed_time`. If the stopwatch is paused, then it will remain paused. Otherwise, it will continue running. Parameters ---------- verbose : Op...
2.530585
2.056776
1.230365
self._start_time = None self._end_time = None self._elapsed_time = datetime.timedelta() self._cumulative_elapsed_time = datetime.timedelta() self.split_elapsed_time = []
def reset(self)
Reset the stopwatch.
4.020026
3.417649
1.176255
options = kwargs_to_string(kwargs) cmd = 'which bbduk.sh' try: subprocess.check_output(cmd.split()).decode('utf-8') except subprocess.CalledProcessError: print('ERROR: Could not find bbduk. Plase check that the bbtools package is installed and on your $PATH.\n\n') raise File...
def bbduk_trim(forward_in, forward_out, reverse_in='NA', reverse_out='NA', returncmd=False, **kwargs)
Wrapper for using bbduk to quality trim reads. Contains arguments used in OLC Assembly Pipeline, but these can be overwritten by using keyword parameters. :param forward_in: Forward reads you want to quality trim. :param returncmd: If set to true, function will return the cmd string passed to subprocess as ...
2.158199
2.101571
1.026945
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]) else: if '#genome_size' in line: size = int(line.split()[1]) ...
def genome_size(peaks_file, haploid=True)
Finds the genome size of an organsim, based on the peaks file created by kmercountexact.sh :param peaks_file: Path to peaks file created by kmercountexact. :param haploid: Set to True if organism of interest is haploid, False if not. Default True. :return: size of genome, as an int. If size could not be fou...
2.009789
2.082009
0.965313
param = {} if next_page_token: param['nextPageToken'] = next_page_token if max_results: param['maxResults'] = max_results response = self._InvokeGitkitApi('downloadAccount', param) # pylint does not recognize the return type of simplejson.loads # pylint: disable=maybe-no-member ...
def DownloadAccount(self, next_page_token=None, max_results=None)
Downloads multiple accounts from Gitkit server. Args: next_page_token: string, pagination token. max_results: pagination size. Returns: An array of accounts.
3.846335
4.17754
0.920718
param = { 'hashAlgorithm': hash_algorithm, 'signerKey': hash_key, 'users': accounts } # pylint does not recognize the return type of simplejson.loads # pylint: disable=maybe-no-member return self._InvokeGitkitApi('uploadAccount', param)
def UploadAccount(self, hash_algorithm, hash_key, accounts)
Uploads multiple accounts to Gitkit server. Args: hash_algorithm: string, algorithm to hash password. hash_key: string, base64-encoded key of the algorithm. accounts: array of accounts to be uploaded. Returns: Response of the API.
7.460341
7.380782
1.010779
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.GitkitServerError('Error response for cert url: %s' % content)
def GetPublicCert(self)
Download Gitkit public cert. Returns: dict of public certs.
7.054423
4.716446
1.495707
body = simplejson.dumps(params) if params else None req = urllib_request.Request(self.google_api_url + method) req.add_header('Content-type', 'application/json') if need_service_account: if self.credentials: access_token = self.credentials.get_access_token().access_token elif se...
def _InvokeGitkitApi(self, method, params=None, need_service_account=True)
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...
2.319129
2.353669
0.985325
d = { 'assertion': self._GenerateAssertion(), 'grant_type': 'urn:ietf:params:oauth:grant-type:jwt-bearer', } try: body = parse.urlencode(d) except AttributeError: body = urllib.urlencode(d) req = urllib_request.Request(RpcHelper.TOKEN_ENDPOINT) req.add_header...
def _GetAccessToken(self)
Gets oauth2 access token for Gitkit API using service account. Returns: string, oauth2 access token.
2.697771
2.865413
0.941495
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, 'iss': self.service_account_email } return crypt.make_signed_jwt( ...
def _GenerateAssertion(self)
Generates the signed assertion that will be used in the request. Returns: string, signed Json Web Token (JWT) assertion.
4.164639
4.113086
1.012534
try: response = simplejson.loads(raw_response) if 'error' not in response: return response else: error = response['error'] if 'code' in error: code = error['code'] if str(code).startswith('4'): raise errors.GitkitClientError(error['messa...
def _CheckGitkitError(self, raw_response)
Raises error if API invocation failed. Args: raw_response: string, the http response. Raises: GitkitClientError: if the error code is 4xx. GitkitServerError: if the response if malformed. Returns: Successful response as dict.
2.624297
2.585831
1.014876
if 'user_id' in dictionary: raise errors.GitkitClientError('use localId instead') if 'localId' not in dictionary: raise errors.GitkitClientError('must specify localId') if 'email' not in dictionary: raise errors.GitkitClientError('must specify email') return cls(decode=False, **d...
def FromDictionary(cls, dictionary)
Initializes from user specified dictionary. Args: dictionary: dict of user specified attributes Returns: GitkitUser object
4.83915
3.722251
1.30006
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'] = self.photo_url if self.email_verified is not None: param['emailVerified'...
def ToRequest(self)
Converts to gitkit api request parameter dict. Returns: Dict, containing non-empty user attributes.
1.89593
1.833055
1.0343
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: parsed = crypt.verify_signed_jwt_with_certs(jwt, certs, aud) except crypt.AppIdentityEr...
def VerifyGitkitToken(self, jwt)
Verifies a Gitkit token string. Args: jwt: string, the token to be checked Returns: GitkitUser, if the token is valid. None otherwise.
5.240869
4.9078
1.067865
user = self.rpc_helper.GetAccountInfoByEmail(email) return GitkitUser.FromApiResponse(user)
def GetUserByEmail(self, email)
Gets user info by email. Args: email: string, the user email. Returns: GitkitUser, containing the user info.
17.407866
13.756399
1.265438
user = self.rpc_helper.GetAccountInfoById(local_id) return GitkitUser.FromApiResponse(user)
def GetUserById(self, local_id)
Gets user info by id. Args: local_id: string, the user id at Gitkit server. Returns: GitkitUser, containing the user info.
18.36014
11.716553
1.567026
return self.rpc_helper.UploadAccount(hash_algorithm, base64.urlsafe_b64encode(hash_key), [GitkitUser.ToRequest(i) for i in accounts])
def UploadUsers(self, hash_algorithm, hash_key, accounts)
Uploads multiple users to Gitkit server. Args: hash_algorithm: string, the hash algorithm. hash_key: array, raw key of the hash algorithm. accounts: list of GitkitUser. Returns: A dict of failed accounts. The key is the index of the 'accounts' list, starting from 0.
8.181992
5.738883
1.425712
next_page_token, accounts = self.rpc_helper.DownloadAccount( None, pagination_size) while accounts: for account in accounts: yield GitkitUser.FromApiResponse(account) next_page_token, accounts = self.rpc_helper.DownloadAccount( next_page_token, pagination_size)
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.
4.561341
4.781848
0.953887
if 'action' in param: try: if param['action'] == GitkitClient.RESET_PASSWORD_ACTION: request = self._PasswordResetRequest(param, user_ip) oob_code, oob_link = self._BuildOobLink(request, param['action']) return { ...
def GetOobResult(self, param, user_ip, gitkit_token=None)
Gets out-of-band code for ResetPassword/ChangeEmail request. Args: param: dict of HTTP POST params user_ip: string, end user's IP address gitkit_token: string, the gitkit token if user logged in Returns: A dict of { email: user email who initializes the request new_emai...
2.198876
1.868995
1.176502
code = self.rpc_helper.GetOobCode(param) if code: parsed = list(parse.urlparse(self.widget_url)) query = dict(parse.parse_qsl(parsed[4])) query.update({'mode': mode, 'oobCode': code}) try: parsed[4] = parse.urlencode(query) except AttributeError: parsed[4] = ...
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 clicks the oob url in the email. ...
4.55612
3.314046
1.374791
x = Popen(command, shell=True, stdout=PIPE, stderr=PIPE) out, err = x.communicate() out = out.decode('utf-8') err = err.decode('utf-8') return out, err
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.
1.870478
1.799914
1.039204
outstr = '' for arg in kwargs: outstr += ' -{} {}'.format(arg, kwargs[arg]) return outstr
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.
3.45914
3.025823
1.143206
with open(result_file) as handle: lines = handle.readlines() mash_results = list() for line in lines: result = MashResult(line) mash_results.append(result) return mash_results
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
2.280367
2.504582
0.910478
with open(screen_result) as handle: lines = handle.readlines() results = list() for line in lines: result = ScreenResult(line) results.append(result) return results
def read_mash_screen(screen_result)
:param screen_result: Tab-delimited result file generated by mash screen. :return: results: A list with each line in the result file as an entry, with attributes identity, shared_hashes, median_multiplicity, pvalue, and query_id
3.045001
3.215392
0.947008
p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) out, err = p.communicate() out = out.decode('utf-8') err = err.decode('utf-8') if p.returncode != 0: raise subprocess.CalledProcessError(p.returncode, cmd=cmd) return out, err
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 are the stdout and stderr fro...
1.582372
1.57197
1.006617
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))
def write_to_logfile(logfile, out, err, cmd)
Writes stdout, stderr, and a command to a logfile :param logfile: Path to file to write output to. :param out: Stdout of program called, as a string :param err: Stderr of program called, as a string :param cmd: command that was used
1.998098
2.074041
0.963384
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.isfile(name.replace(forward_id, reverse_id)): pair_list.append([name, name.replace(forward_id, reverse_id)]) return pair_list
def find_paired_reads(fastq_directory, forward_id='_R1', reverse_id='_R2')
Looks at a directory to try to find paired fastq files. Should be able to find anything fastq. :param fastq_directory: Complete path to directory containing fastq files. :param forward_id: Identifier for forward reads. Default R1. :param reverse_id: Identifier for reverse reads. Default R2. :return: Lis...
2.229499
2.492136
0.894614
read_list = list() if find_fasta is False: fastq_files = glob.glob(os.path.join(fastq_directory, '*.f*q*')) else: # Very misnamed! fastq_files = glob.glob(os.path.join(fastq_directory, '*.f*a*')) for name in sorted(fastq_files): # Iterate through files, adding them t...
def find_unpaired_reads(fastq_directory, forward_id='_R1', reverse_id='_R2', find_fasta=False)
Looks at a directory to find unpaired fastq files. :param fastq_directory: Complete path to directory containing fastq files. :param forward_id: Identifier for forward reads. Default _R1. :param reverse_id: Identifier for forward reads. Default _R2. :param find_fasta: If False, will look for fastq files...
2.363208
2.351746
1.004874
alleles = list() with open(profiles_file) as f: lines = f.readlines() for line in lines: line = line.rstrip() genus = line.split(':')[0] if genus == target_genus: alleles = line.split(':')[1].split(',')[:-1] return alleles
def find_genusspecific_allele_list(profiles_file, target_genus)
A new way of making our specific databases: Make our profiles file have lists of every gene/allele present for each genus instead of just excluding a few genes for each. This way, should have much smaller databases while managing to make ConFindr a decent bit faster (maybe) :param profiles_file: Path to pro...
2.034368
2.467949
0.824315
index = SeqIO.index(os.path.join(database_folder, 'rMLST_combined.fasta'), 'fasta') seqs = list() for s in allele_list: try: seqs.append(index[s]) except KeyError: logging.warning('Tried to add {} to allele-specific database, but could not find it.'.format(s)) ...
def setup_allelespecific_database(fasta_file, database_folder, allele_list)
Since some genera have some rMLST genes missing, or two copies of some genes, genus-specific databases are needed. This will take only the alleles known to be part of each genus and write them to a genus-specific file. :param database_folder: Path to folder where rMLST_combined is stored. :param fasta_file:...
2.910485
2.573481
1.130952
out, err, cmd = bbtools.bbduk_bait(database, pair[0], forward_out, reverse_in=pair[1], reverse_out=reverse_out, threads=str(threads), returncmd=True) if logfile: write_to_logfile(logfile, out, err, cmd)
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. :param database: Path to rMLST database, in FASTA format. :param forward_out: :param reverse_out: ...
4.887183
6.930283
0.705192
genera_present = list() out, err, cmd = mash.screen('{}/refseq.msh'.format(databases), pair[0], pair[1], threads=threads, w='', i='0.95', output_file=os.path.join(tmpdir, 'screen.tab'), returncmd=True) write_to_logfile(log, out, err, cmd) ...
def find_cross_contamination(databases, pair, tmpdir='tmp', log='log.txt', threads=1)
Usese mash to find out whether or not a sample has more than one genus present, indicating cross-contamination. :param databases: A databases folder, which must contain refseq.msh, a mash sketch that has one representative per genus from refseq. :param tmpdir: Temporary directory to store mash result files ...
2.981552
2.633607
1.132117
# make a dict by dictionary comprehension where values are True or False for each base depending on whether the count meets the threshold. # Method differs depending on whether absolute or fraction cutoff is specified if base_fraction_cutoff: total_hq_base_count = sum(high_quality_base_count.v...
def number_of_bases_above_threshold(high_quality_base_count, base_count_cutoff=2, base_fraction_cutoff=None)
Finds if a site has at least two bases of high quality, enough that it can be considered fairly safe to say that base is actually there. :param high_quality_base_count: Dictionary of count of HQ bases at a position where key is base and values is the count of that base. :param base_count_cutoff: Number of ...
3.72244
3.779647
0.984865
# Sometimes the qualities come out to ridiculously high (>70) values. Looks to be because sometimes reads # are overlapping and the qualities get summed for overlapping bases. Issue opened on pysam. unfiltered_base_qualities = dict() for read in column.pileups: if read.query_position is not...
def find_if_multibase(column, quality_cutoff, base_cutoff, base_fraction_cutoff)
Finds if a position in a pileup has more than one base present. :param column: A pileupColumn generated by pysam :param quality_cutoff: Desired minimum phred quality for a base in order to be counted towards a multi-allelic column :param base_cutoff: Minimum number of bases needed to support presence of a b...
3.981354
3.880124
1.026089
contig_names = list() for contig in SeqIO.parse(fasta_file, 'fasta'): contig_names.append(contig.id) return contig_names
def get_contig_names(fasta_file)
Gets contig names from a fasta file using SeqIO. :param fasta_file: Full path to uncompressed, fasta-formatted file :return: List of contig names.
1.821093
2.187985
0.832315
bamfile = pysam.AlignmentFile(bamfile_name, 'rb') multibase_position_dict = dict() to_write = list() # These parameters seem to be fairly undocumented with pysam, but I think that they should make the output # that I'm getting to match up with what I'm seeing in Tablet. for column in bamfil...
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. Must be sorted/indexed :param reference_fasta: Full path to fasta file that was used to generate the bamfile. :param report_fil...
3.094528
3.130913
0.988379
genes_to_use = dict() score_dict = dict() gene_alleles = list() with open(kma_report) as tsvfile: reader = csv.DictReader(tsvfile, delimiter='\t') for row in reader: gene_allele = row['#Template'] score = int(row['Score']) gene = gene_allele.split...
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 format gene_allele
1.905105
1.776316
1.072504
outstr = '' # First, sort base_dict so that major allele always comes first - makes output report nicer to look at. base_list = sorted(base_dict.items(), key=lambda kv: kv[1], reverse=True) for base in base_list: outstr += '{}:{};'.format(base[0], base[1]) return outstr[:-1]
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.
4.557591
4.47041
1.019502
total_length = 0 for sequence in SeqIO.parse(fasta_file, 'fasta'): total_length += len(sequence.seq) return total_length
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.
1.950198
2.303692
0.846553
contam_levels = list() with open(contamination_report_file) as csvfile: reader = csv.DictReader(csvfile) for row in reader: lowest_count = 99999 base_counts = row['Bases'].split(';') for count in base_counts: num_bases = int(count.split(':...
def estimate_percent_contamination(contamination_report_file)
Estimates the percent contamination of a sample (and standard deviation). :param contamination_report_file: File created by read_contig, :return: Estimated percent contamination and standard deviation.
2.362145
2.47243
0.955394
# If the report file hasn't been created, make it, with appropriate header. if not os.path.isfile(output_report): with open(os.path.join(output_report), 'w') as f: f.write('Sample,Genus,NumContamSNVs,ContamStatus,PercentContam,PercentContamStandardDeviation,BasesExamined,DatabaseDownloa...
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 creates the file if it doesn't already exist. :param output_report: Path to CSV output report file. Should have headers SampleName,Genus,NumContamSNVs, ContamStatus,PercentContam, and PercentCon...
2.407712
2.050915
1.17397
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 (kilobytes), M (megabytes), or G (gigabytes). Your specified ' 'suffix was {...
def check_acceptable_xmx(xmx_string)
BBTools can have their memory set manually. This will check that the memory setting is actually valid :param xmx_string: The users requested XMX, as a string. :return: True if the Xmx string will be accepted by BBTools, otherwise false.
2.834317
2.809411
1.008865
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'): regex = '[ ]{' + str(15 - len(char_set)) + '}' + char_set if char_sets is None: ...
def char_code(columns, name=None)
Character set code field. :param name: name for the field :return: an instance of the Character set code field rules
3.64853
3.644004
1.001242
def normalize_all(_choices): # normalize all the keys for easier comparison if normalizer: _choices = [(normalizer(key), value) for key, value in choices] return _choices choices = normalize_all(choices) def choice_validator(value): if normalizer: ...
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 user input (the key); the second being the value associated with the key. The callable by default will match, upon complete match the first ...
2.806933
2.864162
0.980019
def write_choices(choice_keys, default_key): _stdout.write('(') _stdout.write('/'.join(choice_keys)) _stdout.write(') ') if default_key is not NotImplemented: _stdout.write('[') _stdout.write(choice_keys[default_key]) _stdout.write('] ') ...
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 once. validator Defaults to None. Must be a callable that takes in a value. The callable should raise ValueError when the value leads to an error,...
2.856153
2.810258
1.016331
# generate compacted ndiff output. diff = '\n'.join(l for l in ( line.rstrip() for line in difflib.ndiff( json_dumps(original).splitlines(), json_dumps(new).splitlines(), )) if l[:1] in '?+-' or l[-1:] in '{}' or l[-2:] == '},') basename_target = basenam...
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. Optionally, a custom json.dumps method can also be passed in for output generation.
4.973985
5.158672
0.964199
basedir = join(working_dir, 'node_modules', package_name) package_json = join(basedir, 'package.json') if not exists(package_json): logger.debug( "could not locate package.json for the npm package '%s' in the " "current working directory '%s'; the package may have been ...
def locate_package_entry_file(working_dir, package_name)
Locate a single npm package to return its browser or main entry.
3.335063
3.276624
1.017835
pictures = Image.objects.filter( folder__id__in=Gallery.objects.filter(is_published=True).values_list( 'folder__pk', flat=True)) if selection == 'recent': context.update({ 'pictures': pictures.order_by('-uploaded_at')[:amount] }) elif selection == 'random...
def render_pictures(context, selection='recent', amount=3)
Template tag to render a list of pictures.
2.42444
2.460106
0.985502
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
def add_header(self, entry)
Parses the VCF Header field and returns the number of samples in the VCF file
5.202858
4.150624
1.253512
var_call = VCFEntry(self.individuals) var_call.parse_entry(row) return var_call
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.)
8.465296
4.61871
1.832827
var_call = VCFEntry(self.individuals) var_call.parse_entry( row ) self.entries[(var_call.chrom, var_call.pos)] = var_call return var_call
def add_entry(self, row)
This will parse the VCF entry and also store it within the VCFFile. It will also return the VCFEntry as well.
6.14698
3.766228
1.632132
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},Description={3}>'.format(key, val.get('num_entries','.'), type_map.get(val.get('type', '')), v...
def get_header(self, individual=-1)
Returns the vcf header
1.951182
1.855491
1.051572
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[value] = {} id_ = value elif key == 'Number': ...
def add_info(self, entry)
Parse and store the info field
3.016103
2.938324
1.02647
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': self.filter[value] = {} id_ = value elif key == 'Description': ...
def add_filter(self, entry)
Parse and store the filter field
3.585775
3.388273
1.05829
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] = {} id_ = value elif key == 'Description': ...
def add_alt(self, entry)
Parse and store the alternative allele field
3.346178
3.004338
1.113782
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)])
def sample_string(self, individual=-1)
Returns the VCF entry as it appears in the vcf file
4.625308
4.22192
1.095546
if isinstance(individual, str): individual = self.individuals[individual] extra = OrderedDict() for format_ in self.format: index = getattr(self, format_) if index != -1: if format_ == 'GT': d = self.genotype ...
def get_sample_info(self, individual=-1)
Returns the sample info of a given sample or all by default
2.812835
2.759578
1.019299
if individual is not None: if isinstance(individual, str): individual = self.individuals[individual] alts = self.genotype[individual] return [sum(alts) == len(alts)] if sum(alts) > 0 else [False] else: return [sum(alts) == len(alts...
def is_homozygous(self, individual=None)
This will give a boolean list corresponding to whether each individual is homozygous for the alternative allele.
2.688237
2.332683
1.152423
#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): individual = self.individuals[individual] if nucleotides_only: return [self.alt[i-1].replace('.', '') ...
def get_alt(self, individual=0, nucleotides_only=True)
Returns the alternative alleles of the individual as a list
5.312167
5.214197
1.018789
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('<')]
def get_alt_length(self, individual=0)
Returns the number of basepairs of each alternative allele
4.865887
4.160885
1.169436
#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: out.append(None) else: ...
def get_alt_lengths(self)
Returns the longest length of the variant. For deletions, return is negative, SNPs return 0, and insertions are +. None return corresponds to no variant in interval for specified individual
6.653398
5.926472
1.122658
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 i in alts] return [False]
def has_snp(self, individual=0)
Returns a boolean list of SNP status, ordered by samples
3.561876
3.309306
1.076321
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_ == 'PASS' or filter_ == '.': self.passed = True else: ...
def parse_entry(self, entry)
This parses a VCF row and stores the relevant information
2.3206
2.199519
1.055049
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
def add_child(self, child)
Children are GFFFeatures and are defined when added. This is done to avoid memory overheads that may be incurred by GFF files that have millions of rows.
2.244866
2.105551
1.066166
if hasattr(obj, 'isoformat'): result = obj.isoformat() else: raise TypeError("Unserializable object {} of type {}".format(obj, type(obj))) return result
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: object to transform into it's ISO fo...
3.176986
3.951951
0.803903
result = '' for field_encoder in field_encoders: try: result += field_encoder.encode(entity_dict) except KeyError as e: return False return result
def try_encode(field_encoders, entity_dict)
Inner encoding and try return string from entity dictionary :param field_encoders: :param entity_dict: :return:
3.033254
2.941608
1.031155
possible_results = [] entity_dict = self.get_entity_dict(entity) record_field_encoders = self.get_record_fields_encoders() for field_encoders in record_field_encoders: result = self.try_encode(field_encoders, entity_dict) if result: possib...
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:
4.385924
3.716777
1.180034
if self.__argparser is None: self.__argparser = self.argparser_factory() self.init_argparser(self.__argparser) return self.__argparser
def argparser(self)
For setting up the argparser for this instance.
3.277791
2.821702
1.161636
return ArgumentParser( prog=self.prog, description=self.__doc__, add_help=False, )
def argparser_factory(self)
Produces argparser for this type of Runtime.
5.693535
4.37515
1.301335
# loop variants kwargs = vars(parsed) failed = list(extras) # initial values runtime, subparser, idx = (self, self.argparser, 0) # recursion not actually needed when it can be flattened. while isinstance(runtime, Runtime): cmd = kwargs.pop(ru...
def unrecognized_arguments_error(self, args, parsed, extras)
This exists because argparser is dumb and naive and doesn't fail unrecognized arguments early.
10.595418
10.443641
1.014533
warnings.warn( 'Runtime.error is deprecated and will be removed by calmjs-4.0.0', DeprecationWarning) details = self.get_argparser_details(argparser) argparser = details.subparsers[target] if details else self.argparser argparser.error(message)
def error(self, argparser, target, message)
This was used as part of the original non-recursive lookup for the target parser.
6.891803
6.465627
1.065914
argparser.add_argument( '-w', '--overwrite', dest=EXPORT_TARGET_OVERWRITE, action='store_true', help='overwrite the export target without any confirmation', ) argparser.add_argument( '--export-target', dest=EXPORT_TARGET, met...
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 its super. It should not reimplement this completely. Example: def init_argparser_export_target(self, argparser): super(MyToolchainRuntime, self).init_argparser_export_target( ...
2.887856
3.51896
0.820656
cwd = self.toolchain.join_cwd() argparser.add_argument( '--working-dir', dest=WORKING_DIR, metavar=metavar(WORKING_DIR), default=cwd, help=help_template % {'explanation': explanation, 'cwd': cwd}, )
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 this is used. Arguments explanation Explanation text for the default help template help_template A standard help message for this option.
3.17429
4.351668
0.729442
argparser.add_argument( '--build-dir', default=None, dest=BUILD_DIR, metavar=metavar(BUILD_DIR), help=help, )
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...
For setting up build directory
3.267341
3.977222
0.821513
argparser.add_argument( '--optional-advice', default=default, required=False, dest=ADVICE_PACKAGES, action=StoreRequirementList, metavar='<advice>[,<advice>[...]]', help=help )
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 appropriate entry points for setting up the advices for ' ...
For setting up optional advice.
4.347147
4.654936
0.933879
super(ToolchainRuntime, self).init_argparser(argparser) # it is possible for subclasses to fully override this, but if # they are using this as the runtime to drive the toolchain they # should be prepared to follow the layout, but if they omit them # it should only res...
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.
7.951165
7.890351
1.007707
self.prepare_spec_debug_flag(spec, **kwargs) self.prepare_spec_export_target_checks(spec, **kwargs) # defer the setup till the actual toolchain invocation spec.advise(SETUP, self.prepare_spec_advice_packages, spec, **kwargs)
def prepare_spec(self, spec, **kwargs)
Prepare a spec for usage with the generic ToolchainRuntime. Subclasses should avoid overriding this; override create_spec instead.
14.057729
13.119579
1.071508
spec = self.create_spec(**kwargs) self.prepare_spec(spec, **kwargs) return spec
def kwargs_to_spec(self, **kwargs)
Turn the provided kwargs into arguments ready for toolchain.
4.586042
4.497776
1.019625
argparser.add_argument( 'package_names', metavar=metavar('package'), nargs='+', help=help)
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'))
Default helper for setting up the package_names option. This is separate so that subclasses are not assumed for the purposes of artifact creation; they should consider modifying the default help message to reflect the fact.
4.042058
4.835752
0.83587
argparser.add_argument( '--source-registry', default=default, dest=CALMJS_MODULE_REGISTRY_NAMES, action=StoreDelimitedList, metavar='<registry>[,<registry>[...]]', help=help, ) argparser.add_argument( '--source-registries', d...
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.
3.562135
3.688981
0.965615
argparser.add_argument( '--loaderplugin-registry', default=default, dest=CALMJS_LOADERPLUGIN_REGISTRY_NAME, action='store', metavar=metavar('registry'), help=help, )
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' ))
Default helper for setting up the loaderplugin registries flags. Note that this is NOT part of the init_argparser due to implementation specific requirements. Subclasses should consider modifying the default value help message to cater to the toolchain it encapsulates.
4.337629
4.847143
0.894884
super(SourcePackageToolchainRuntime, self).init_argparser(argparser) self.init_argparser_source_registry(argparser) self.init_argparser_package_names(argparser)
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.
5.595142
6.134391
0.912094
super(PackageManagerRuntime, self).init_argparser(argparser) # Ideally, we could use more subparsers for each action (i.e. # init and install). However, this is complicated by the fact # that setuptools has its own calling conventions through the # setup.py file, and ...
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.
7.641505
7.68043
0.994932
if name is None: name = 'Alphanumeric Field' if columns < 0: # Can't be empty or have negative size raise BaseException() if isLast: columns = str('1,' + str(columns)) # Checks if non-ASCII characters are allowed if not extended: # The regular express...
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-ASCII characters are allowed, but the no ASCII lowercase constraint is k...
4.663201
4.218697
1.105365
string = string.strip() if len(string) == 0: message = 'The string should not be empty' raise pp.ParseException(message)
def _check_not_empty(string)
Checks that the string is not empty. If it is empty an exception is raised, stopping the validation. This is used for compulsory alphanumeric fields. :param string: the field value
4.491095
6.784891
0.661926
if name is None: name = 'Numeric Field' if columns <= 0: # Can't be empty or have negative size raise BaseException() # Only numbers are accepted field = pp.Regex('[0-9]{' + str(columns) + '}') # Parse action field.setParseAction(_to_int) field.leaveWhitespac...
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 field
7.421141
6.68997
1.109294
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: # Integer columns can't have negative size raise BaseException('Number of integer value...
def numeric_float(columns, nums_int, name=None)
Creates the grammar for a Numeric (N) field, accepting only the specified number of characters. This version only allows floats. As nothing in the string itself indicates how many of the characters are for the integer and the decimal sections, this should be specified with the nums_int parameter. ...
4.732123
4.674333
1.012363
index_end = len(number) - nums_int return float(number[:nums_int] + '.' + number[-index_end:])
def _to_numeric_float(number, nums_int)
Transforms a string into a float. The nums_int parameter indicates the number of characters, starting from the left, to be used for the integer value. All the remaining ones will be used for the decimal value. :param number: string with the number :param nums_int: characters, counting from the lef...
5.715032
5.824013
0.981288
value = float(string) if value < minimum: message = 'The Numeric Field value should be above %s' % minimum raise pp.ParseException(message)
def _check_above_value_float(string, minimum)
Checks that the number parsed from the string is above a minimum. This is used on compulsory numeric fields. If the value is not above the minimum an exception is thrown. :param string: the field value :param minimum: minimum value
7.028214
9.33409
0.752962
if name is None: name = 'Boolean Field' # Basic field field = pp.Regex('[YN]') # Parse action field.setParseAction(lambda b: _to_boolean(b[0])) # Name field.setName(name) return field
def boolean(name=None)
Creates the grammar for a Boolean (B) field, accepting only 'Y' or 'N' :param name: name for the field :return: grammar for the flag field
7.537462
6.695527
1.125746
if string == 'Y': result = True elif string == 'N': result = False else: raise pp.ParseException(string, msg='Is not a valid boolean value') return result
def _to_boolean(string)
Transforms a string into a boolean value. If a value which is not 'Y' or 'N' is received, a ParseException is thrown. :param: string: the string to transform :return: True if the string is 'Y', False if it is 'N'
4.637892
3.861394
1.201093
if name is None: name = 'Flag Field' # Basic field field = pp.Regex('[YNU]') # Name field.setName(name) field.leaveWhitespace() return field
def flag(name=None)
Creates the grammar for a Flag (F) field, accepting only 'Y', 'N' or 'U'. :param name: name for the field :return: grammar for the flag field
14.02709
8.660408
1.61968
if name is None: name = 'Date Field' # Basic field # This regex allows values from 00000101 to 99991231 field = pp.Regex('[0-9][0-9][0-9][0-9](0[1-9]|1[0-2])' '(0[1-9]|[1-2][0-9]|3[0-1])') # Parse action field.setParseAction(lambda d: datetime.datetime.strpti...
def date(name=None)
Creates the grammar for a Date (D) field, accepting only numbers in a certain pattern. :param name: name for the field :return: grammar for the date field
3.953702
3.749335
1.054508