content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
def decorator_with_args(decorator_to_enhance): """ This is decorator for decorator. It allows any decorator to get additional arguments """ def decorator_maker(*args, **kwargs): def decorator_wrapper(func): return decorator_to_enhance(func, *args, **kwargs) return decorator_wrapper return decorator_maker
1af073daf9e9ac9a8834f3a1484bdfa293b1b2bb
7,951
def generate_intervals(nelements): """ Generates all possible permutations of lists that access elements from boths ends of a list without accessing the middle, and one permutation that accesses ALL elements of a list. """ intervals = list() for i in range(0, nelements): interval = list() if i <= int(nelements / 2): for j in range(0, i): interval.append(j) if i == int(nelements / 2) and (nelements % 2) == 1: interval.append(int(nelements / 2)) for j in range(i - 1, -1, -1): interval.append(-1 * (j + 1)) if interval: intervals.append(interval) return intervals
06098fbff3342c369b7334e4447cdf9b3ef1a0ab
7,952
import re def find_subtype(meta_dict): """Find subtype from dictionary of sequence metadata. Args: `meta_dict` (dict) dictionary of metadata downloaded from genbank Returns: `subtype` (str) RSV subtype as one letter string, 'A' or 'B'. """ subtype = '' if ' A' in meta_dict['organism']: subtype = 'A' elif ' B' in meta_dict['organism']: subtype = 'B' elif subtype == '': for val in meta_dict.values(): if re.search(r'RSV\s?A\b', val) or \ re.search(r'type: A\b', val) or \ re.search(r'group: A\b', val) or re.search(r'\bA\b', val): subtype = 'A' elif re.search(r'RSV\s?B\b', val) or \ re.search(r'type: B\b', val) or \ re.search(r'group: B\b', val) or re.search(r'\bB\b', val): subtype = 'B' return subtype
130b8ed61f117a786cf5f5ae49fc75e8b074ef2e
7,953
def extract_gff3_fields(primer_info): """ The gff3 file is a format to annotate locations on a genome. The gff3 annotations requires locations on the genome, this was not required for creating the primers. This function computes these locations and prepares the data for the gff3 file :param primer_info: the sequence and target used for creating primers :return: lines to be writen in gff3 file """ gff3_objects = [] gt_seq_region = primer_info['ref']+'_'+str(primer_info['forward_start'])+'-'+str(primer_info['reverse_stop']) SNP_name = primer_info['ref'] + '_' + str(primer_info['pos']) # creating the parent gff3_objects.append({ 'seqid' : primer_info['ref'], 'source' : "Primer3", 'type' : "region", 'start': str(primer_info['forward_start']), 'end' : str(primer_info['reverse_stop']), 'score' : '.', 'strand' : '+', 'phase' : '.', # used for coding DNA sequence (CDS) 'attributes' : { 'ID' : gt_seq_region, 'Name' : primer_info['ref']+'_'+str(primer_info['pos']), 'Parent' : primer_info['parent'], 'Note' : "GT-seq target region" } }) gff3_objects.append({ 'seqid' : primer_info['ref'], 'source' : "Primer3", 'type' : "PCR_product", 'start': str(primer_info['forward_start']), 'end' : str(primer_info['reverse_stop']), 'score' : '.', 'strand' : '+', 'phase' : '.', # used for coding DNA sequence (CDS) 'attributes' : { 'ID' : gt_seq_region + "_pcr", 'Name' : SNP_name + " PCR product", 'Parent' : gt_seq_region, 'Note' : "GT-seq primer product" } }) #forward primer gff3_objects.append({ 'seqid': primer_info['ref'], 'source': "Primer3", 'type': "forward_primer", 'start': str(primer_info['forward_start']), 'end': str(primer_info['forward_stop']), 'score': '.', 'strand': '+', 'phase': '.', # used for coding DNA sequence (CDS) 'attributes': { 'ID': gt_seq_region + "_FW", 'Name': SNP_name+"_FW", 'Parent': gt_seq_region } }) #reverse primer gff3_objects.append({ 'seqid': primer_info['ref'], 'source': "Primer3", 'type': "reverse_primer", 'start': str(primer_info['reverse_start']), 'end': str(primer_info['reverse_stop']), 'score': '.', 'strand': '-', 'phase': '.', # used for coding DNA sequence (CDS) 'attributes': { 'ID': gt_seq_region + "_RV", 'Name': SNP_name+"_RV", 'Parent': gt_seq_region } }) return gff3_objects
4e8f0fbfc3bff136b3c03d4a2c35648491d42fba
7,954
from typing import Sequence from typing import Type from typing import Union def unique_fast( seq: Sequence, *, ret_type: Type[Union[list, tuple]] = list ) -> Sequence: """Fastest order-preserving method for (hashable) uniques in Python >= 3.6. Notes ----- Values of seq must be hashable! See Also -------- `Uniquify List in Python 3.6 <https://www.peterbe.com/plog/fastest-way-to-uniquify-a-list-in-python-3.6>`_ """ return ret_type(dict.fromkeys(seq))
c41c6b298e52bd3069414206cf9ada4766ea8f4d
7,955
def intersect(s1, s2): """ Returns the intersection of two slices (which must have the same step). Parameters ---------- s1, s2 : slice The slices to intersect. Returns ------- slice """ assert (s1.step is None and s2.step is None) or s1.step == s2.step, \ "Only implemented for same-step slices" if s1.start is None: start = s2.start elif s2.start is None: start = s1.start else: start = max(s1.start, s2.start) if s1.stop is None: stop = s2.stop elif s2.stop is None: stop = s1.stop else: stop = min(s1.stop, s2.stop) if stop is not None and start is not None and stop < start: stop = start return slice(start, stop, s1.step)
13841ceddd3bb5c73a29bd4067a751579bc04e9b
7,958
def is_word_guessed(word, guesses): """ This function will check if the user has guessed all of the letters in the word. """ # Loop through the word. for letter in word: # Check if the letter has been guessed. if letter not in guesses: # The user has not guessed the letter. return False # The user has guessed all of the letters. return True
7ab3ad07a5588745dc4a9f01dac89c788cc688f5
7,959
def fitness_function(solution, answer): """fitness_function(solution, answer) Returns a fitness score of a solution compaired to the desired answer. This score is the absolute 'ascii' distance between characters.""" score =0 for i in range(len(answer)): score += (abs(solution[i]-answer[i])) return score
059924beb07d0e0e1892783f515061ffcf714d43
7,962
def adjust_cruise_no(cruise): """If shipc should be mapped we map cruise_no as well.""" if len(cruise) > 7: return '_'.join((cruise[:4], cruise[4:8], cruise[8:])) else: return cruise
a83a35cb0a1bad17778f3b39756c431237254a51
7,963
import argparse def parse_args(): """Parse command line arguments. """ arg_parser = argparse.ArgumentParser( formatter_class=argparse.ArgumentDefaultsHelpFormatter) arg_parser.add_argument('-hca', '--http_cert', default=None, help='The ca cert of external HTTP Server') arg_parser.add_argument('-ca', '--ca_cert', default=None, help='The ca cert required for etcd') arg_parser.add_argument('-c', '--cert', default=None, help='The cert required for etcd') arg_parser.add_argument('-k', '--key', default=None, help='The key cert required for etcd') arg_parser.add_argument('-host','--hostname', default='localhost', help='Etcd host IP') arg_parser.add_argument('-port','--port', default='2379', help='Etcd host port') return arg_parser.parse_args()
f2edbc2dbbfdb438198e6f6bb8edba6400982ef0
7,964
def signature(word: str) -> str: """Return a word sorted >>> signature("test") 'estt' >>> signature("this is a test") ' aehiisssttt' >>> signature("finaltest") 'aefilnstt' """ return "".join(sorted(word))
a17e006dcd9f55cfc57d7cd0140489c7be518dc7
7,965
def getHeaders(lst, filterOne, filterTwo): """ Find indexes of desired values. Gets a list and finds index for values which exist either in filter one or filter two. Parameters: lst (list): Main list which includes the values. filterOne (list): A list containing values to find indexes of in the main list. filterTwo (list): A list to check by for the same index of a value from filterOne if it does not exist in the main list. Returns: (list): A list containing indexes of values either from filterOne or filterTwo. """ headers = [] for i in range(len(filterOne)): if filterOne[i] in lst: headers.append(lst.index(filterOne[i])) else: headers.append(lst.index(filterTwo[i])) return headers
0aa3612b15114b0e0dcdf55eb3643df58157239b
7,966
from typing import Callable from typing import Any from typing import Tuple import inspect def combine_args_kwargs( func: Callable[..., Any], *args: Any, **kwargs: Any ) -> Tuple[Any, ...]: """ Combine args and kwargs into args. This is needed because we allow users to pass custom kwargs to adapters, but when creating the virtual table we serialize only args. """ signature = inspect.signature(func) bound_args = signature.bind(*args, **kwargs) bound_args.apply_defaults() return bound_args.args
03e5c310462b3d15e3ab69cf6d8717744a95caa4
7,967
def definers (ioc, name) : """Return the classes defining `name` in `mro` of `ioc`""" try : mro = ioc.__mro__ except AttributeError : mro = ioc.__class__.__mro__ def _gen (mro, name) : for c in mro : v = c.__dict__.get (name) if v is not None : yield c, v return tuple (_gen (mro, name))
f5d90118ca1ad719d47143d0260bfcbda2749124
7,969
def add_dest(df_conc, dest_labware, dest_start=1): """Setting destination locations for samples & primers. Adding to df_conc: [dest_labware, dest_location] """ dest_start= int(dest_start) #try: # dest_labware = dest_labware_index[dest_type] #except KeyError: # raise KeyError('Destination labware type not recognized') # adding columns df_conc['dest_labware'] = dest_labware dest_end = dest_start + df_conc.shape[0] df_conc['dest_location'] = list(range(dest_start, dest_end)) # return return df_conc
d3e066148fc07bd5ed47d496d56c39e24062315c
7,970
def top(Q): """Inspects the top of the queue""" if Q: return Q[0] raise ValueError('PLF ERROR: empty queue')
16327db2698fbef4cad1da2c9cb34b71158a2a6c
7,972
def get_valid_handles_domain_only(): """ Define valid domain handles """ return ["cli", "web", "gui", "pub"]
64dc04fbbecbc442b1fd99279161c04461332a87
7,973
def qc_board_and_constraints(board, constraints): """ Purpose: When the board first comes in, do a check to see if any of the fixed values are duplicates @param board The Sudoku board: A list of lists of variable class instances @param constraints The unallowed values for each cell, list of tuples """ i = 0 while i < len(constraints): ([irow, icol], [jrow, jcol]) = constraints[i] xi = board[irow][icol] xj = board[jrow][jcol] if xi.fixed and xj.fixed and xi.get_only_value() == xj.get_only_value(): return constraints, False if xi.fixed: # Remove this constraint; don't update i constraints.pop(i) elif not xi.fixed: # update i i += 1 return constraints, True
82c8013c12eda3fd548295be96e713d760587985
7,974
def spdot(A, x): """ Dot product of sparse matrix A and dense matrix x (Ax = b) """ return A.dot(x)
b44c9434a42974be54e2c4794b6f063f86836707
7,975
def translate_user(user): """ translates trac user to pivotal user """ return user
69a439a12188239a557b69fa9f858473f1509a26
7,976
import os def get_target_imagepath(image_path,category_num): """ category: 0-userid, 1-isbad, 2-gender: 1 male,0 female, 3-age """ basename=os.path.basename(image_path).split(".")[0].split("_") an=int(basename[category_num]) return an
131466cea39de6bc1e68b8603c2b065981d3d386
7,977
def make_snippet(snippets, location): """Makes a colored html snippet.""" output = "<br>".join(sentence.replace( location, f'<i style="background-color: yellow;">{location}</i>') for sentence in snippets) return output
57bebb05df3ae34b45f57e589f6b105425609b8c
7,981
def kid_2(): """Return a second JWT key ID to use for tests.""" return "test-keypair-2"
c1bbe824ee90470c17ac62cbc3096cff4e3ddb1a
7,982
def move_items_back(garbages): """ Moves the items/garbage backwards according to the speed the background is moving. Args: garbages(list): A list containing the garbage rects Returns: garbages(list): A list containing the garbage rects """ for garbage_rect in garbages: # Loops through the garbages garbage_rect.centerx -= 2 # Decrease the centerx coordinate by 2 return garbages
9ffd28c7503d0216b67419009dac6ff432f3b100
7,984
import re def _mask_pattern(dirty: str): """ Masks out known sensitive data from string. Parameters ---------- dirty : str Input that may contain sensitive information. Returns ------- str Output with any known sensitive information masked out. """ # DB credentials as found in called processes. call_proc_db_creds = re.compile(r"--(user|password)=[^', ]+([', ])") clean = call_proc_db_creds.sub(r"--\1=*****\2", dirty) return clean
b75ae1e6ea128628dd9b11fadb38e4cbcfe59775
7,985
def contains_non_ascii_unicode(s): """Determine whether the Unicode string 's' contains non-ASCII code-points.""" # Surely there must be a better way to do this? There's nothing I can see in # the stdlib 'unicodedata' module: # http://docs.python.org/library/unicodedata.html # # Note that list comprehensions are faster than 'map' invocations, when # the 'map' invocation would involve a lambda: # http://stackoverflow.com/questions/1247486/python-list-comprehension-vs-map # # A generator expression will be more memory-efficient than a list comp: # http://www.python.org/dev/peps/pep-0289/ # # I assume the use of 'any' (a built-in "in C" function) will be very fast # in terms of iteration and minimal in memory usage; hopefully it will also # short-circuit the evaluation of the generator expr, so only as many # iterations of the generator expr will be performed as are necessary to find # the first non-ASCII code point. #return any(((ord(c) > 127) for c in s)) # Update: According to Stack Overflow, # http://stackoverflow.com/questions/196345/how-to-check-if-a-string-in-python-is-in-ascii # the above approach is inefficient and unPythonic. # Instead... try: s.decode('ascii') except UnicodeEncodeError: return True else: return False
138d3c298598603f2d0dc24518bbea46a4f8b7e6
7,988
def __remove_duplicate_chars(string_input, string_replace): """ Remove duplicate chars from a string. """ while (string_replace * 2) in string_input: string_input = \ string_input.replace((string_replace * 2), string_replace) return string_input
6302bf225fcd5cde822e0640eb7b2c44dcc93fc8
7,989
import os import re def generate_message(username, pr_list): """Generates message using the template provided in PENDING_REVIEW_NOTIFICATION_TEMPLATE.md file. """ template_path = '.github/PENDING_REVIEW_NOTIFICATION_TEMPLATE.md' if not os.path.exists(template_path): raise Exception( 'Please add a template on path: {0}'.format(template_path)) message = '' with open(template_path, 'r') as file: message = file.read() message = re.sub(r'\{\{ *username *\}\}', '@' + username, message) message = re.sub(r'\{\{ *pr_list *\}\}', pr_list, message) return message
df5538f5d0e47415019977a234f85bedb14bc2c9
7,990
def clean_data(df): """Split the categories column to 36 individual columns and convert their values to 0 / 1. Drop the original categories column. Drop duplicated rows. Args: df: the dataset Returns: DataFrame: the cleaned dataset """ # split categories into separate category columns categories = df['categories'].str.split(';', expand=True) row = categories.iloc[0] category_colnames = row.apply(lambda x: x[:-2]) categories.columns = category_colnames # convert category values to 0 and 1 for column in categories: categories[column] = categories[column].str.split('-', expand=True)[1] categories[column] = categories[column].astype(int) # replace categories column in df with new category columns df = df.drop(columns='categories') df = df.merge(categories, how='outer', left_index=True, right_index=True) # drop duplicates df = df.drop_duplicates() return df
eeeed21b10419f2c3402abecc0710556db979c6c
7,991
def format_birthday_for_database(p_birthday_of_contact_month, p_birthday_of_contact_day, p_birthday_of_contact_year): """Takes an input of contact's birthday month, day, and year and creates a string to insert into the contacts database.""" formated_birthday_string = p_birthday_of_contact_month + "/" + p_birthday_of_contact_day + "/" + p_birthday_of_contact_year return formated_birthday_string
1b4eff67a4073505f9f693f63db6f7c32646bd53
7,992
import math def normal_distribution(x: float) -> float: """ 標準正規分布 f(x) = (1/sqrt(2pi))exp(-x^2/2) """ # 係数 coefficient = 1 / math.sqrt(2 * math.pi) # 指数 exponent = math.exp(-(x ** 2) / 2) # 標準正規分布 return coefficient * exponent
2ee740674ddf2a7b95d507aedf1f5453a75f31f1
7,993
def ceil(number) -> int: """ >>> import math >>> numbers = [-3.14, 3.14, -3, 3, 0, 0.0, -0.0, -1234.567, 1234.567] >>> all(math.ceil(num) == ceil(num) for num in numbers) True """ return int(number) if number - int(number) <= 0 else int(number) + 1
20c3f5cf56cd149e00a76e368729a76012b24375
7,994
def str_format(s, *args, **kwargs): """Return a formatted version of S, using substitutions from args and kwargs. (Roughly matches the functionality of str.format but ensures compatibility with Python 2.5) """ args = list(args) x = 0 while x < len(s): # Skip non-start token characters if s[x] != '{': x += 1 continue end_pos = s.find('}', x) # If end character can't be found, move to next character if end_pos == -1: x += 1 continue name = s[x + 1:end_pos] # Ensure token name is alpha numeric if not name.isalnum(): x += 1 continue # Try find value for token value = args.pop(0) if args else kwargs.get(name) if value: value = str(value) # Replace token with value s = s[:x] + value + s[end_pos + 1:] # Update current position x = x + len(value) - 1 x += 1 return s
addf11c8390c52da7b0f2886d2298bab66a50e49
7,996
def __private_function_example(): """This is a private function example, which is indicated by the leading under scores. :return: tmp_bool""" tmp_bool = True return tmp_bool
be8d0309dc3a52d4f128e2e113046c1c79efe457
7,997
from typing import Iterable def any_true(iterable) -> bool: """Recursive version of the all() function""" for element in iterable: if isinstance(element, Iterable): if not any_true(element): return True elif element: return True return False
67b4ea1e3c9da9c92a2ed8a26f346d67825e62fd
7,998
import math import numpy def getMatrix3(eulerdata, inplane=False): """ math from http://mathworld.wolfram.com/EulerAngles.html EMAN conventions - could use more testing tested by independently rotating object with EMAN eulers and with the matrix that results from this function """ #theta is a rotation about the x-axis, i.e. latitude # 0 <= theta <= 180 degrees the = eulerdata['euler1']*math.pi/180.0 #eman alt, altitude #phi is a rotation in the xy-plane, i.e. longitude # 0 <= phi <= 360 degrees phi = eulerdata['euler2']*math.pi/180.0 #eman az, azimuthal if inplane is True: psi = eulerdata['euler3']*math.pi/180.0 #eman phi, inplane_rotation else: psi = 0.0 if 'mirror' in eulerdata and eulerdata['mirror'] == 1: """ using mirror function see: http://blake.bcm.tmc.edu/emanwiki/EMAN2/Symmetry for documentation """ #theta flips to the back the = math.pi - the #phi is rotated 180 degrees phi += math.pi #this works without in_plane if inplane is False: #psi is rotated 180 degrees psi += math.pi m = numpy.zeros((3,3), dtype=numpy.float32) m[0,0] = math.cos(psi)*math.cos(phi) - math.cos(the)*math.sin(phi)*math.sin(psi) m[0,1] = math.cos(psi)*math.sin(phi) + math.cos(the)*math.cos(phi)*math.sin(psi) m[0,2] = math.sin(psi)*math.sin(the) m[1,0] = -math.sin(psi)*math.cos(phi) - math.cos(the)*math.sin(phi)*math.cos(psi) m[1,1] = -math.sin(psi)*math.sin(phi) + math.cos(the)*math.cos(phi)*math.cos(psi) m[1,2] = math.cos(psi)*math.sin(the) m[2,0] = math.sin(the)*math.sin(phi) m[2,1] = -math.sin(the)*math.cos(phi) m[2,2] = math.cos(the) return m
365b158cd6d5f3150c725a6f8df0d14160168dae
8,000
import json def unknown_method_request(): """Sample unknwon/invalid method request for testing purposes.""" return json.dumps( { "method": "some_random_method", "params": {}, } )
50fcfda030df632a0d1275bcb55c58e2f80e8c6b
8,003
def pcy(series, n=1): """Percent change over n years""" return (series/series.shift(n*series.index.freq.periodicity)-1)*100
a18bff66c60bf2620f524e104cf0b9842a85acf4
8,005
def to_eval_str(value): """ Returns an eval(str(value)) if the value is not None. :param value: None or a value that can be converted to a str. :return: None or str(value) """ if isinstance(value, str): value = eval(str(value)) return value
4cb13ad95095b8a6ee494265e600f989d98be05e
8,006
import sys def _encodehack(s): """ :param s: input string :type s: :class:str or :class:bytes: or :class:unicode Yields either UTF-8 decodeable bytestring (PY2) or PY3 unicode str. """ if sys.version_info[0] > 2: if type(s) == str: return s # type(s) is PY3<str> else: return s.decode('utf-8') # type(s) is PY3<bytes> or illegal elif type(s) == unicode: return s.encode('utf-8') # It is PY2 :class:unicode else: return s.decode('utf-8').encode('utf-8')
471d80c5bf35ade97d82b77eb7d628e86924643f
8,009
def read_float(field: str) -> float: """Read a float.""" return float(field) if field != "" else float('nan')
ce6f862c9696e3f84ba20b58a0acdce5c1e212b0
8,010
def get_trigger_name(operation, source_table, when): """Non-PostgreSQL trigger name""" op_initial = operation.lower()[0] when_initial = when.lower()[0] return f"trigger_{source_table}_{when_initial}{op_initial}r"
4e67005512fee99dd1bf5ed8b5d979e747d27b9f
8,011
def get_deprt(lista): """Add together from row with same index.""" base = [] for item in lista: base.append(item) resultado = set(base) return resultado
ecc3026d7674fcd90100db7d0b82cbc4376f1e4e
8,012
def get_dummy_image_name(): """ Returns the name of the dummy image """ return "python-logo.jpeg"
0a3a3664d06449641eb5ca32e03edd64d31eb63b
8,013
def check_punctuation(words): """Check to see if there's a period in the sentence.""" punctuation = [".", ",", "?"] return [word for word in words if word in punctuation]
4de89db149924ae3d457e57a3f9edac5dd4ae18a
8,014
from typing import Iterable from typing import Union from typing import List from typing import Tuple import os import hashlib def get_hashed_combo_path( root_dir: str, subdir: str, task: str, combos: Iterable[Union[List[str], Tuple[str, str]]], ) -> str: """ Return a unique path for the given combinations of models. :param root_dir: root save directory :param subdir: immediate subdirectory of root_dir :param task: the ParlAI task being considered :param combos: the combinations of models being compared """ # Sort the names in each combo, as well as the overall combos sorted_combos = [] for combo in combos: assert len(combo) == 2 sorted_combos.append(tuple(sorted(combo))) sorted_combos = sorted(sorted_combos) os.makedirs(os.path.join(root_dir, subdir), exist_ok=True) path = os.path.join( root_dir, subdir, hashlib.sha1( '___and___'.join( [f"{m1}vs{m2}.{task.replace(':', '_')}" for m1, m2 in sorted_combos] ).encode('utf-8') ).hexdigest()[:10], ) return path
b81b5d9d3b17a43daf4023200f7b7e40a26eb21e
8,016
def make_word(parts, sub, i): """Replace a syllable in a list of words, and return the joined word.""" j = 0 for part in parts: for k in range(len(part)): if i == j: part[k] = sub return ' '.join(''.join(p for p in part) for part in parts) j += 1
869aa94f60b819b38ad7ddc315b65d862cf525e0
8,017
import locale import math def format_col(df, col_name, rounding=0, currency=False, percent=False): """Function to format numerical Pandas Dataframe columns (one at a time). WARNING: This function will convert the column to strings. Apply this function as the last step in your script. Output is the formatted column. Parameters: df = the dataframe object col_name = the name of the column as a string rounding = decimal places to round to. ie 0 means round to the nearest whole number currency = adds the $ symbol percent = adds the % symbol and multiplies by 100 """ locale.setlocale(locale.LC_ALL, 'en_US.utf8') round_by = '{:,.%sf}' % str(rounding) if currency == True: return df[col_name].apply(lambda x: '$' + round_by.format(x) if math.isnan(x) == False else x) elif percent == True: return df[col_name].apply(lambda x: round_by.format(x * 100) + '%' if math.isnan(x) == False else x) else: return df[col_name].apply(lambda x: round_by.format(x) if math.isnan(x) == False else x)
a049c3a5f0ce28c3ec54ad0988e2679d512c6135
8,018
def tab_clickable_evt() -> str: """Adds javascript code within HTML at the bottom that allows the interactivity with tabs. Returns ------- str javascript code in HTML to process interactive tabs """ return """ <script> function menu(evt, menu_name) { var i, tabcontent, tablinks; tabcontent = document.getElementsByClassName("tabcontent"); for (i = 0; i < tabcontent.length; i++) { tabcontent[i].style.display = "none"; } tablinks = document.getElementsByClassName("tablinks"); for (i = 0; i < tablinks.length; i++) { tablinks[i].className = tablinks[i].className.replace(" active", ""); tablinks[i].style.backgroundColor = "white"; tablinks[i].style.color = "black"; } document.getElementById(menu_name).style.display = "block"; evt.currentTarget.className += " active"; evt.currentTarget.style.backgroundColor = "black"; evt.currentTarget.style.color = "white"; } window.onload=function(){ menu(event, 'SUMMARY'); }; </script>"""
bc15f819ef615200d09a356e250bc2d41710b36a
8,019
def validate_input_config(config): """Validate that the input source is valid""" input_manifest_s3_uri = config.get("inputManifestS3Uri") chain_from_job_name = config.get("chainFromJobName") if input_manifest_s3_uri and not chain_from_job_name: return None if not input_manifest_s3_uri and chain_from_job_name: return None return "Must specify single 'inputManifestS3Uri' or 'chainFromJobName' as input config"
4a2788c421225b7c38ec9414285e38d3323ac1ab
8,020
def reverse_complement(string): """Returns the reverse complement strand for a given DNA sequence""" return(string[::-1].translate(str.maketrans('ATGC','TACG')))
bd033b9be51a92fdf111b6c63ef6441c91b638a3
8,022
def _parse_seq(seq): """Get a primary sequence and its length (without gaps)""" return seq, len(seq.replace('-', ''))
f02c6f316e3bc56d3d77b6ca6363aa1e0a6b4780
8,023
def reverse_digit(x): """ Reverses the digits of an integer. Parameters ---------- x : int Digit to be reversed. Returns ------- rev_x : int `x` with it's digits reversed. """ # Initialisations if x < 0: neg = True else: neg = False x = abs(x) x_len = len(str(x)) # Number of digits in `x` rev_x = 0 for i in range(x_len): digit = x % 10 x = x // 10 rev_x += digit*(10**(x_len-i-1)) if neg == True: rev_x = -1*rev_x return rev_x else: return rev_x
d7358f5778897262b8d57c6dd3e2eb4acb05a2d1
8,025
def yyyymmdd(d, separator=''): """ :param d: datetime instance separator: string :return: string: yyyymmdd """ month = d.month if month < 10: month = '0' + str(month) else: month = str(month) day = d.day if day < 10: day = '0' + str(day) else: day = str(day) return separator.join([str(d.year), month, day])
a5b765ea9b740ac26b03fd16def62c7d84389e8e
8,026
def ping(value=0): """Return given value + 1, must be an integer.""" return {'value': value + 1}
487902e19decd04f2d1b7a75da6a9ca6bb2714d7
8,027
def f(x): """ Quadratic function. It's easy to see the minimum value of the function is 5 when is x=0. """ return x**2 + 5
7469225fd7d864c96ca957caa51bec924a81d599
8,030
def dropLabels(events, minPct=.05): """ # apply weights, drop labels with insufficient examples """ while True: df0 = events['bin'].value_counts(normalize=True) if df0.min() > minPct or df0.shape[0] < 3: break print('dropped label: ', df0.argmin(), df0.min()) events = events[events['bin'] != df0.argmin()] return events
cbfc6de91be685d6e5309a490c455badd7596093
8,031
def hammingDistance(str1, str2): """ Returns the number of `i`th characters in `str1` that don't match the `i`th character in `str2`. Args --- `str1 : string` The first string `str2 : string` The second string Returns --- `differences : int` The differences between `str1` and `str2` """ # Convert strings to arrays a = list(str1) b = list(str2) # Determine what n equals if len(a) < len(b): n = len(a) else: n = len(b) # Increment the number of distances for each difference differences = 0 for i in range(n): if a[i] != b[i]: differences += 1 return differences
ad35cc79f89171c75a16a13ec6862a2a4abdbd61
8,032
def pedirOpcion(): """Pide y devuelve un entero en el rango de opciones validas""" correcto = False num = 0 while not correcto: try: num = int(input("Elige una opcion -> ")) if num < 0 or num > 3: raise ValueError correcto = True except ValueError: print("Error, introduce un valor valido") return num
a758254110e0d39fc8b1b4cab91b95799311fdcf
8,034
from typing import OrderedDict def _order_dict(d): """Convert dict to sorted OrderedDict""" if isinstance(d, dict): d = [(k, v) for k, v in d.items()] d = sorted(d, key=lambda x: x[0]) return OrderedDict(d) elif isinstance(d, OrderedDict): return d else: raise Exception('Must be dict or OrderedDict')
94b3e9e0c5b34e466c913c46683c752ca9560a12
8,035
def display_get_rule_name(): """display function to prompt for the name of the rule to add""" return input("Name of the rule to add: ")
e6df6b4df7aecb289d56d65c35de78eb1a8ab591
8,036
import sys def in_virtualenv() -> bool: """Return True when pype is executed inside a virtual env.""" return ( hasattr(sys, 'real_prefix') or ( hasattr(sys, 'base_prefix') and sys.base_prefix != sys.prefix ) )
3b7e7b8f21b2a988e0190219c8d26a503929d5af
8,037
import ast def collect_args(args: ast.arguments): """Collect function arguments.""" all_args = args.args + args.kwonlyargs all_args += [args.vararg, args.kwarg] return [arg for arg in all_args if arg is not None]
b8fdd180259aadd6a8d31a83503cf7da2b2c0bae
8,039
import shutil from pathlib import Path def clean_build(): """Remove build directory and recreate empty""" shutil.rmtree("site_build", ignore_errors=True) build_dir = Path("site_build") build_dir.mkdir(exist_ok=True) return build_dir
121e6ba5f06243654a3a38946a332efae43ce6c2
8,040
def clean_toc(toc: str) -> str: """Each line in `toc` has 6 unnecessary spaces, so get rid of them""" lines = toc.splitlines() return "\n".join(line[6:] for line in lines)
40a22200d04c12865e4bffae9cdd3bdc4ea827be
8,042
import pickle def pickle_load(file_path): """ data = pickle_load(file_path) Load data from a pickle dump file inputs: file_path: str, path of the pickle file output: data: python object """ with open(file_path, 'rb') as file_ptr: data = pickle.load(file_ptr) return data
c9112881facc7a6a135893168fa9abf63309b392
8,043
def versiontuple(v): """Return the version as a tuple for easy comparison.""" return tuple(int(x) for x in v.split("."))
422d49818e2d6d34d0591c1c450d0c92b7fabc82
8,044
import re def find_checksum(s): """Accepts a manifest-style filename and returns the embedded checksum string, or None if no such string could be found.""" m = re.search(r"\b([a-z0-9]{32})\b", s, flags=re.IGNORECASE) md5 = m.group(1).lower() if m else None return md5
f0d9735833e257a3f133d2d51b01775e35408755
8,045
def sum_up_nums(*nums): """(int or float) -> int or float Adds up as many numbers(separate arguments) as the caller can supply. Returns the sum of <*nums> """ cntr = 0 # Init sum zero for num in nums: cntr += num return cntr
8ed03f16d624ea24a90a20d42df30328b119edd7
8,046
def get_expts(context, expts): """Takes an expts list and returns a space separated list of expts.""" return '"' + ' '.join([expt['name'] for expt in expts]) + '"'
76cd216662a6f7a248b70351f79b52e3c47871aa
8,048
def create_filename(last_element): """ For a given file, returns its name without the extension. :param last_element: str, file name :return: str, file name without extension """ return last_element[:-4]
3faaf647ed6e3c765321efb396b2806e7ef9ddf9
8,050
from typing import Union def is_number(value: Union[int, str]) -> bool: """ Is thing a number """ return isinstance(value, int) or (isinstance(value, str) and value.isnumeric())
e69de261a45398eb970c00e9a5997a615c6fc7e6
8,051
def normalization(vector): """ Normalize scores in this vector """ x = vector[vector>0] beta = x.quantile(0.9) updated_vector = vector/beta return updated_vector
dfe403e8ec73ca3fab5492ce42a6390f1963f840
8,052
import os import sqlite3 def get_default_db(): """Get the default database for the crawler. Returns: DB API v2 compliant connection to the crawler's default database. """ parent_dir = os.path.dirname(os.path.realpath(__file__)) loc = os.path.join(parent_dir, 'articles.db') return sqlite3.connect(loc)
77c589ecb51379fff937c84579e8a30313352b29
8,054
import os def dispatch_repl_commands(command): """Execute system commands entered in the repl. System commands are all commands starting with "!". """ if command.startswith('!'): os.system(command[1:]) return True return False
96b7f7783c8579b2717fef2a160094bf2e7dc86e
8,055
def simplify_numpy_dtype(dtype): """Given a numpy dtype, write out the type as string Args: dtype (numpy.dtype): Type Returns: (string) name as a simple string """ kind = dtype.kind if kind == "b": return "boolean" elif kind == "i" or kind == "u": return "integer" elif kind == "f": return "float" elif kind == "c": return "complex" elif kind == "m": return "timedelta" elif kind == "M": return "datetime" elif kind == "S" or kind == "U": return "string" else: return "python object"
c2370b2a08e58c9614ca43e3f14864782eef4100
8,056
def GetNetworkPerformanceConfig(args, client): """Get NetworkPerformanceConfig message for the instance.""" network_perf_args = getattr(args, 'network_performance_configs', []) network_perf_configs = client.messages.NetworkPerformanceConfig() for config in network_perf_args: total_tier = config.get('total-egress-bandwidth-tier', '').upper() if total_tier: network_perf_configs.totalEgressBandwidthTier = client.messages.NetworkPerformanceConfig.TotalEgressBandwidthTierValueValuesEnum( total_tier) return network_perf_configs
2b2f0773fb01b7bbcda30af38d03ed845331f10c
8,057
def OpenFace(openface_features, PID, EXP): """ Tidy up OpenFace features in pandas data.frame to be stored in sqlite database: - Participant and experiment identifiers are added as columns - Underscores in column names are removed, because sqlite does not like underscores in column names. - Only column names with 'AU' in the column name are considered relevant features and kept, the rest is removed. Parameters ---------- video_features : pandas.core.frame.DataFrame Data frame with columns participant_id (str), experiment_id (str), timestamp (datetime64), and columns for the OpenFace derived video features: AU01r (float64), AU02r (float64), AU01c (float64), AU02c (float64) PID : str Participant identifier EXP : str Experiment identifier. Returns ------- video_features : pandas.core.frame.DataFrame New data frame """ # tidy up data frame: filter_col = [col for col in openface_features if col.startswith('AU')] filter_col.insert(0,'time') filter_col.insert(0,'participant_id') filter_col.insert(0,'experiment_id') openface_features['participant_id'] = PID openface_features['experiment_id'] = EXP openface_features = openface_features[filter_col] openface_features.columns = openface_features.columns.str.replace('_', '') openface_features = openface_features.rename(columns = {'experimentid':'experiment_id'}) openface_features = openface_features.rename(columns = {'participantid':'participant_id'}) return openface_features
684e74c159a3551e3fd6d9a80b134c2474759056
8,059
def check_issue(name, checks, controls): """ Checks if a certain RWT issue needs to be suggested. Returns: list """ rwt = [] is_issue = False total_reasons = [] total_offenders = [] for check in checks: for control in controls: if control != []: for res in control: if res['ControlId'] == check: if res['Result'] == False: is_issue = True for reason in res['failReason']: total_reasons.append(reason) for offender in res['Offenders']: total_offenders.append(offender) rwt.append({'Name': name, 'Result': is_issue, 'total_reasons': total_reasons, 'total_offenders': total_offenders}) return rwt
7e16b5d7fe2e674a4e91ccec70ca6a5f47784c49
8,060
def get_binary_result(probs): """ 将预测结果转化为二分类结果 Args: probs: 预测结果 Return: binary_result: 二分类结果 """ binary_result = [] for i in range(len(probs)): if float(probs[i][0]) > 0.5: binary_result.append(1) elif float(probs[i][0]) < 0.5: binary_result.append(0) return binary_result
df0375b05abe2807a1568133f8ed0aa4a5fe3736
8,061
def _load_transforms(): """ Load the transform pairs into the module level variable for later lookup. Returns ------- :class:`dict` """ return { f: (globals().get(f), globals().get("inverse_{}".format(f))) for f in globals().keys() if "inverse_{}".format(f) in globals().keys() }
45ef7c50aee54e6daa344809e603f7abf7bbe836
8,062
import copy def deep_merge_dict(base, priority): """Recursively merges the two given dicts into a single dict. Treating base as the the initial point of the resulting merged dict, and considering the nested dictionaries as trees, they are merged os: 1. Every path to every leaf in priority would be represented in the result. 2. Subtrees of base are overwritten if a leaf is found in the corresponding path in priority. 3. The invariant that all priority leaf nodes remain leafs is maintained. Parameters ---------- base : dict The first, lower-priority, dict to merge. priority : dict The second, higher-priority, dict to merge. Returns ------- dict A recursive merge of the two given dicts. Example: -------- >>> base = {'a': 1, 'b': 2, 'c': {'d': 4}, 'e': 5} >>> priority = {'a': {'g': 7}, 'c': 3, 'e': 5, 'f': 6} >>> result = deep_merge_dict(base, priority) >>> print(sorted(result.items())) [('a', {'g': 7}), ('b', 2), ('c', 3), ('e', 5), ('f', 6)] """ if not isinstance(base, dict) or not isinstance(priority, dict): return priority result = copy.deepcopy(base) for key in priority.keys(): if key in base: result[key] = deep_merge_dict(base[key], priority[key]) else: result[key] = priority[key] return result
5c527f45d4ddee00f1e905b09165bcd3551412f6
8,063
def get_convert_label_fn(odgt): """ A function that converts labels to expected range [-1, num_classes-1] where -1 is ignored. When using custom dataset, you might want to add your own function. """ def convert_ade_label(segm): "Convert ADE labels to range [-1, 149]" return segm - 1 def convert_cityscapes_label(segm): "Convert cityscapes labels to range [-1, 18]" ignore_label = -1 label_mapping = { -1: ignore_label, 0: ignore_label, 1: ignore_label, 2: ignore_label, 3: ignore_label, 4: ignore_label, 5: ignore_label, 6: ignore_label, 7: 0, 8: 1, 9: ignore_label, 10: ignore_label, 11: 2, 12: 3, 13: 4, 14: ignore_label, 15: ignore_label, 16: ignore_label, 17: 5, 18: ignore_label, 19: 6, 20: 7, 21: 8, 22: 9, 23: 10, 24: 11, 25: 12, 26: 13, 27: 14, 28: 15, 29: ignore_label, 30: ignore_label, 31: 16, 32: 17, 33: 18} temp = segm.clone() for k, v in label_mapping.items(): segm[temp == k] = v return segm if 'cityscapes' in odgt.lower(): return convert_cityscapes_label elif 'ade' in odgt.lower(): return convert_ade_label else: return lambda x: x
dd87a1cc889faf5874eaec45db51804b20fb46ff
8,064
def _get_span(s, pattern): """Return the span of the first group that matches the pattern.""" i, j = -1, -1 match = pattern.match(s) if not match: return i, j for group_name in pattern.groupindex: i, j = match.span(group_name) if (i, j) != (-1, -1): return i, j return i, j
8feec723d5a09e70f000c6fcdf58269dd6ea9330
8,065
from pathlib import Path def guess_format(path): """Guess file format identifier from it's suffix. Default to DICOM.""" path = Path(path) if path.is_file(): suffixes = [x.lower() for x in path.suffixes] if suffixes[-1] in ['.h5', '.txt', '.zip']: return suffixes[-1][1:] if suffixes[-1] == '.nii' or path.suffixes[-2:] == ['.nii', '.gz']: return 'nifti' return 'dicom'
70f463ef28adc2c65346ec8b5b87294494a9ee0f
8,066
import numpy def cartesian_to_polar(u, v): """ Transforms U,V into r,theta, with theta being relative to north (instead of east, a.k.a. the x-axis). Mainly for wind U,V to wind speed,direction transformations. """ c = u + v*1j r = numpy.abs(c) theta = numpy.angle(c, deg=True) # Convert angle relative to the x-axis to a north-relative angle theta -= 90 theta = -theta % 360 return r, theta
ee35ca5d5201b10e31b6f0eea0471b0b97ada5fb
8,067
def get_samples(profileDict): """ Returns the samples only for the metrics (i.e. does not return any information from the activity timeline) """ return profileDict["samples"]["metrics"]
06b273e7499e9cb64e38b91374117de6bd3f6c3e
8,069
def dobro(n): """ Dobrar número :param n: número a ser dobrado :return: resultado """ n = float(n) n += n return n
fe17270b7a3373545986568657cf6755dc88638f
8,070
def aoi_from_experiment_to_cairo(aoi): """Transform aoi from exp coordinates to cairo coordinates.""" width = round(aoi[1]-aoi[0], 2) height = round(aoi[3]-aoi[2], 2) return([aoi[0], aoi[2], width, height])
40986aeaf5bb1e5d8295289ce310b4c7cf7f4241
8,071
def rec_dfs_edges(graph): """ recursive way for above Note: a-b and b-a are different in this case.. """ nodes = graph.nodes # type: dict visited = set() start = list(nodes.keys())[0] edges = [] def _rec_dfs(graph, _start, _nodes): for _node in nodes: if _node in visited: continue # new node visited.add(_node) children = graph[_node] for child in children: edges.append((_node, child)) _rec_dfs(graph, child, _nodes) _rec_dfs(graph, start, nodes) return edges
c4801cb45d09602cef65f20d5612d8c0e0fc8a49
8,072
def palindromic(d): """Gets a palindromic number made from a product of two d-digit numbers""" # Get the upper limit of d digits, e.g 3 digits is 999 a = 10 ** d - 1 b = a # Get the lower limit of d digits, e.g. 3 digits is 100 limit = 10 ** (d - 1) for x in range(a, limit - 1, -1): for y in range(b, limit - 1, -1): tmp = x * y if str(tmp) == str(tmp)[::-1]: print(x, y) return x * y return 0
d4324d6c2de3dff46e14b754627bb551e03e957f
8,073
import sys def getArguments(): """ Get argumments from command-line If pass only dataframe path, pop and gen will be default """ dfPath = sys.argv[1] if(len(sys.argv) == 4): pop = int(sys.argv[2]) gen = int(sys.argv[3]) else: pop = 10 gen = 2 return dfPath, pop, gen
cc1248746a82bed597c2cc5564b35a9a241f9360
8,074
import requests import os import tarfile def status(jobid, results_dir_path=None, extract=False, silent=False, host="http://www.compbio.dundee.ac.uk/jpred4/cgi-bin/rest", jpred4="http://www.compbio.dundee.ac.uk/jpred4"): """Check status of the submitted job. :param str jobid: Job id. :param str results_dir_path: Directory path where to save results if job is finished. :param extract: Extract (True) or not (False) results into directory. :type extract: :py:obj:`True` or :py:obj:`False` :param silent: Should the work be done silently? :type silent: :py:obj:`True` or :py:obj:`False` :param str host: JPred host address. :param str jpred4: JPred address for results retrieval. :return: Response. :rtype: requests.Response """ if not silent: print("Your job status will be checked with the following parameters:") print("Job id:", jobid) print("Get results:", bool(results_dir_path)) job_url = "{}/{}/{}/{}".format(host, "job", "id", jobid) response = requests.get(job_url) if response.reason == "OK": if not silent: print(response.text) if "finished" in response.text.lower(): if results_dir_path is not None: results_dir_path = os.path.join(results_dir_path, jobid) if not os.path.exists(results_dir_path): os.makedirs(results_dir_path) archive_url = "{}/{}/{}/{}.{}".format(jpred4, "results", jobid, jobid, "tar.gz") archive_path = os.path.join(results_dir_path, "{}.{}".format(jobid, "tar.gz")) archive_response = requests.get(archive_url, stream=True) with open(archive_path, "wb") as outfile: for chunk in archive_response.iter_content(chunk_size=1024): outfile.write(chunk) if extract: tar_archive = tarfile.open(archive_path) tar_archive.extractall(path=results_dir_path) if not silent: print("Saving results to: {}".format(os.path.abspath(results_dir_path))) else: response.raise_for_status() return response
98931b8af31cea66c602fa5c6a48a58c2f5a42e0
8,075
def markup(pre, string): """ By Adam O'Hern for Mechanical Color Returns a formatting string for modo treeview objects. Requires a prefix (usually "c" or "f" for colors and fonts respectively), followed by a string. Colors are done with "\03(c:color)", where "color" is a string representing a decimal integer computed with 0x01000000 | ((r << 16) | (g << 8) | b). Italics and bold are done with "\03(c:font)", where "font" is the string FONT_DEFAULT, FONT_NORMAL, FONT_BOLD or FONT_ITALIC. \03(c:4113) is a special case gray color specifically for treeview text. """ return '\03({}:{})'.format(pre, string)
7ef910aa3b057e82c777b06f73faf554d9c4e269
8,079
def response2dict(response): """ This converts the response from urllib2's call into a dict :param response: :return: """ split_newlines = response.split('\r\n') split_tabs = [s.split('\t') for s in split_newlines if s !=''] return split_tabs
d0bcfaca4ed00c74a1a10838881dac8e80f5d479
8,080
from bs4 import BeautifulSoup def get_person_speech_pair(file_name): """ XML parser to get the person_ids from given XML file Args: file_name(str): file name Returns: person_id_speech_pair(dict): Dict[person_id(int) -> speech(str)] """ person_id_speech_dict = dict() with open(file_name, encoding='utf-8') as file: soup = BeautifulSoup(file, 'xml') all_speech = soup.find_all('speaker') for single_speech in all_speech: try: # newer format person_id = single_speech['personId'] except KeyError: try: # older format person_id = single_speech['person'] except KeyError: continue single_speech_list = [] for s in single_speech.stripped_strings: single_speech_list.append(s) processed_speech = ' '.join(single_speech_list) # print(parsed_speech, '\n') if person_id not in person_id_speech_dict: person_id_speech_dict[person_id] = [] person_id_speech_dict[person_id].append(processed_speech) for person_id in person_id_speech_dict: person_id_speech_dict[person_id] = ' '.join(person_id_speech_dict[person_id]) return person_id_speech_dict
0751ed8d46c39027c0503dcd94d8c324c700c1a5
8,084
import pandas def get_df(a: int) -> pandas.DataFrame: """ Generate a sample dataframe """ return pandas.DataFrame(data={"col1": [a, 2], "col2": [a, 4]})
56008e78d68110e8f12463b37368d0be7f3e4c9a
8,085
import os def random_key_generator(key_length): """ Creates a random key with key_length written in hexadecimal as string Paramaters ---------- key_length : int Key length in bits Returns ------- key : string Key in hexadecimal as string """ return bytes.hex(os.urandom(key_length // 8))
80c8e9e6949cfd1e5ead274c0b89bc0d40e1f926
8,086
from datetime import datetime def utc2local(utc_dtm): """ UTC 时间转本地时间( +8:00 ) :param utc_dtm: :return: """ local_tm = datetime.fromtimestamp(0) utc_tm = datetime.utcfromtimestamp(0) offset = local_tm - utc_tm return utc_dtm + offset
0070c3ae1e37071cbf57806ca18576f81abb64e0
8,087
def get_hash_hex(raw_hash): """Creates a nice hex representation of a raw req""" return raw_hash.encode('iso-8859-1').encode('hex')
a7c0e873617cae2481fecc32a2051ad1fc6a9519
8,088