content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
def find_all(str_:str, key:str): """ Returen all the starting indices of string `key` in string `str_`. Example: ---------- >>> find_all("abcaa", 'a') [0, 3, 4] """ p, indices = -1, [] while True: p = str_.find(key, p + 1) if p < 0: break indices.append(...
1f8ea4f3a7a71c83605441189c93ecdd104248f1
629,097
def _token_symbols(token_list): """Given a list of tokens, returns a list of their symbol names.""" return [token.symbol for token in token_list]
e45e2a694332461ddf89804d387829a2263a2c66
629,098
def _use_cfg_in_finalize(opt): """ Return True if the cfg_t parameter is used in the finalize function. """ if opt.algorithm == opt.algo_bit_by_bit: if opt.width is not None and opt.poly is not None and opt.reflect_out is not None and opt.xor_out is not None: return True elif opt...
e6f6f3f8bb6e24c82e329ffeb0b3fe76dfb08561
629,100
def modes(df): """ :param df: dataframe :rtype: string """ if len(df) > 1: return 'lines' else: return 'markers'
5e4b77ce84b8f759e02e867475e6c356e46d34b5
629,101
def formatannotation(annotation, base_module=None): """ This is taken from Python 3.7's inspect.py; the only change is to add documentation. INPUT: - ``annotation`` -- annotation for a function - ``base_module`` (optional, default ``None``) This is only relevant with Python 3, so the doct...
8d4887774f5c940796f822cedeeaf562a4d6c290
629,104
def occlude_and_predict(X_arr, A_arr, masks, thresh, model): """ COPIES and mutates input data Returns predicted CLASS (not prob.) of occluded data """ #Copy node features. We need to edit it. X_arr_occ = X_arr.copy() #Occlude activated nodes for each explain method #NB: array shape is...
fb6c22566af4ea870a9c6720bd9aff50b55c445e
629,105
def bytes2human(size, *, unit="", precision=2, base=1024): """ Convert number in bytes to human format. Arguments: size (int): bytes to be converted Keyword arguments (opt): unit (str): If it will convert bytes to a specific unit 'KB', 'MB', 'GB', ...
e35db9550ab2ff5a9ddc24903e29e5f21f66b465
629,106
import copy def apply_diffs(diffs, manifest): """ Apply a series of differences to a manifest diffs is an list(diffs) of list(diff) of dict(change item) """ manifest = copy.deepcopy(manifest) # helper which removes the 'status' key from a diff key_filter = lambda item : { key : value for key, va...
b9a465251cd859aefc7c55345eee096103c800ef
629,108
def bin_ent(logits_tensor): """Computes the binary entropy of a tensor of independent log probabilities. :param torch.Tensor logits_tensor: A tensor of log independent Bernoulli parameters. All elements should be nonpositive. shape arbitrary. :returns: A tensor of the same shape c...
9f3826b19bd9f519681a9d54bd5127aa5751fe8c
629,110
def boolean(obj): """ Convert obj to a boolean value. If obj is string, obj will converted by case-insensitive way: * convert `yes`, `y`, `on`, `true`, `t`, `1` to True * convert `no`, `n`, `off`, `false`, `f`, `0` to False * raising TypeError if other values passed If obj is non...
f2172b0d4c5794425a11a28705de81871a6fbe36
629,111
import os import re def create_aws_cluster(cluster_name="mycluster"): """Creates a cluster. The cluster is created using the cluster cli, a configuration and a name. If a cluster with the given name already exists nothing is done. Args: cluster_name: A string name of the cluster to b...
8a3e7420686a430f842ec05b161cb7190dbee5cf
629,112
from operator import mod def is_islamic_leap_year(i_year): """Return True if i_year is an Islamic leap year.""" return mod(14 + 11 * i_year, 30) < 11
d7c20c674ee2e93423adf3c3307bfa73f0716efc
629,113
def size_str_to_num(s): """ parses 'maxsize' input """ suffix_one = {'M':10**6, 'G':10**9} suffix_two = { x + 'B': suffix_one[x] for x in suffix_one.keys()} if s[-1] in suffix_one: txtnum = s[0:-1] pwr = suffix_one[s[-1]] elif s[-2:] in suffix_two: txtnum = ...
27fba75eac1137cca3d1070946c9900e95aed621
629,114
import os def is_valid_config_file(file_path: str) -> str: """ Validate the path to the configuration file. :param str file_path: the path to the config file :rtype: str :return: the validated file path :raises ValueError: if the path is not valid """ if not os.path.isfile(file_path):...
4ae81a1a4983981946c7483cb739aeb090dc015a
629,115
def config_to_string(config, html=False): """ docstring """ print_ignore = ['weights_dict', 'optimizer_dict'] args = vars(config) separator = '<br>' if html else '\n' confstr = '' confstr += f'------------ Configuration -------------{separator}' for k_val, v_val in sorted(args.items(...
c031d6ecc21b16c67ef0cbda25364888029bf635
629,116
def _split_up_multiple_entries(entry): """Split up lists of entries that have been recorded as a single string.""" split_types = ['<br>', '<br/>', '<br />'] for split_type in split_types: if split_type in entry: return entry.split(split_type) return [entry]
b9309269c72adc245597b1359c90476efc5e75f6
629,117
import requests def get_applicable_news_categories(resource_uri, category_names): """ Checks which of the given category_names are applicable to the given news article (given by resource_uri). Crawls the wikinews website and searches for the category_uri in the original HTML code (which contains link...
cf6f162ef36e00f4247983c36c489c87f8632972
629,118
import subprocess def check_output(cmd, **kwargs): """ Simple backport of subprocess.check_output() from python 2.7. """ p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, **kwargs) out, err = p.communicate() if p.retu...
68998caf231a22829e5dafaf319be89323700477
629,119
def fibonacci(n): """Return nth term in fibonacci sequence Parameters ---------- n: int nth term in fibonacci sequence to calculate Returns ------- int: int nth term of fibonacci sequence, equal to sum of previous two terms Examples ...
9ef3df4ea1d2ca1eb77a645db438031d4bc4748e
629,121
import inspect def get_all_args(fn) -> list: """ Returns a list of all arguments for the function fn. >>> def foo(x, y, z=100): return x + y + z >>> get_all_args(foo) ['x', 'y', 'z'] """ sig = inspect.signature(fn) return list(sig.parameters)
bb5b90f978f62ab96124b290ad243602b4cced0c
629,122
import typing def _remove_arg( source: typing.List[str], flag: str, has_value: bool, ) -> typing.List[str]: """ Search for and remove the specified flag within the source arguments. This function removes it and its optional value if has_value is specified, returning a copy of the source l...
e85035c7d88b180f47c29cf3d5b2b051570f3a64
629,123
def canBalance(arr): """ Determine if a list of numbers is balance. Parameter: arr := list of numbers Return: True if a split position can be found in the arr such that both halves sum of numbers are equal. False otherwise. Assuming numbers can be integers or float...
17b6c2bd1163708c420b5e4f3d132f4abaae1f35
629,124
def have_proper_bundles(args): """ boolean to indicate we have pickled bundles""" return (hasattr(args, "pickle_bundles_dir") and args.pickle_bundles_dir is not None)\ or (hasattr(args, "unpickle_bundles_dir") and args.unpickle_bundles_dir is not None)
2c9e066fe7abc4fff2a66a224d558c753eecb144
629,125
import itertools def std_from_mean_kde(data): """ Plot the KDE of the pandas series along with vertical reference lines for each standard deviation from the mean. Parameters: - data: pandas Series with numeric data Returns: Matplotlib Axes object. """ mean_mag, st...
d16d3945f4d7d1d0ee7a6ead20e78ced8d288e47
629,126
def makeopendir(fs, directory): """ Creates and opens the given directory in the given PyFilesystem. """ if not fs.isdir(directory): fs.makedir(directory) return fs.opendir(directory)
684e69f18123e9ebf257aa231f69e36bbe02e711
629,128
import os import sys def getexepath(): """ 返回可执行程序的当前路径。 sys.argv 中保存了可执行程序的全路径 :return: """ return os.path.split(os.path.realpath(sys.argv[0]))[0]
8bc3530fc3e0fd1ccb1ee0c512cd14b3d5987c8b
629,129
import functools def patch(cls, attr): """Patch the function named attr in the object cls with the decorated function.""" orig_func = getattr(cls, attr) @functools.wraps(orig_func) def decorator(func): def wrapped_func(*args, **kwargs): return func(orig_func, *args, **kwargs) ...
cafd5a15e2c3f1c50614073003134727c3d81a62
629,130
from datetime import datetime def current_date(): """Returns the UTC time now as a `datetime.datetime` object.""" return datetime.utcnow()
a4672cef69477f464815003cac4a5ed81d07464d
629,132
def hjertingComponents(): """//Hjerting function components (expansion coefficients in Voigt fn "a" parameter): // Observation and Analysis of Stellar Photospehres -, 3rd. Ed., Tab 11.5, p. 256 // David F. Gray""" #//Note: "u" is the Voigt fn "v" parameter numV = 81 #//Row 0 containt absc...
15add85aa8875dce122536ec555ee51a9e933777
629,133
import re def findReadPosition(fullAssembly, read, label=''): """Finds the index of a given target (read) inside the context (fullAssembly) ========================================= context -------------- target ^ ^ startIndex ...
6d839ea2974f32e84d5b36c3e908255d7a6a631b
629,134
def find_by_file(dbo, filename): """ Look up the id for a filename of image """ rv = dbo.find_one({'filename': filename}, {'_id': 1}) return rv['_id'] if rv else None
4f1219936d26e64be6b0f88f4101cb2691316e69
629,135
def quantize_float(f, q): """Converts a float to closest non-zero int divisible by q.""" return int(round(f / q) * q)
28a7170b3c1d2d8e7c0d9dc36ae8bc1b31c01165
629,136
def generate_avatar_path(obj, filename): """ Generates an unique path to user's avatar dir according to user's id. """ return 'images/avatars/' + str(obj.id) + '/' + filename
a68f1761d2f1aeb94a2565816cb7cac8a2d076e0
629,137
import re import sys def checkElandFile(filin): """Check ELAND alignment file given by user""" try: for line in open(filin ,'rU'): # Old ELAND format if re.search('^[!-~]+\t[ATGCNatgcn.]+', line): return 'old' # New ELAND format elif re.s...
97a7b78d82aa7aa371573641eae0a917083c2b56
629,138
def merge_two_dicts(starting_dict: dict, updater_dict: dict) -> dict: """ Starts from base starting dict and then adds the remaining key values from updater replacing the values from the first starting dict with the second updater dict. Thus, the update_dict has precedence as it updates and replaces the...
b9df7f3bf7785c67198ec0f282e89d51f25d153a
629,140
def assign_autonlevel(x): """ df.apply(lambda x: x) support function Provides logic and return value for autonomy level category value grouping. """ auto_cats = ['semi autonomous', 'autonomous', 'piloted semi autonomous', 'piloted', 'undisclosed'] # type conversion x = ...
007c239eb07362d5674eb8fe8c782bdde08000fe
629,141
def presale_crowdsale(chain, presale_fund_collector, uncapped_flatprice, team_multisig): """ICO associated with the presale where funds will be moved to a presale.""" presale_fund_collector.transact({"from": team_multisig}).setCrowdsale(uncapped_flatprice.address) return uncapped_flatprice
912b59facdf5009a1841b04811c2b3e83f8e4b16
629,142
def flows_from_flowCollection(flow): """FlowgramCollection from array of pos x seq: names are integers. This is an InputHandler for FlowgramCollection. It converts an arbitrary array of numbers into Flowgram objects and leaves the flowgrams unlabeled. """ return flow.flows, flow.Names, [f.heade...
5c02f91bd4b1ee68dc2e2ccff1bfe9d01f94c9db
629,144
def get_parity_check_matrix(): """Stores the parity matrix in one place""" parity_check_matrix = ['0001111', '0110011', '1010101' ] return(parity_check_matrix)
1ec22b41635259f35c5af9c847942f0d5a440d65
629,145
import torch def GSIRRU(input_a, input_b, n_channels: int): # best and fastest converging unit, uses a lot of VRAM. """Gated[?] SIREN ReLU Unit (GSIRRU)""" in_act = input_a+input_b in_act[:, :n_channels, :].detach().mul_(16) # modify tensor WITHOUT telling autograd. t_act = torch.sin(in_act[:, :n_chan...
be112d54dcaea96076722ddd9afdf3557e5674cc
629,146
def calc_posteri_prime(posteri_snr): """Calculates the posteri prime Parameters ---------- posteri_snr : ndarray The signal-to-noise ratio of the noisey signal, frame by frame. Returns ------- posteri_prime : ndarray The primed posteri_snr, calculated according to the re...
6e5b54bb747fe67a543e63199f1972b14107cfa5
629,148
import textwrap def _duration_to_string() -> str: """ Generate the code for serializing durations to strings. :return: generated code """ return textwrap.dedent( '''\ _ZERO_TIMEDELTA = datetime.timedelta(0) def _duration_to_string( duration: datetime.timedelta) -> st...
c9bbeea30fc5eaee9551051ca68eb5cb5485ff38
629,149
def truncate(f, digits): """truncate. Args: f: digits: """ return ("{:.30f}".format(f))[:-30+digits]
92ce44c8ed49199a9ad4073e52fb8349584ae59d
629,150
import signal import os def killme_after(delay, loop, sig='SIGINT', pid=None): """ :param delay: delay in seconds to execute signal :param loop: asyncio event loop :param sig: signal (string), must presents in signal package :param pid: PID (default is current PID) :return: """ if not ...
d5191f4e6340412db93719b06bb6966c69a71dc1
629,151
def extract_important_feature(prevfeat, curfeat): """ Return the most important feature from gff """ priority = {"CDS": 4, "exon": 3, "mRNA": 2, "gene": 1} prevprior = priority.get(prevfeat, 0) curprior = priority.get(curfeat, 0) if curprior == 0 and prevprior == 0: return "interge...
dd498d2123478e823d02690a384a42c70609724f
629,152
import re from typing import Tuple from typing import Optional def get_year_data(match: re.Match, mixed: bool = False) -> Tuple[int, Optional[int]]: """Get year data from match.""" if mixed: year_string, *_ = match.groups() else: _, year_string, *_ = match.groups() if "-" in year_str...
dbe2f81f6d90b282c7eb5904d12e685ae68c4b11
629,153
def dot(p1, p2): """Dot product 4-momenta""" e = p1[0] * p2[0] px = p1[1] * p2[1] py = p1[2] * p2[2] pz = p1[3] * p2[3] return e - px - py - pz
54ed5f7aced40877bddb3257540741ab615186f6
629,154
import shlex def string_to_tokens(s): """ Converts string to list of tokens, with support for quotes. Defined here for convenience. See shlex documentation for more information on parsing rules: https://docs.python.org/2/library/shlex.html#parsing-rules :param s: string "a b 'c d' e" :re...
454c34be86b558f4afaadb26260b2160d71ecbe3
629,155
def categorical_accuracy(preds, y): """ Returns accuracy per batch, i.e. if you get 8/10 right, this returns 0.8, NOT 8 """ top_pred = preds.argmax(1, keepdim = True) correct = top_pred.eq(y.view_as(top_pred)).sum() acc = correct.float() / y.shape[0] return acc
a07779bb8f308e149d0fe58e9885927afb91053b
629,157
import pickle def load_pickle(path): """ load the dictionary data :param path: the path we save the data. :return: data as a dictionary. """ pkl_file = open(path, 'rb') data = pickle.load(pkl_file) pkl_file.close() return data
fe812d5c4d088987967636672f1f78a144449537
629,159
from typing import Any def check_valid_category_name(child: Any): """Returns true if category name is valid, false otherwise.""" return (child.find('name') is not None and child.find('name').text is not None and child.find('categoryPath') is not None and len(child.find('categoryPath')) > 0 and ...
6dc781a8142c670df0482b93a57b55cb520b3aab
629,160
def in_list(collection_list): """Return true if test is in collection""" if "test" in str(collection_list): return True else: return False
28fbd8a1fbf5f877775a481b768d2aa121e55499
629,162
def overlay_image_alpha(img, img_overlay, pos, alpha_mask): """Overlay img_overlay on top of img at the position specified by pos and blend using alpha_mask. Alpha mask must contain values within the range [0, 1] and be the same size as img_overlay. Ref: https://stackoverflow.com/questions/14...
532f4183c06d2edf0e5a6fc84b339b7307f475ee
629,163
def accel(t0, state, k): """Constant acceleration aligned with the velocity. """ # requires modification and validation v_vec = state[3:] norm_v = (v_vec * v_vec).sum() ** .5 return 1e-5 * v_vec / norm_v
9a4f215f3c76447b773983b9cf02a8b83c521602
629,164
def library_dilution_calculator_fixed_volume(concentration, size, ul): """Calculate ng per sample (based on given ul_sample) needed for multiplexing.""" nM_DNA = (float(concentration)*(10.0**6.0))/(660*float(size)) ng_sample = (660*float(size)*nM_DNA*ul)/(10.0**6.0) return ng_sample
956533c26991cc8a19ad09bd400d46762e39342f
629,165
def _format_timedelta(timedelta): """Convert timedelta to string, lopping off microseconds.""" # This approach probably looks awful to all you time nerds, but it will work # in all the locales we use in-house. return str(timedelta).split('.')[0]
d0714efaa5a4138a40d9a25394e24852344a50f0
629,166
def genPPG(prices, weights): """ Generates low and high price per gram amounts for an item returns an array, with first element being low, and second element being high if there is only one variant of an item, a single element array will be returned """ try: assert(prices...
0502e1206da85009a7051584718d5bebf416ece2
629,167
def get_dimension_filt(C): """ get dimension filtration data from bats complex """ spxs = [] ts = [] for d in range(C.maxdim() + 1): ts.extend([d for _ in range(C.ncells(d))]) spxs.extend(C.get_simplices(d)) return spxs, ts
465b050f1e18f196b6c05c2b75277a56d1bf79dd
629,168
def count_cell_entries(df, col_name='', output_col_name=''): """ Returns pd.value_counts() as a DataFrame Parameters ---------- df : Pandas Dataframe Dataframe on which to run value_counts(), must have column `col`. col : str Name of column in `df` for which to generate counts ...
014da61eca2bfcff49e8136243fb0884036f43f3
629,169
def _canonical_to_natural(mu, sigma_squared): """convert from canonical to natural gaussian parameters""" n1 = mu / sigma_squared n2 = -0.5 * 1 / sigma_squared return n1, n2
fa0089a1ab733dbdd63b9ee2b08353df2f91f928
629,170
def add_carry_bits(res, carry, MASK=0xFFFFFFFF): """Adds bits at each position 1 + 1 = 0 1 + 0 = 1 Examples: >>> res, carry = int("0101", 2), int("0011", 2) >>> bin(add_carry_bits(res, carry)) '0b110' """ return (res ^ carry) & MASK
e56c253b5eec5dd8f51164171c023cb041439222
629,171
import json def is_string_json_loadable(string: str): """ Determine if the serialized dictionary is a JSON object. Rather than constructing a complicated regex pattern, a simple try/except of the json.load should suffice. """ try: json.loads(string) return True except json.JSO...
818b41c3a1bfb582b29b906b179ff3087cb8f937
629,172
import struct def byte2py_int(data): """ Converts byte to Python int value. """ return struct.unpack('B', data)[0]
8934fe55225e2fb33fd5272b1060ee4079044051
629,173
def _get_interval_domain_min(dom): """ Get the lower bound of an interval domain Args: dom: Domain Returns: Domain min value """ return dom[0] if isinstance(dom, tuple) else dom
db17a8725eea1d4ffc62122309d33bcbb4c9a25f
629,174
def create_decompose_file_name(hw_details, decompose_param_obj): """ Creates file name for output of decompose process using hw_details_class obj and schedule_param obj """ fname = "" fname += str(hw_details.tree_depth) fname += str(hw_details.n_tree) fname += decompose_param_obj.str_fname() return...
1c8436c60790a1e2fcf0d5ea6ac7c8c318f8413b
629,175
def CustomRequestHandler(environ, start_response): """ This request handler echoes request body in response body. """ # Get `Context-Length` header value content_length_text = environ['CONTENT_LENGTH'] # If header value is empty if not content_length_text: # Set content length be 0 ...
12aa17113f308309a94d86261f2f7749e81885b9
629,176
import re def to_snake(string): """ Converts to snake case. :param string: A target string. :return: Converted string. """ return re.sub(r'(?<!^)(?=[A-Z])', '_', string).lower()
845bd2fec36c721cc792b283369a0dd6ab52a61b
629,177
def with_metaclass(mcls): """ For metaclass compatibility between Python 2 and 3. cf. http://stackoverflow.com/questions/22409430/portable-meta-class-between-python2-and-python3 """ def decorator(cls): body = vars(cls).copy() # clean out class body body.pop('__dict__', None)...
a7899592615a3bf5eb05e50ff81c880711efd4ba
629,178
import inspect def get_keyword_names(obj): """Returns a list of method names for the given object This excludes methods that begin with an underscore, and also excludes the special method `get_keyword_names`. """ names = [ member[0] for member in inspect.getmembers(obj, inspect.is...
2de0ad018fb2742cbe1d1fbebf6c0a621f1ab1f2
629,179
import re import os def rootcint_builder(target, source, env): """ Call rootcint (for ROOT < 6) or rootcling (for ROOT >= 6) to generate a ROOT dictionary from the given headers in 'source'. Any relevant -D definitions and -I include directives are taken from $_CCCOMCOM. The ROOT version is expect...
eca8d43d5bf3e8ae2fba937df5d6e60cf1ab3ff8
629,180
from typing import Optional def parse_key(headers) -> Optional[str]: """ Parses the header for an API key, and returns it if found. The authorization header must be in the following format: ``Token <api key>``. :param headers: A dictionary of request headers :return: If present, the key pa...
cda11fd0afa08fb3a85ed457b913f4e32d229c1f
629,181
def _receptor_standard_config(config): """Set standard config for network with receptor layer.""" config.data_dir = './datasets/proto/relabel_200_100' config.receptor_layer = True config.ORN_NOISE_STD = 0.1 config.kc_dropout_rate = 0. config.lr = 1e-4 # For receptor, this is the default LR ...
401111613a11255b3b3768c7c3e19ac57fb6a896
629,182
import pandas as pd import numpy as np def _read_files_to_process(file_paths, n_per_class, random_state): """Local function to read in files to process """ # If we have one file only just read and randomly sample it. if len(file_paths) == 1: return pd.read_csv(file_paths[0]).sample(n=n_per_c...
81bff4d4891da4188a252c70ecf29bfc05b03da7
629,183
import time from datetime import datetime def utc2local(utc_st): """ UTC时间转本地时间(+ 8: 00)""" now_stamp = time.time() local_time = datetime.fromtimestamp(now_stamp) utc_time = datetime.utcfromtimestamp(now_stamp) offset = local_time - utc_time local_st = utc_st + offset return local_st
cc50975a97d8c25425babc2cde50bacfcf76ed36
629,184
def validate_both(first_validator, second_validator): """Make sure both validators pass""" def validate(cursor_trail, tree): return (first_validator(cursor_trail, tree) and second_validator(cursor_trail, tree)) return validate
5f9fbe3663614661c02004b76ade546abbdba416
629,187
import logging def experimental(cls): """Decorator which indicates that module is experimental. Use it to mark experimental or research modules. """ def wrapped(x): """Wrapper function.""" logging.warning( f"Module {x} is experimental, not ready for production and is not f...
17efe9fd7143aff3ba99a93b5a4c049d4e1598cc
629,188
import re def _tokenize(stuff): """ >>> print(" ".join(_tokenize("One, Any (1911-)"))) 1911 any one """ return sorted(set( re.sub(r'\W(?u)', '', part.lower(), flags=re.UNICODE) for part in stuff.split(" ")))
de071f1494f183bbcff41a29e37f222735534889
629,189
def report_dockerfile(filename): """ Report DockerFile if it contains ENTRYPOINT in uppercase. """ with open(filename) as f: for line in f: if 'ENTRYPOINT' in line: #print('\tDockerfile found with ENTRYPOINT:', filename) #print('\t\t', line.strip()) return line.strip()
fc7b5572d1695327f2fded957b8f2475d354f658
629,190
def create_shown_name(obj): """ This takes the main name, or if there's a Bayer/Flamsteed designation, assemble a string from that. """ things = [] if obj.catalog.name in ['Bayer', 'Flamsteed']: try: return "{} {}".format(obj.id_in_catalog, obj.object.constellation.a...
0a7e6080aa2ed0c651a359a21d3c48a6a2d35104
629,192
import os def _get_name_ext(file): """ Split a file name in name and extension. Args: file (str): Full file path. Returns: tuple (str, str), name and extension. """ _, name = os.path.split(file) return os.path.splitext(name)
b1c1904d0d015c36c09aca6f9afeedb1393d6ba9
629,193
def repeat_flaky_test(test, n_repeats=2, n_allowed_failures=0, *args, **kwargs): """ Run the given test `n_repeats` times, raising the `n_allowed_failures+1`^th assertion error. Parameters ---------- test : Callable[Any, V] test to wrap n_repeats : int, optional number of times ...
d8998a87f30c01241ed51901edf89e2a845a59bf
629,194
def str2val(val, na="na", list_detection=False): """guess type (int, float) of value. If `val` is neither int nor float, the value itself is returned. """ if val is None: return val def _convert(v): try: x = int(v) except ValueError: try: ...
34da4d91adb150bca27509710c8bb9f25651f95f
629,195
import numpy as np import re def coverage(protein, peptides): """Calculate how much of `protein` is covered by `peptides`. Peptides can overlap. If a peptide is found multiple times in `protein`, it contributes more to the overall coverage. Requires :py:mod:`numpy`. .. note:: Modificatio...
b90b4ab511a616617b50d2fef181a2d995e72de4
629,197
import os def token(key): """ >>> token('hello') 'hello' >>> token(('hello', 'world')) # doctest: +SKIP 'hello/world' """ if isinstance(key, str): return key elif isinstance(key, tuple): return os.path.join(*map(token, key)) else: return str(key)
3dd35cc309a303580b9b5c49dcb7e6e7a24e4c39
629,198
def trend(time, slope, offset): """ Generate a trend of size n """ return slope * time + offset
25bad2ac60ecca199250a2b500696bf93416279a
629,199
import argparse def parse_args(): """Command arguments parsing""" parser = argparse.ArgumentParser( description="This program converts an XML input to the an equivalent " "input file written in a format that is natively readable " "by Fortran's code...
3585fbb4f2c3cb84e6bb88095f7a537b6231bc47
629,200
def maximum_border_length(w): """Maximum string borders by Knuth-Morris-Pratt :param w: string :returns: table f such that f[i] is the longest border length of w[:i + 1] :complexity: linear """ n = len(w) f = [0] * n # init f[0] = 0 k = 0 # current lo...
564a29d77f8cc83e7093ae351ff3d308eebaa703
629,201
def hash_object(object_): """ Returns the hash value of the given object even if it not defines `__hash__`. Parameters ---------- object_ : `Any` The object to get it's hash value of. Returns ------- hash_value : `int` """ try: hash_value = hash(object_)...
49e6c303eb26e2085426e82443de36991a6e97f6
629,202
from typing import List def read_ta_list(fname: str)->List[str]: """ Read total list of TAs from a file with one TA roll number per line""" tfile = open(fname,"r") tas = [] for l in tfile: s=l.strip() if (len(s)==0): continue tas.append(s.lower()) return tas
7d683a32a9381a7efc80223cf2cea200238dc0a8
629,203
import math def sum_of_divisors_v2(n): """Find the sum of all divisors of a given integer. NOTE: If we look carefully, all the divisors are present in pairs. For example if n = 100, then the various pairs of divisors are: (1,100), (2,50), (4,25), (5,20), (10,10). resource: https://www.geeksforgeek...
33bc5b22cca28dc3c1be8b65b81182b3f3ec858b
629,204
def find_happy_number(num: int) -> bool: """ Time complexity: O(logN) Space complexity: O(1) Parameters ---------- num : int input number Returns ------- bool whether the input is a happy number """ def get_next(number: int) -> int: """ Calc...
29512c868c761ec86bb0a333ad092d692bbba017
629,205
def replace_vol(img, vol, center, vol_as_mask=None): """Replace a volume within an image, centering on the given coordinates and cropping the input volume to fit. Args: img: Image as a Numpy array into which ``vol`` will be placed. ``img`` will be updated in-place. vol: Volume...
b3f9e1fc23c1c2855b0a98f79ca4410052f45010
629,207
def parse_row(row, columns_map): """ converts smartsheet row into a dict """ row_dict = row.to_dict() cells = row_dict['cells'] result = { 'id': row_dict['id'], 'row_number': row_dict['rowNumber'], 'parent_id': row_dict.get('parentId'), 'name': cells[columns_map['...
b80baeea97e615801215f0b17461300b90e2cef4
629,209
import torch def max_loss(predict,target): """return max value of predict - target""" return torch.max(torch.abs(predict-target))
10fe62e7270497030e52ff0734656431bdb92561
629,210
def _find_associated_colorbar(obj): """A rather poor way of telling whether an axis has a colorbar associated: Check the next axis environment, and see if it is de facto a color bar; if yes, return the color bar object. """ for child in obj.get_children(): try: cbar = child.color...
2c756e0d3c669f72afa0c05750132910cff41468
629,211
import re import string from typing import Counter def get_words(text): """Retrieve the words present in a given string of text. The return value is a list of tuples where the first member is a lowercase word, and the second member the number of time it is present in the text. Example: IN: "Did th...
8885fc4a872458fd5551fb0d7fdd0652d9683853
629,212
import os def load_config(): """Parse existing .env file. Taken from https://github.com/theskumar/python-dotenv/. """ config = {} if not os.path.isfile('.env'): return config with open('.env', 'r') as f: for line in f: line = line.strip() if not line ...
2c9eeb0942abba58f1dd690de22a6a5ce74f2647
629,214
import numpy def advect(gr, u, S, dt): """ compute the advective term that updates u in time. Here, S is a source term """ # we need the states in the first ghost cell too ib = gr.ilo-1 ie = gr.ihi+1 # compute the limited slopes -- 2nd order MC limiter test = gr.scratchArray() t...
b519ad46cb475e2169ab150962254966d89b0453
629,215
def parse_serial_line(line): """ Not currently used. Kept for reference :param line: :return: """ sensors = {} for s in line.split(";"): x = s.split(":") try: sensors[x[0]] = int(x[1]) except: pass # print('?', x) return sen...
bcccd3213412436d40219f4c7f110234b7874f00
629,216
import os import sys def get_manpath_directories(): """Return the list of directories in MANPATH""" manual_directories = [] if "MANPATH" in os.environ.keys(): manual_directories = os.environ["MANPATH"].split(os.pathsep) else: if os.name == "posix": if os.path.isdir("/usr/sh...
ba94cc0a1199a70355266a89de6fc3575ef4f2e7
629,217