content
stringlengths
39
14.9k
sha1
stringlengths
40
40
id
int64
0
710k
def gen_mask(n: int) -> int: """ Will create a n bit long mask. This works by creating a byte with a 1 at the n+1 place. Subtracting this with one will make all previus bits 1, thus creating a byte with the first n bits set. >>> bin(gen_mask(3)) '0b111' >>> bin(gen_mask(2)) '0b11' >>> bin(gen_mask(8)) '0b11111111' """ return (1 << n) - 1
482e16f3ac465d841d59bfe4ff312fcbd1ac512c
62,716
def style_str(s, color='black', weight=300): """ Style the supplied string with HTML tags Args: s (str): string to format color( str ): color to show the string in weight( int ): how thick the string will be displayed Returns: html(string) : html representation of the string """ return f'<text style="color:{color}; font-weight:{weight}" >{s}</text>'
d00e80a153787260c6528bb3f00b697fb2ab8c81
62,717
def get_redact_list(item): """ Get the redaction list, ensuring that the images and metadata dictionaries exist. :param item: a Girder item. :returns: the redactList object. """ redactList = item.get('meta', {}).get('redactList', {}) for cat in {'images', 'metadata'}: redactList.setdefault(cat, {}) for key in list(redactList[cat]): if not isinstance(redactList[cat][key], dict): redactList[cat][key] = {'value': redactList[cat][key]} return redactList
8452ceb18e43be77d4fe88e73ff7d332372da7f5
62,718
def str_is_int(x: str) -> bool: """Test if a string can be parsed as an int""" try: int(x) return True except ValueError: return False
3740ec6118c84de097b13139581cf5080e910c00
62,720
def replace_escapes(text): """ Replace escape sequences with the characters they represent :param text: string to replace escapes in :return: New string with escapes replaced by the represented characters """ escape = False out = "" for char in text: if escape is True: if char == "t": out += "\t" elif char == "n": out += "\n" elif char == "s": out += " " else: out += char escape = False continue if char == "\\": escape = True else: out += char return out
666133b97cdee52e9cdc94686cdb208cda4dcbba
62,722
def weighted_moving_average(days, weights): """ | Calculates the rolling weighted moving average. The weights list should have the size of the days window. | Name: weighted\_moving\_average\_\ **days** :param days: Size of the window :type days: int :param weights: Weights to use for the calculation :type weights: list(int) """ def f(w): def g(x): return (w * x).sum() / sum(w) return g def return_function(data): if len(weights) == days: column_name = f"weighted_moving_average_{days}" if column_name not in data.columns: data[column_name] = ( data["close"].rolling(window=days).apply(f(weights), raw=True) ) return data[column_name].copy() else: raise Exception("Weights length and rolling mean must be same length") return return_function
689e5e88895a28de1850c1563f0f9fcc0f4c34cf
62,726
import json def read_json(filename): """Reads data from a file in JSON format""" with open(filename) as data_file: return json.load(data_file)
b0d8665101851729ed0ed0b9fc2778a5a9d7f3a1
62,728
import json import requests def groupList(apikey): """ Returns all Groups existing in your FileCrypt Account apikey: Your ApiKey from FileCrypt """ data={"api_key":apikey,"fn":"group","sub":"list"} return json.loads(requests.post("https://filecrypt.cc/api.php",data=data).text)
4408d1a585905635e9b8b12d294e91f59f1de3cb
62,729
def check_unique_list(input): """ Given a list, check if it is equal to a sorted list containing 1-9 Return True if the given list is unique, False otherwise """ # convert list string into list of int and sort it int_list = list(map(int, input)) int_list.sort() return int_list == [1, 2, 3, 4, 5, 6, 7, 8, 9]
0448d3c054063076b4bcd3eb37def9cc5e1edfed
62,735
def _findstart(line_segment): """Find start of text to autocomplete. >>> _findstart("where x.pers") 8 >>> _findstart("from d.person, d.na") 17 >>> _findstart(" and x.") 10 >>> _findstart("where i") 6 >>> _findstart(" ") 3 """ if '.' in line_segment: return line_segment.rindex('.') + 1 elif ' ' in line_segment: return line_segment.rindex(' ') + 1 else: return -1
a8e75e2f19c96529021e2eea5cf361be2fefaf74
62,745
def _bin_to_int(b_list): """ Convert b_list, a list of {0,1}, to an integer """ out = 0 for b in b_list: out = (out << 1) | b return out
a82e123348e892e95d5ca476005c34a4d9ead7eb
62,746
def get_byte(byte_str): """ Get a byte from byte string :param byte_str: byte string :return: byte string, byte """ byte = byte_str[0] byte_str = byte_str[1:] return byte_str, byte
2a00e82e10b4ed367ebcb41240d5393477f3b234
62,748
def checkCrossConstraint(env, trajEvader, trajPursuer): """Checks if the evader crosses the boundary. Args: env (gym.Env): the environment. trajEvader (np.ndarray): the trajectory of the evader. trajPursuer (np.ndarray): the trajectory of the pursuer. Returns: bool: True if crossing the boundary. int: the time step at which the evader hits the obstacle. """ numStep = trajEvader.shape[0] crossConstraintFlag = False crossConstraintInstant = None for t in range(numStep): posEvader = trajEvader[t, :2] evader_g_x = env.evader.safety_margin(posEvader) if not crossConstraintFlag and evader_g_x > 0: crossConstraintInstant = t crossConstraintFlag = True return crossConstraintFlag, crossConstraintInstant
630bd9ea5d702a9a8e8b74b064cb91545db364dd
62,751
def split_documents_into_equal_chunks(documents, chunk_size): """This method splits a list or dictionary into equal chunks size :param documents: List or Dictionary to be partitioned into chunks :param chunk_size: Maximum size of a chunk Returns: list_of_chunks: List containing the chunks """ list_of_chunks = [] for i in range(0, len(documents), chunk_size): if type(documents) is dict: partitioned_chunk = list(documents.items())[i: i + chunk_size] list_of_chunks.append(dict(partitioned_chunk)) else: list_of_chunks.append(documents[i: i + chunk_size]) return list_of_chunks
3fb2d0bc1b035529915c25372df70e1ec055de4c
62,755
import pprint def mock_render_template(*args, **kwargs): """ Pretty-print the args and kwargs. Allows us to not depend on any actual template rendering mechanism, while still returning a unicode object """ return pprint.pformat((args, kwargs)).encode().decode()
710eabecef2d2f29543788756ae872f73a766011
62,757
def string2bool(allegedstring): """ Tries to return a boolean from a string input if possible, else it just returns the original item, allegedly a string. """ if allegedstring.lower().startswith('t'): return True elif allegedstring.lower().startswith('f'): return False elif allegedstring == "1": return True elif allegedstring == "0": return False else: return allegedstring
a5a8598f0d0c2e79a27f7ae9a4555894b2ccf9ac
62,765
def isWhitespace(char): """ Determine whether a character is whitespace @param char: the character to check @return True if the character is whitespace, False otherwise """ return char == ' ' or char == '\t' or char == '\r' or char == '\n'
72eb79c8bb6a6192dd3c7713bbe5e3944550c994
62,768
import re def _convert_to_code(val): """ Convert ' to code(`) or ''' code blocks(```) and convert ' within code blocks to " e.g.: 'display_name' converts to `display_name` e.g.: '''pip install -U 'resilient-circuits'''' converts to ```shell $ pip install -U "resilient-circuits" ``` """ return re.sub(r"'{3}(.*)'(.*)'(.*)'{3}", r'\n\n```shell\n$ \1"\2"\3\n```\n', val).replace("'", "`").replace("\t\t", "\t")
143e26a6d6ee322adffa5df9c54d6a5c03b5c4f0
62,774
def parse_ft_line(line, vocab_to_idx=None, lbl_to_idx=None): """Convert line from fastText format to list of labels and tokens. If vocab_to_idx and/or lbl_to_idx provided, tokens are converted to integer indices. """ line = line.strip().split() labels = [w for w in line if w.startswith('__label__')] if lbl_to_idx: labels = [lbl_to_idx[w] for w in labels] tokens = [w for w in line if not w.startswith('__label__')] if vocab_to_idx: tokens = [vocab_to_idx.get(w, len(vocab_to_idx)) for w in tokens] return labels, tokens
08138cf8b1d20f109cc05db5c671a0eb3d69c2f1
62,775
def flatten(l): """ Flattens a list. Written by Bearophile as published on the www.python.org newsgroups. Pulled into Topographica 3/5/2005. """ if type(l) != list: return l else: result = [] stack = [] stack.append((l,0)) while len(stack) != 0: sequence, j = stack.pop(-1) while j < len(sequence): if type(sequence[j]) != list: k, j, lens = j, j+1, len(sequence) while j < len(sequence) and \ (type(sequence[j]) != list): j += 1 result.extend(sequence[k:j]) else: stack.append((sequence, j+1)) sequence, j = sequence[j], 0 return result
a4a8b9f3bff6e4deea546e58faaec0bd73bb217a
62,783
def validate_dpi(s): """confirm s is string 'figure' or convert s to float or raise""" if s == 'figure': return s try: return float(s) except ValueError: raise ValueError('"%s" is not string "figure" or' ' could not convert "%s" to float' % (s, s))
56778a405a4e15ee5f1acd4ad165e5c33db00d19
62,789
import re import platform def on_ubuntu() -> bool: """ return true on recent ubuntu linux distro. """ match = re.match(r'^.+Ubuntu-\d\d\.\d\d-\w+', platform.platform()) return match is not None
94938ef1dfd9960a3a6c10b8a42e56b695c1fa6f
62,790
def reshape_nda_to_3d(arr) : """Reshape np.array to 3-d """ sh = arr.shape if len(sh)<4 : return arr arr.shape = (arr.size/sh[-1]/sh[-2], sh[-2], sh[-1]) return arr
9adee8d1c9c2bc4afa4a066c116d1d60c143632f
62,796
def similarity_threshold(h, bands): """ Function returning the Jaccard similarity threshold for minhash signature composed of h integers and a signature matrix divided in n bands. Args: h (int): Number of integers in the minhash signature. bands (int): Number of bands dividing the signature matrix. Returns: float: The Jaccard similarity threshold. """ return (1.0 / bands) ** (1 / (h / bands))
aa1b35cf8942391077dba01dc87a4489ae94e1cd
62,804
def get_neighbors(r_index, c_index): """Get neighboring cell positions Args: r_index (int): Current row index c_index ([type]): Current column index Returns: [List of list of integers]: List of neighbors with each neighbor containing a list of their row and column index. """ neighbors = [] for x in range(-1, 2, 1): for y in range(-1, 2, 1): if x != 0 or y != 0: neighbors.append([r_index + x, c_index + y]) return neighbors
267c7b56ce04085f3095a7d21a0710bb3b980094
62,807
import random import string def string_id(length=8): """ Generate Random ID. Random ID contains ascii letters and digitis. Args: length (int): Character length of id. Returns: Random id string. """ return ''.join(random.choice(string.ascii_letters + string.digits) for _ in range(length))
dacfef58781c5291ce6bb975ee1de317b5524fda
62,808
import time def created_at(created_at): """Convert a timestamp string to one more suited for sorting""" return time.strftime("%Y-%m-%d %H:%M:%S", time.strptime(created_at, "%a %b %d %H:%M:%S +0000 %Y"))
088fd700be2c308dafb66b243c1eb9f02c2a41cf
62,812
import random def get_random_list(length=100, max_num=10): """ Generate a list containing random numbers. Args: length (int): The length of the list to generate. max_num (int): The largest number to include in the list. """ return [random.randrange(1, max_num, 1) for _ in range(length)]
2ac16cac38c53afebed595110ead8619fa14d583
62,817
def _format_lineno(session, line): """Helper function to format line numbers properly.""" if session == 0: return str(line) return "%s#%s" % (session, line)
f30e29eb016b5246ce94582f95ed0c4c4fe20432
62,819
from typing import Optional import time def make_run_id(model_name: str, task_name: str, run_name: Optional[str] = None) -> str: """Choose a run ID, based on the --run-name parameter and the current time.""" if run_name is not None: return run_name else: return "%s_%s__%s" % (model_name, task_name, time.strftime("%Y-%m-%d_%H-%M-%S"))
330b4b18dff3865d98fbc9ed731038e3afb2c989
62,826
def replace(text, searchValue, replaceValue): """ Return a string where all search value are replaced by the replace value. """ return text.replace(searchValue, replaceValue)
60840f9b2896603cf7200186795d088617a38710
62,833
import time def timeit(num: int): """~ Profiling function ~ @Info: Prints average time to execute specific function @Param: - num: int ~ Number of samples to take for average""" def _timeit(fnc): sum = 0 ct = 0 def __timeit(*args, **kwargs): nonlocal sum nonlocal ct start = time.time() ret = fnc(*args, **kwargs) end = time.time() ms = (end-start)*1000 sum += ms ct += 1 if ct == num: print(f"{fnc.__name__} took {sum/ct} ms on average") ct = 0 sum = 0 return ret return __timeit if callable(num): # is a function (function was used as decorator) tmp = num num = 1 return _timeit(tmp) return _timeit
f479e07ac48b3dbee7b3b93fa7e4c9d73a9a525c
62,834
import re def FileExtension(file_name): """Return the file extension of file 'file' should be a string. It can be either the full path of the file or just its name (or any string as long it contains the file extension.) Example #1: input (file) --> 'abc.tar.gz' return value --> 'tar.gz' Example #2: input (file) --> 'abc.tar' return value --> 'tar' """ match = re.compile(r"^.*?[.](?P<ext>tar[.]gz|tar[.]bz2|\w+)$", re.VERBOSE|re.IGNORECASE).match(file_name) if match: # if match != None: ext = match.group('ext') return ext else: return '' # there is no file extension to file_name
53cff85d1b9c8faa0bb062fa459205ee8dad0b6d
62,835
def make_draw_response(reason: str) -> str: """Makes a response string for a draw. Parameters: - reason: The reason for the draw, in the form of a noun, e.g., 'stalemate' or 'insufficient material'. Returns: The draw response string. """ return f"It's a draw because of {reason}!"
638dd1eadc8daae422c8096bd76e81a0c085a5fa
62,839
def MI_Tuple(value, Is): """ Define function for obtaining multiindex tuple from index value value: flattened index position, Is: Number of values for each index dimension Example: MI_Tuple(10, [3,4,2,6]) returns [0,0,1,4] MI_Tuple is the inverse of Tuple_MI. """ IsValuesRev = [] CurrentValue = value for m in range(0,len(Is)): IsValuesRev.append(CurrentValue % Is[len(Is)-m-1]) CurrentValue = CurrentValue // Is[len(Is)-m-1] return IsValuesRev[::-1]
97a71e9049fec0e95fccfcebb2aea4032f980fbe
62,844
def add(x, y): """ This function sums up two numbers. Parameters ---------- x : float The first number to be added. y : float The second number to be added. Returns ------- sum : float The sum of x and y. """ sum = x + y return sum
506e2dbf1be7bbc1efde2735b2c634583afcc454
62,846
def store_path(connection, path): """Store the file path in the SQL filepaths table. :param connection: :param path: :return: path id""" insert = '''INSERT OR IGNORE INTO filepaths(filepath) VALUES(?)''' cursor = connection.cursor() cursor.execute(insert, (path,)) return cursor.lastrowid
d8ee7f44539ff642dffd62bd089b818cffe3468b
62,849
def create_cell_metadata(hidden: bool) -> dict: """ Creates the metadata Dict of a Synapse notebook cell. :param hidden: The flag that determines whether a cell is hidden or not. :returns: The metadata Dict of a Synapse notebook cell. """ return {"jupyter": {"source_hidden": hidden, "outputs_hidden": hidden}}
8b9b8a8a5a27522cb640205375c18abc264ca400
62,853
def binomial_coefficient(n: int, k: int) -> int: """ Returns the binomial coefficient Defined as: factorial(n) // (factorial(n - k) * factorial(k)) :param n: The number of items :param k: The number of selected items :return: The number of ways to select k items from n options """ if k > n: return 0 k = min(k, n - k) # take advantage of symmetry c = 1 for i in range(k): c = (c * (n - i)) // (i + 1) return c
97e75efd159fe3de36f28138ef90b695660f3cf4
62,855
def compress_2d_list(squares_list): """ Convert 2d list to a 1d list """ result = [] for row in squares_list: for col in row: result.append(col) return result
3f4db2227e0dec1bc67ec277637dbcdb001a15ad
62,857
from typing import Dict def get_names(market, name_attr='name', name_key=False) -> Dict[int, str]: """ Get dictionary of {runner ID: runner name} from a market definition - name_attr: optional attribute name to retrieve runner name - name_key: optional flag to return {runner name: runner ID} with name as key instead """ if not name_key: return { runner.selection_id: getattr(runner, name_attr) for runner in market.runners } else: return { getattr(runner, name_attr): runner.selection_id for runner in market.runners }
64885ee93a8dd0c9ec454bb335cf7fe47d454ef3
62,866
def clean_nested_colname(s): """ Removes map name for MapType columns. e.g. metadata.SeriesInstanceUID -> SeriesInstanceUID """ return s[s.find('.')+1:]
20a8db386c82f66924bda591db8cdeddf6b643a8
62,867
import curses def has_colours(stream): """Determine if an output stream supports colours. Args: stream: the output stream to check Returns: True if more than 2 colours are supported; else False """ if hasattr(stream, 'isatty') and stream.isatty(): try: curses.setupterm() return curses.tigetnum('colors') > 2 except Exception: pass return False
46a5cb171213423157f45904f7df9c77aad1c652
62,869
def get_region_for_sample(sample, bpid, target): """ Parse a dictionary and obtain the region for a given sample """ for sample_id in target: if sample.find(sample_id) != -1: if bpid == 1: return target[sample_id]['region1'] else: return target[sample_id]['region2'] break
e302f12f72a33a58f296bac24260ce00fed4128b
62,871
def norm_z_value(img, ref_img): """This function will normalize the two images using z-value normalization Parameters ---------- img : ndarray The image to normalize ref_img : ndarray The referene image Returns ------- img : ndarray The image that's been normalized. """ # Get standard deviations for current and prior imgstd = img.std() refstd = ref_img.std() # Align prior standard deviation to current img = ((img - img.mean()) / imgstd) * refstd + ref_img.mean() return img
e8d02bd31884576f4ef8c65dc7a7a61685e3cece
62,874
def get_api_interfaces_name_by_type(api_interfaces, type_str, key_name='name'): """ Extract interface names from Interfaces API response by type :param api_interfaces: Interfaces API response :param type_str: Type string to match :param key_name: Optional - Key name to use (default 'name') :return: List of Interface names matching type_str """ interface_name_list = [] for interface in api_interfaces: if_name = interface.get(key_name) if if_name and interface.get('type') == type_str: interface_name_list.append(if_name) return interface_name_list
b31b554a6698114a060cf756b644abf55c2baf18
62,877
def createRegionStr(chr, start, end=None): """ Creating "samtools"-style region string such as "chrN:zzz,zzz,zzz-yyy,yyy,yyy". If end is not specified, it will create "chrN:xxx,xxx,xxx-xxx,xxx,xxx". :param chr: :param start: :param end: :return: A string of samtool-style region """ if end == None: return str(chr) + ":" + str(int(start)) + "-" + str(int(start)) elif end is not None: return str(chr) + ":" + str(int(start)) + "-" + str(int(end))
99ce4a7c26704ae11c59ee18b8f468d82bf6a182
62,878
def wrapCtr(angDeg): """Returns the angle (in degrees) wrapped into the range (-180, 180]""" # First wrap into [0, 360]; result is 360 if ctrAng < 0 but so near 0 that adding 360 rounds it ctrAng = angDeg % 360.0 if ctrAng > 180.0: ctrAng -= 360.0 return ctrAng
fda5c77288e18517035e33fc0a2dd42030cd0db8
62,879
def find(search_list: list, value: int) -> int: """ Implement a binary search algorithm. :param search_list: a sorted list of values :param value: value to search :return: index of value in the search_list """ # Raise error in case list is empty if not search_list: raise ValueError("ERROR: the search list is empty!") left, right, mid = 0, len(search_list) // 2, len(search_list) - 1 # In each step, the algorithm compares the search key value with # the key value of the middle element of the array. while left <= right: # if the search key is greater, on the sub-array to the right if value > search_list[mid]: left = mid + 1 mid = (mid + right) // 2 # if the search key is less than the middle element's key, # then the algorithm repeats its action on the sub-array # to the left of the middle element if value < search_list[mid]: right = mid - 1 mid = mid // 2 # If the keys match, then a matching element has been # found and its index, or position, is returned. if value == search_list[mid]: return mid # Value is not in search list raise ValueError("ERROR: {} not in search list!".format(value))
2fe59800f6ddc6869f26ff7bbc7bb82fabb6a1fd
62,893
import logging def get_sample2locusId(all_df, has_gene2, meta_ix, dbg_lvl=0): """ Args: all_df: all.poolcount dataframe has_gene2: list of booleans relating to genes with insertions 0.1 < f < 0.9 meta_ix: integer marking where sets begin and not metadata (Created): good_inserts_all_df: data frame which has all poolcount inserts that are within 0.1 and 0.9 frac of the gene good_locus_ids: a list of all the locus ids which have good values Returns: sample2locusId is a dict that goes from sample name (str) to a dict of locusId -> num barcodes counted in that locusId with only the good gene insertions """ if dbg_lvl > 1: logging.info("Starting to get sample2locusId") # We get a matrix of sample (col) to genes (rows) with entry being total number # of insertions within that gene if the insertions occured within 0.1 and 0.9 f good_inserts_all_df = all_df[has_gene2] good_locus_ids = good_inserts_all_df['locusId'] unq_good_loc_id = list(good_locus_ids.unique()) sample2locusId = {} # This variable is just to save computation within the upcoming cycles col_len = len(good_locus_ids) # We iterate over all the sample names (i.e. setname + index) for colname in good_inserts_all_df.columns[meta_ix:]: locusId2count = {x:0 for x in unq_good_loc_id} current_col = good_inserts_all_df[colname] for i in range(col_len): locusId2count[good_locus_ids.iat[i]] += int(current_col.iat[i]) sample2locusId[colname] = locusId2count if dbg_lvl > 1: logging.info("Finished getting sample2locusId") return sample2locusId
b61e604079e8061f07275c1ca643f783dc90e3d6
62,898
def mono_comb(n: int, r: int, mod: int = 10**9 + 7) -> int: """Binomial coefficient python 3.8 or later Parameters ---------- n n r r mod, optional mod, by default 10**9+7 Returns ------- nCr Notes ----- Time complexity O(min(r, n - r)) Examples -------- Examples -------- >>> print(mono_comb(5, 3)) 10 """ r = min(r, n - r) numer = 1 denom = 1 for i in range(r): numer *= n - i denom *= r - i numer %= mod denom %= mod denom_mod = pow(denom, -1, mod) return (numer * denom_mod) % mod
aff211b94c71d1c15b4f83416b0a0ebe669f9e7d
62,899
from typing import List def flatten(lst: List) -> list: """Reduce a nested list to a single flat list. >>> flatten(["A", [2, ["C"]], ["DE", (5, 6)]]) == ["A", 2, "C", "DE", 5, 6] True """ result = [] for item in lst: isiterable = False try: iter(item) isiterable = True except TypeError: pass if isiterable and not isinstance(item, str): result += flatten(item) else: result.append(item) return result
3837f9578d5917664c8187a1360dab4ba5fd6673
62,901
def getAlleles(ref, alt, gt): """ Given ref alt and gt, return a list of alleles at site :param ref: str Reference allele :param alt: list List of alt alleles at site :param gt: list Genotype at site :return: set Set of alleles at site """ if gt is None: return None; allAlleles = [ref] + alt; return set([allAlleles[i] for i in gt]);
2e990444790405343194197f8fd96bf5391179c8
62,906
def make_date_prefix(date): """Make an S3 key prefix from a date. Format a date as: YYYY/MM-Month/DD/ For example: 2016/09-September/15/ """ return date.strftime('%Y/%m-%B/%d/')
41f8fb5600a6d163f580da8d220c758610df4e58
62,907
def moboinfocheck(moboInfo, autoupdate, n_krig): """ Function to check the MOBO information and set MOBO Information to default value if required parameters are not supplied. Args: moboInfo (dict): Structure containing necessary information for multi-objective Bayesian optimization. autoupdate (bool): True or False, depends on your decision to evaluate your function automatically or not. n_krig (int): The number of objective functions. Returns: moboInfo (dict): Checked/Modified MOBO Information """ # Check necessary parameters if "nup" not in moboInfo: if autoupdate is True: raise ValueError("Number of updates for Bayesian optimization, moboInfo['nup'], is not specified") else: moboInfo["nup"] = 1 print("Number of updates for Bayesian optimization has been set to 1") else: if autoupdate == True: pass else: moboInfo["nup"] = 1 print("Manual mode is active, number of updates for Bayesian optimization is forced to 1") # Set default values if "acquifunc" not in moboInfo: moboInfo["acquifunc"] = "EHVI" print("The acquisition function is not specified, set to EHVI") else: availacqfun = ["ehvi", "ehvi_vec", "ehvi_kmac3d", "parego"] if moboInfo["acquifunc"].lower() not in availacqfun: raise ValueError(moboInfo["acquifunc"], " is not a valid acquisition function.") else: pass # Set necessary params for multiobjective acquisition function if moboInfo["acquifunc"].lower() in ("ehvi", "ehvi_vec", "ehvi_kmac3d"): if "refpoint" not in moboInfo: moboInfo["refpointtype"] = 'dynamic' else: moboInfo["refpointtype"] = 'static' if len(moboInfo["refpoint"]) != n_krig: msg = (f'refpoint {moboInfo["refpoint"]} should have the same ' f'dimension as the number of Kriging models ({n_krig})!') raise ValueError(msg) if 'refpointtype' in moboInfo: refpointavail = ['dynamic','static'] if moboInfo["refpointtype"].lower() not in refpointavail: raise ValueError(moboInfo["refpointtype"],' is not valid type') if n_krig == 2 and moboInfo["acquifunc"].lower() not in ("ehvi", "ehvi_vec"): msg = 'For 2-objective optimization, set "acquifunc" to "ehvi" or "ehvi_vec"' raise NotImplementedError(msg) elif n_krig == 3 and moboInfo["acquifunc"].lower() != 'ehvi_kmac3d': msg = 'For 3-objective optimization, set "acquifunc" to "ehvi_kmac3d"' raise NotImplementedError(msg) elif moboInfo["acquifunc"].lower() == "parego": moboInfo["krignum"] = 1 if "paregoacquifunc" not in moboInfo: moboInfo["paregoacquifunc"] = "EI" # If moboInfo['acquifuncopt'] (optimizer for the acquisition function) is not specified set to 'sampling+cmaes' if "acquifuncopt" not in moboInfo: moboInfo["acquifuncopt"] = "lbfgsb" print("The acquisition function optimizer is not specified, set to L-BFGS-B.") else: availableacqoptimizer = ['lbfgsb', 'cobyla', 'cmaes', 'ga', 'diff_evo', 'fcmaes'] if moboInfo["acquifuncopt"].lower() not in availableacqoptimizer: raise ValueError(moboInfo["acquifuncopt"], " is not a valid acquisition function optimizer.") else: pass if "nrestart" not in moboInfo: moboInfo["nrestart"] = 1 print( "The number of restart for acquisition function optimization is not specified, setting BayesInfo.nrestart to 1.") else: if moboInfo["nrestart"] < 1: raise ValueError("BayesInfo['nrestart'] should be at least one") print("The number of restart for acquisition function optimization is specified to ", moboInfo["nrestart"], " by user") if "filename" not in moboInfo: moboInfo["filename"] = "temporarydata.mat" print("The file name for saving the results is not specified, set the name to temporarydata.mat") else: print("The file name for saving the results is not specified, set the name to ", moboInfo["filename"]) if "ehvisampling" not in moboInfo: moboInfo['ehvisampling'] = 'default' print("EHVI sampling is not specified, set sampling to default") else: availsamp = ['default','efficient'] if moboInfo['ehvisampling'].lower() not in availsamp: raise ValueError(moboInfo['ehvisampling'], ' is not a valid option') else: print("EHVI sampling is set to ", moboInfo['ehvisampling']) if "n_cpu" not in moboInfo: moboInfo['n_cpu'] = 1 print("n_cpu not specified, set to 1") else: if moboInfo["n_cpu"] < 1: raise ValueError("BayesInfo['n_cpu'] should be at least one") print(f"n_cpu is set to {moboInfo['n_cpu']} by user") return moboInfo
c78127c24324089bf80d9dc81378b33579a829d0
62,909
def __wrap_sign_into_row(body_identifiers: dict, hand_identifiers: dict) -> dict: """ Supplementary method for merging body and hand data into a single dictionary. """ return {**body_identifiers, **hand_identifiers}
06e1145d6b48bee6c0f06e0b7311f08b2823ecbd
62,912
import mimetypes def guess_mimetype(filename: str, fallback: bool = False) -> str: """Guess a mimetype based on a filename. Args: filename: The filename to check. fallback: Fall back to application/octet-stream if unknown. """ mimetype, _encoding = mimetypes.guess_type(filename) if mimetype is None: if fallback: return 'application/octet-stream' else: raise ValueError("Got None mimetype for {}".format(filename)) return mimetype
3cbaafdb2476491c2723ab1ba776eb62abd4b8d2
62,919
def merge_residual_mapping(guide_residuals, guide_mapping, residual_construct_col, mapping_construct_col): """Join guide residual df and mapping to genes Parameters ---------- guide_residuals: DataFrame Guide-level residuals guide_mapping: DataFrame Mapping between guides and genes residual_construct_col: str Name of column with constructs in the residual DataFrame mapping_construct_col: str Name of column with constructs in the guide/gene mapping file Returns ------- DataFrame Guide residuals mapped to genes """ mapped_guide_residuals = guide_residuals.merge(guide_mapping, how='inner', left_on=residual_construct_col, right_on=mapping_construct_col) return mapped_guide_residuals
0eaa4ee53aba4b2d5088526fd06bc96d1115f20e
62,922
def _get_cache_key(account, container): """ Get the keys for both memcache (cache_key) and env (env_key) where info about accounts and containers is cached :param account: The name of the account :param container: The name of the container (or None if account) :returns a tuple of (cache_key, env_key) """ if container: cache_key = 'container/%s/%s' % (account, container) else: cache_key = 'account/%s' % account # Use a unique environment cache key per account and one container. # This allows caching both account and container and ensures that when we # copy this env to form a new request, it won't accidentally reuse the # old container or account info env_key = 'swift.%s' % cache_key return cache_key, env_key
1891eb909cfc37f02f22580e2ed589e258982afd
62,925
import torch def get_perm(N, dtype, device): """ Compute permutation to generate following array 0, 2, 4, ..., 2*(N//2)-2, 2*(N//2)-1, 2*(N//2)-3, ..., 3, 1 """ perm = torch.zeros(N, dtype=dtype, device=device) perm[0:(N-1)//2+1] = torch.arange(0, N, 2, dtype=dtype, device=device) perm[(N-1)//2+1:] = torch.arange(2*(N//2)-1, 0, -2, dtype=dtype, device=device) return perm
72cf6a05d41946a81e4289d9ea33586c1df620f5
62,928
from typing import OrderedDict def simple_reverse(in_dict): """Simple reverse dict key and value.""" out_dict = OrderedDict() for k, v in in_dict.items(): out_dict[v] = k return out_dict
eece4c22bb391a8da3119ed832353e19f7fff1e1
62,929
def get_input(prompt, operation, check=None): """ Prompt the user for input and apply ``operation`` to input. If ``check`` is not None run the check on the converted input If value is invalid it will re-prompt user """ while 1: try: value = input(prompt) value = operation(value) if check: if not check(value): raise Exception return value except (ValueError, Exception): continue
570df61b6d2b70e6754ce34c81c5346772f1777b
62,934
def padNumber(number, pad): """pads a number with zeros """ return ("%0" + str(pad) + "d") % number
8418c4c9771fd7cdc2c6adc5be34dbb12939b69a
62,937
import functools def reraises(from_exc, to_exc, when=None, make_message=None): """Reraises exception thrown by decorated function. This decorator catches the specified exception 'from_exc' in the decorated function and reraises it as a different exception 'to_exc'. The exceptions to catch can further be limited by providing a predicate which should return 'True' for exceptions that should be reraised. It allows to optionally adjust the exception's message. Parameters ---------- from_exc : type The original exception type to_exc : type The target exception type when : callable, optional A predicate that can be used to further refine the exceptions to be reraised. make_message : callable, optional Modify the original exception message. Examples -------- Reraise ValueError as TypeError with a new message: >>> @reraises( ... from_exc=ValueError, ... to_exc=TypeError, ... make_message=lambda m: m + " (I used to be a ValueError)" ... ) ... def foo(e): ... raise(e) >>> foo(ValueError("Error!")) Traceback (most recent call last): ... TypeError: Error! (I used to be a ValueError) Other exceptions are unaffected! >>> foo(RuntimeError("Error!")) Traceback (most recent call last): ... RuntimeError: Error! """ def decorator(f): @functools.wraps(f) def wrapper(*args, **kwargs): try: return f(*args, **kwargs) except from_exc as e: if when is None or when(e): msg = str(e) if make_message is None else make_message(str(e)) raise to_exc(msg) from e else: raise e return wrapper return decorator
42cfa5db9f795e0bb444fc938be7f3f1dbee41a3
62,942
def largest_divisor_five(x=120): """Find which is the largest divisor of x among 2,3,4,5""" largest = 0 if x%5==0: largest = 5 elif x%4==0: largest = 4 elif x%3==0: largest = 3 elif x%2==0: largest = 2 else: ## when all other (if, elif) conditions are not met return "no divisor found for %d" %x ## each function can return a value or a variable return "The largest divisor of %d is %d" %(x, largest)
2747f59faaad7ae9c0ed5ff99f7c2d76ecaafe85
62,950
def next_marker_by_id(collection, limit, marker): """ Returns the next marker based on the limit-1 item in the collection :param collection: an iterable containing the collection to be paginated :param limit: the limit on the collection :marker: the current marker used to obtain this collection :return: the next marker that would be used to fetch the next collection, based on the collection item ids """ return collection[limit - 1]['id']
447889d9bd333888bfdd41a7b51901c3c556e3fc
62,957
def attending_info_detect(in_data): """Detect if the email address is validate or not See if the email address include the @ sign to determine if it is a valid email address Args: in_data (dict): The dictionary that includes the attending's email address Returns: str or True: Indicate if it is a valid email address """ good_email = "@" in in_data["attending_email"] if good_email is not True: return "You entered a invalid email address, " return True
2ebeb96049befcd6200bba6fb76cf8709a96bf10
62,961
def cut_indices_of(array, cut): """ Calculates the indices of the elements on the given cut for the given matrix. Where a diagonal runs from top left to bottom right, a cut runs from bottom left to top right. :param array: 2D array :param cut: index of the cut (cut 0 is the single element of the top left) :return: the indices to retrieve the cut """ if array.ndim != 2: raise RuntimeError("array should be 2D") h, w = array.shape if cut < 0 or cut >= w + h - 1: return range(0, 0), range(0, 0) cut_length = cut + 1 - max(0, cut - h + 1) - max(0, cut - w + 1) if cut < h: return range(cut, cut - cut_length, -1), range(0, cut_length) else: return range(h-1, h-cut_length-1, -1), range(cut - h + 1, cut - h + 1 + cut_length)
276cac460b64b88fa4c224da10fb55cb93c47509
62,963
def dom_level(dns_name): """ Get domain level """ return dns_name.count(".")
20d54dd98378f377485149bbb9854b6d2001ab55
62,966
def rivers_with_station(stations): """Created a sorted list of Rivers with stations on them""" # Initialise rivers list rivers = [] # Add river to list from station, if river is not present for station in stations: if station.river in rivers: pass else: rivers.append(station.river) # Sort list rivers.sort() return rivers
cd515483aa56d2c9fec767234b22d0993bca3725
62,971
import decimal def _add_percentage_to_progress_bar(progress_bar, count, total): """Add the percentage to the progress bar. Parameters ---------- progress_bar : str The bar component of the progress bar, as built so far. count : int The number of cycles completed. total : int The total number of cycles to complete. Returns ------- str The progress bar, with percentage appended if appropriate. """ operation_is_not_finished = count != total if operation_is_not_finished: progress = count / total if total > 0 else 1 percentage = progress * 100 # Round the percentage down so that it is never shown as 100% before # the operation is finished. rounded_percentage = decimal.Decimal(percentage).quantize( decimal.Decimal("0.0"), rounding=decimal.ROUND_DOWN, ) progress_bar += " {}%".format(rounded_percentage) return progress_bar
7ab1ae33652e158eae04379944819c103383aec7
62,975
def format_month_interval(val): """ Format a MonthInterval value. """ return f"{int(val)}M"
28ac3d457dab6c4c877d15b137a26930180c389e
62,977
def weighted_count(pdf): """ Return weighted count of items in Pandas DataFrame. """ return pdf['s006'].sum()
083cc2a10f829c2b863224367d360cc2c1a8b0ed
62,983
def build_dsn_string(db_settings): """ This function parses the Django database configuration in settings.py and returns a string DSN (https://en.wikipedia.org/wiki/Data_source_name) for a PostgreSQL database """ return "postgres://{USER}:{PASSWORD}@{HOST}:{PORT}/{NAME}".format(**db_settings)
4d4d14907f76f1a739020f5ca29576d20bb7fdbf
62,986
def chomp( s ): """Return string without terminal newline if present""" return s[:-1] if s.endswith('\n') else s
247415db1784cba1b99a5c20048487c7801130dd
62,988
import logging import re def get_encoder_and_decoder_params(model): """Filter model parameters into two groups: encoder and decoder.""" logger = logging.getLogger(__name__) enc_params = [] dec_params = [] for k, v in model.named_parameters(): if bool(re.match(".*conv1.*|.*bn1.*|.*layer.*", k)): enc_params.append(v) logger.info(" Enc. parameter: {}".format(k)) else: dec_params.append(v) logger.info(" Dec. parameter: {}".format(k)) return enc_params, dec_params
4a6fbc25d0cf08f1b9511c981af8abdc55f63ae8
62,993
def swap_places_colon(ingredient): """Split string `ingredient` by colon and swap the first and second tokens.""" components = ingredient.split(':') if len(components) <= 1: return ingredient else: return '{} {}'.format( swap_places_colon(':'.join(components[1:])), components[0])
f6051ea7611d0bf7edc79c88db2d2369917c2690
62,998
def time_delta(faker): """Time delta.""" return faker.time_delta(1)
eecc214d272d28732dd7d330c36ed06daeec284a
62,999
import pprint def format_for_leo(obj): """ Convert obj to string representiation (for editing in Leo)""" return pprint.pformat(obj)
f552bbbaafa0c229bad6ef6c5a8e2fed89330f08
63,001
def get_group_list(project, client): """Return a sorted list of groups for project.""" groups = client.get(f"/api/projects/{project['pk']}/groups/") groups = sorted(groups, key=lambda x: x["pk"]) return groups
921b95851b6ccc9468d5158f78997f47b022bc3c
63,005
def atf_fc_uri(article_uri): """URI of feature collection""" return article_uri+"/featurecollection"
c725642309955795b5558b638146b782c7f51d0b
63,018
def infer_ap_func(aperiodic_params): """Infers which aperiodic function was used, from parameters. Parameters ---------- aperiodic_params : list of float Parameters that describe the aperiodic component of a power spectrum. Returns ------- aperiodic_mode : {'fixed', 'knee'} Which kind of aperiodic fitting function parameters are consistent with. """ if len(aperiodic_params) == 2: aperiodic_mode = 'fixed' elif len(aperiodic_params) == 3: aperiodic_mode = 'knee' else: raise ValueError('Aperiodic parameters not consistent with any available option.') return aperiodic_mode
259677e4ece98961e8016d505e9047ae99b13289
63,019
from typing import Any def identity(value: Any) -> Any: """Given a value, return the exact same value""" return value
4335555cc3d66b7ec5c3215915c46dda8c4e1a77
63,020
def col(label: str) -> int: """Return the correct index given an Excel column letter.""" if not label.isalpha(): raise ValueError(f"'{label}' is not a valid column label.") return ( sum( (ord(char) - ord("A") + 1) * (26 ** position) for position, char in enumerate(reversed(label.upper())) ) - 1 )
423cb4d431dcbe5ae8b9ee0e9e53fabecf44d7da
63,024
def lsystemToDrawingCommands(draw, s): """ :param draw: :param s: :return commands: Takes a dictionary, draw, of character->turtle instuctions, and a L-system string, s. Uses draw to map the string to drawing commands, and returns a list, commands, of those commands. """ commands = [] for character in s: if draw.get(character): commands.append(draw[character]) return commands
0b7a00d40b69d143746b9dbbc06b77c08e9455dd
63,028
def field_name(field): """ :param field: Tupla que tiene el nombre y valor de un campo del documento original. :return: El nombre del campo. """ return field[0]
c3be05723cbd8a627e0b98c25628d61b04038e4b
63,030
import hashlib def get_hash(file): """ Computes md5 hash for a file to detect duplicates :param file: uploaded file :return: Hex hash """ s = hashlib.md5() with open(file, 'rb') as f: for line in f: s.update(line) return s.hexdigest()
31ba5a4515c850893d0d5428d43cb1b65aafe3ea
63,032
def get_graph(graph): """ Get correct graph due to data parallel :param graph: network graph :type graph: torch.nn.Module :return: correct graph :rtype: torch.nn.Module """ if hasattr(graph, 'module'): # fix DataParallel return graph.module else: return graph
1f9ba8de96359ffd58f422e1063b923fb14c4d1a
63,034
def EntryToHostName(entry): """Extracts the buildbot host name from the slaves list entry. The slave list entry is a dict.""" return entry.get('hostname', None)
84d21e15418f4b632a0fb05978490ecec3e64377
63,036
def yes_or_no(true_or_false): """A convenience function for turning True or False into Yes or No, respectively.""" if true_or_false: return "Yes" else: return "No"
be45e1dbc18451cf8df0f4513dfa49c82f7dc88e
63,038
def handle_content_properties_information(element: object) -> dict: """ Handle API response 'properties' information. Args: element (object): An XML element hierarchy data. Returns: dict: Transformed dictionary of properties information. """ data = {'Name': element.findtext('Name')} # type: ignore properties = {} for share_property in element.findall('Properties'): # type: ignore for attribute in share_property: properties[attribute.tag] = attribute.text data['Properties'] = properties # type: ignore return data
cd60d70cd7d5e6ca5ad622b1a73c3d879ba29896
63,039
def remove(src, rel, dst): """ Returns an SQL statement that removes edges from the SQL backing store. Either `src` or `dst` may be specified, even both. :param src: The source node. :param rel: The relation. :param dst: The destination node. """ smt = 'DELETE FROM %s' % rel queries = [] params = [] if src is not None: queries.append('src = ?') params.append(src) if dst is not None: queries.append('dst = ?') params.append(dst) if not queries: return smt, params smt = '%s WHERE %s' % (smt, ' AND '.join(queries)) return smt, params
61af56d70d4fb2e6d56225c23de1fdcc3c6ec35a
63,040
def transfer_driver_cookies_to_request(cookies): """ Extract the cookies to a format that the request library understands :param cookies: This should be a driver cookie. Obtained with the command my_driver.get_cookies() :type cookies: dict :return: Cookies dictionary suitable for a requests lib object :rtype: dict """ return {i['name']: i['value'] for i in cookies}
b81df474c731f939421852bf2f719fee73c9d3c5
63,049
def to_bits(_bytes: bytes) -> list: """Convert bytes to a bit list""" bits = [] offset = 0 for byte in _bytes: for i in range(8): bits.insert(0+offset,(byte >> i) & 1) offset += 8 return bits
157d814dede3bf2e261067f6374ceed1ed7f7697
63,053
def _GetChannelSet(five_g, width): """Returns a tuple of target channels based on spectrum and width given. Args: five_g: (bool) Whether target is 5GHz radio. width: (int) Channel width, eg. 20, 40, 80. """ if five_g: if width == 20: return (36, 40, 44, 48, 52, 56, 60, 64, 100, 104, 108, 112, 116, 120, 124, 128, 132, 136, 140, 144, 149, 153, 157, 161, 165) elif width == 40: return (36, 44, 52, 60, 100, 108, 116, 124, 132, 140, 149, 157) elif width == 80: return (36, 52, 100, 116, 132, 149) # we return 2.4G channels otherwise. return (1, 6, 11)
9b5436266a47d52eced41ac8e90471c3cf0dc9f9
63,057
def _flip_bits_256(input: int) -> int: """ Flips 256 bits worth of `input`. """ return input ^ (2**256 - 1)
31e7211330f7d5285b8677f585c460cb903ba113
63,068
import requests import json def get_driving_distance(start_point, end_point): """Gets the driving distance (km) from the start point to the end point (input in [lat, long]).""" # call the OSMR API - needs [long, lat] r = requests.get( f"http://router.project-osrm.org/route/v1/car/{end_point[1]},{end_point[0]};{start_point[1]},{start_point[0]}?overview=false""") # then you load the response using the json libray # by default you get only one alternative so you access 0-th element of the `routes` routes = json.loads(r.content) route_1 = routes.get("routes")[0] driving_distance = route_1["distance"] / 1000 return driving_distance
49551b08a127e33c36117d847155f4c5144be01c
63,070
def fwhm_dict(fwhm): """Convert a list of FWHM into a dictionary""" fwhm = [float(f) for f in fwhm] return {'x': fwhm[0], 'y': fwhm[1], 'z': fwhm[2], 'avg': fwhm[3]}
6192adfff7f2e3c5f5e30671929e59c6e4a6ced4
63,071
import yaml def ordered_dict_representer(dumper, data): """ Represents OrderedDict for yaml dumper. """ values = [] for item_key, item_value in data.items(): node_key = dumper.represent_data(item_key) node_value = dumper.represent_data(item_value) values.append((node_key, node_value)) return yaml.nodes.MappingNode(u'tag:yaml.org,2002:map', values)
b2ef51cc7b45e2860f8522e877641aecf50b77af
63,077
def merge_overlapping_dicts( dicts ): """ Merge a list of dictionaries where some may share keys but where the value must be the same """ result = {} for mapping in dicts: for key, value in mapping.items(): if key in result and result[ key ] != value: raise Exception( "Key `{}` maps to both `{}` and `{}`".format( key, value, result[ key ] ) ) result[ key ] = value return result
34bd96af4847e060799c38b68fde0306171a9631
63,078