content
stringlengths
39
9.28k
sha1
stringlengths
40
40
id
int64
8
710k
def get_passive_outcome(df, trial, sample): """Get data for a replay. Parameters ---------- df : pandas.DataFrame Data to be replayed trial, sample : int Indices into the data for which to fetch actions Returns ------- outcome : int magnitude of the outcome to be obtained in the passive condition """ df = df[(df['trial'] == trial)] outcomes = df[(df['trial'] == trial)]['outcome'].dropna() outcome = int(outcomes.tolist()[sample]) return outcome
e54e2e7e9dbbc7759a2a4284cfd4af88f5037793
233,001
import torch def get_avg_global_features(points, mask, features, model): """obtain the avg pooling global features Args: points ([type]): points_batch mask ([type]): points mask features ([type]): point features model ([type]): the loaded model Returns: [type]: return the avg global features """ with torch.no_grad(): output = None def hook_func(module_, input_, output_): nonlocal output output = output_ # the model's name(pool_avg) is determined by the classifer definition hook = model.module.classifier.pool_avg.register_forward_hook(hook_func) model(points, mask, features) # (B,num_classes) hook.remove() return output
8a3f91c7f8ddbcb8aab32bff21d2dafaa19c68ef
451,622
def manhattan_dist(pose1, pose2): """ Returns manhattan distance between two poses """ return abs(pose1[0] - pose2[0]) + abs(pose1[1] - pose2[1])
9c4de9944febd48d6226e752f21dbdfb75555b81
592,287
import inspect import logging def verify_parameters(code, kwargs, err_message): """ Used to verify the that the parameters in kwarg match the signature of the code. :param code: The code fragment's that has the signature to check. :param kwargs: The kwargs to look for :param err_message: An error message to show if the signature doesn't match. :return: """ params = inspect.signature(code).parameters verified = True # The kwargs should all be in the function. Anything left should have a default param_keys = set(params.keys()) param_keys.discard('self') # Make sure they have all the ones we asked for. missing = set(kwargs.keys()) - set(param_keys) for param_name in missing: logging.error(f"Missing param '{param_name}' on function {err_message}") verified = False remaining = set(param_keys) - set(kwargs.keys()) for param_name in remaining: if params[param_name].default == inspect.Parameter.empty: logging.error(f"Param '{param_name}' not passed for {err_message}") verified = False return verified
cd3c3542c41bb7ba0d3f8d7f250f44d743acb0a9
16,667
def _parse_input_list(input_list: str) -> list[str]: """ Converts a CSV list of assets IDs into a list of parsed IDs (but not Asset objects) """ return [fqn_id for fqn_id in input_list.split(",") if fqn_id != "" and fqn_id != ":"]
280bb0e110be0f1230533acfa0f8ae4f3f2ac7af
679,503
def global_usage_count(main=False): """ Returns global usage query Args: category (str): category name main (bool): optional in order to account only for file used in main namespaces """ query = """ SELECT /* SLOW_OK */ COUNT(page.page_title) AS total_usage, COUNT(DISTINCT page.page_title) AS images_used, COUNT(DISTINCT gil.gil_wiki) AS nb_wiki FROM image CROSS JOIN page ON image.img_name = page.page_title CROSS JOIN categorylinks ON page.page_id = categorylinks.cl_from CROSS JOIN globalimagelinks gil ON gil.gil_to = image.img_name WHERE categorylinks.cl_to = %s""" if main: return query + " AND gil.gil_page_namespace_id = 0 AND (gil.gil_wiki!='metawiki')" else: return query
4493b3a63b2fbe2e2824403a1db2705ad38cd14b
179,597
def list_to_lower(string_list): """ Convert every string in a list to lower case. @param string_list: list of strings to convert @type string_list: list (of basestring) @rtype: list (of basestring) """ return [s.lower() for s in string_list]
35097ddb6a665c50851bf6c98b60e9de88fb147b
661,563
from typing import Union from typing import List from pathlib import Path def new_dirs(dir_paths: Union[str, List[str]]) -> List[str]: """ 初始化文件夹,检验文件夹的存在状态,并返回准备好的文件夹路径。 Args: dir_paths: 字符串类型的全路径,可以为单个路径,也可以放入列表中,批量创建。 Returns: 包含创建的文件夹路径字符串的list """ if isinstance(dir_paths, str): dir_paths = [dir_paths] for dir in dir_paths: dir_path = Path(dir) dir_path.mkdir(parents=True, exist_ok=True) return dir_paths
2a0a819a6771b22ee7ae4170cb0b42a8e1f59b52
595,329
from bs4 import BeautifulSoup import re def strip_spacing_from_soup(soup: BeautifulSoup, strip=False, verbose=None) -> BeautifulSoup: """ Strip excess white spaces near punctuation marks, e.g. fix ' .' and ' ,' Args: soup (BeautifulSoup, Tag, NavigableString): any soup Returns: soup (BeautifulSoup, Tag, NavigableString): with excess white spaces stripped out Modules: bs4 (BeautifulSoup), re """ if verbose is None: if not strip: verbose=True _punctuation_spaces = re.compile(r'\s([?.!,;"](?:\s|$))') for item in soup.find_all(): if item.string: s = re.search(_punctuation_spaces, item.string) if s: if verbose: print(s) if strip: item.string.replace_with(re.sub(_punctuation_spaces, r'\1', item.string)) return soup
bead3244eb20ec188946bdbee06b444a6099d33f
381,551
def _get_type_to_speed(cfs): """Given a list of charging functions, returns an object whose keys are the CS types and values are speed rank. Speed rank is a CS type's (0-indexed) position in the ordered list of fastest CS types. """ # compute max charge rates by type result = [{ 'cs_type': cf['@cs_type'], 'max_rate': ( (float(cf['breakpoint'][1]['battery_level'])-float(cf['breakpoint'][0]['battery_level'])) / (float(cf['breakpoint'][1]['charging_time']) - float(cf['breakpoint'][0]['charging_time'])) )} for cf in cfs] # assign each type its speed rank (lowest = fastest --> highest = slowest) result = sorted(result, key=lambda x: x['max_rate'], reverse=True) for i, entry in enumerate(result): entry.update({'speed_rank': i}) # return dict type:speed_rank return {cf['cs_type']: cf['speed_rank'] for cf in result}
ca866af02fb39f31779de1bd7b3e6267c363b5b8
57,733
def quantumespresso_magnetic_code(aiida_local_code_factory): """Get a quantumespresso_magnetic code. """ quantumespresso_magnetic_code = aiida_local_code_factory( executable='diff', entry_point='quantumespresso_magnetic') return quantumespresso_magnetic_code
913c8efc7bb2d1851c743754ea04df44c06ce6d7
85,876
def merge_aux(subperm, perm_list): """ Auxiliary function for merging subpermutations. Args: subperm (tuple): perm_list (list) Returns: (tuple) list with subpermutation merged (if successful) and a flag that is set to True if merge was successful and False otherwise. """ # Copy list of subpermutations. perm_list_aux = perm_list.copy() # Go over subpermutations and try to merge. for idx in range(len(perm_list_aux)): if subperm[-1] == perm_list_aux[idx][0]: # If end of subpermutation matches beginning of next. res = subperm + perm_list_aux[idx][1:] del(perm_list_aux[idx]) perm_list_aux.append(res) return perm_list_aux, True if subperm[0] == perm_list_aux[idx][-1]: # If end of the subpermutation matches end of next. res = perm_list_aux[idx][:-1] + subperm del(perm_list_aux[idx]) perm_list_aux.append(res) return perm_list_aux, True # If match unsuccessful, set flag to False. return perm_list, False
50bd179deebaba92a8ede9a9a833523208d1cb80
226,887
def fetch_mga_scores(mga_vec, codon_pos, default_mga=None): """Get MGAEntropy scores from pre-computed scores in array. Parameters ---------- mga_vec : np.array numpy vector containing MGA Entropy conservation scores for residues codon_pos: list of int position of codon in protein sequence default_mga: float or None, default=None value to use if MGA entropy score not available for a given mutation. Drop mutations if no default specified. Returns ------- mga_ent_scores : np.array score results for MGA entropy conservation """ # keep only positions in range of MGAEntropy scores len_mga = len(mga_vec) good_codon_pos = [p for p in codon_pos if p < len_mga] # get MGAEntropy scores if good_codon_pos: mga_ent_scores = mga_vec[good_codon_pos] else: mga_ent_scores = None return mga_ent_scores
9761bb4c8174e16916bfbb37bf715ad4cc85ec14
324,731
def feature_value_match_dict_from_column_names(column_names, prefix=None, suffix=None, col_name_to_feature_vals_delimiter='_match_for_____', feature_vals_delimiter='_'): """Given a list of column names of the form COLUMN_NAME_match_for: FEATURE_VALUE1 FEATURE_VALUE2, FEATURE_VALUE3 return a dictionary map of the form {COLUMN_NAME: [FEATURE_VALUE1, FEATURE_VALUE2, FEATURE_VALUE3]}. Optional arguments for column prefix, suffix, col_to_feature_delimiter and feature_value_delimeter Parameters ---------- column_names: list[str] A list of string column names for which to extract to a dictionary of the form {column_name:[list of feature values]} prefix: str A string prefix to remove from the created columns suffix: str A string suffix to from the created columns col_name_to_feature_vals_delimiter : str, Default = '_match_for: ' The string delimiter that seperates the column features values from the column name feature_vals_delimiter: str, Default = ', ' The string delimiter that seperates the features values from each other Example --------- feature_value_match_dict_from_column_names([ 'Sparse_feature_aggregation_Claim Classification_1mo_match_for: Catastrophic', 'Sparse_feature_aggregation_Injury Type_1mo_match_for: Permanent Partial-Unscheduled', 'Sparse_feature_aggregation_riss_match_for: 14.0, 17.0, 12.0, 13.0'], prefix='Sparse_feature_aggregation_') >>> {'Claim Classification_1mo': ['Catastrophic'], 'Injury Type_1mo': ['Permanent Partial-Unscheduled'], 'riss': ['14.0', '17.0', '12.0', '13.0']} """ # If single string column name passed, # turn it into a list if isinstance(column_names, str): column_names = [column_names] # Remove prefix/suffix if specified if prefix: column_names = [col.replace(prefix, "") for col in column_names] if suffix: column_names = [col.replace(suffix, "") for col in column_names] # Create empty map match_value_map = {} # Iterate through column list for column in column_names: # Split the into column name and feature value column_name, match_values = column.split(col_name_to_feature_vals_delimiter) # Extract just the feature values match_values_list = match_values.split(feature_vals_delimiter) # Add to feature value map match_value_map[column_name] = match_values_list return match_value_map
72de4e16f2854a90f12b06b1f7a29d844ad7b265
88,584
import calendar def tuple_to_secs(tuple): """ Convert time tuple to UTC seconds. """ return calendar.timegm(tuple)
4a55f6927d4b8f6b36c6d4a4aca33abf9b4c019d
132,144
def read(path): """Read the file as one giant string.""" with open(path, "r", encoding="utf-8") as in_file: return in_file.read()
5538aaced99bc68c6b0c31b7e9a80f2adeb58a8c
496,428
import time def time_it(func): """ Run a function and return the time it took to execute in seconds. """ def timed_func(*args, **kwargs): start_time = time.time() func(*args, **kwargs) end_time = time.time() return end_time - start_time timed_func.__name__ = func.__name__ return timed_func
a25f6798ea0f40cd795036c2ef42f40f7b0be691
158,740
import base64 def base64_to_int(b: str) -> int: """ Returns a int from a base64 string """ return int.from_bytes(base64.b64decode(b), 'big')
1021d5f5bcff85ae1a0b6943f08b656eb54d7c48
322,868
def safedel_message(key): """ Create safe deletion log message. :param hashable key: unmapped key for which deletion/removal was tried :return str: message to log unmapped key deletion attempt. """ return "No key {} to delete".format(key)
4bbc5b6a5a2bdeef1cfc535aa16fe1256f93fc17
249,749
import codecs def load_data(train_file): """ Return list of dataset given train_file and gs_file Value: [(sa:str, sb:str, score:float)] """ with codecs.open(train_file, 'r', encoding='utf8') as f: data = [] for idx, line in enumerate(f): line = line.strip().split('\t') score = 0. if len(line) == 3: score = float(line[2]) sa, sb = line[0], line[1] data.append((sa, sb, score)) return data
218077e06a0850460404ed92ac4dbb6229225f3b
162,952
from time import sleep def test_re_auth(relay, mini_sentry): """ Tests that managed non-processing relays re-authenticate periodically. """ relay_options = {"http": {"auth_interval": 1}} # count the number of times relay registers original_check_challenge = mini_sentry.app.view_functions["check_challenge"] counter = [0] def counted_check_challenge(*args, **kwargs): counter[0] += 1 return original_check_challenge(*args, **kwargs) mini_sentry.app.view_functions["check_challenge"] = counted_check_challenge # creates a relay (we don't need to call it explicitly it should register by itself) relay(mini_sentry, options=relay_options) sleep(2) # check that the registration happened repeatedly assert counter[0] > 1
415084bd47ba59f370362abc3a7a07be9bd74e49
515,292
def anisotropy_from_intensity(Ipar, Iper): """ Calculate anisotropy from crossed intensities values. """ return (Ipar - Iper)/(Ipar + 2*Iper)
6e9d2c211394193e0b9d00e79af523f91e9bd6f9
474,451
def fstarBen(mh, m1, f0, beta, gamma): """ Stellar mass to halo mass ratio as a function of halo mass. Fitting function from Moster et al. """ mstar = 2.0 * f0 * 10.0 ** mh / ((10.0 ** mh / 10.0 ** m1) ** (-beta) + (10.0 ** mh / 10.0 ** m1) ** gamma) fstar = mstar / 10.0 ** mh return fstar
e54bb55468ce78c53ba380b08ad99ed61424c306
549,430
def clean(data, parameters): """ Cleans a dictionary to only includ valid parameters and non empty values. """ # Only take valid parameters. data = {key: data.get(key) for key in parameters} # Remove empty parameters. data = {key: value for key, value in data.items() if value is not None} return data
c421f3df0220764af81c0226d8b9430063d141e3
326,544
def get_func_name(func_str): """ Get function name, ie removes possible return type """ name = func_str.split(' ')[-1] return name
50b88f2d575aa0d6a8067db21cc674b1d60bed00
379,173
def limit_string_length(string, max_len=50): """Limit the length of input string. Args: string: Input string. max_len: (int or None) If int, the length limit. If None, no limit. Returns: Possibly length-limited string. """ if max_len is None or len(string) <= max_len: return string else: return "..." + string[len(string) - max_len:]
bd7a96ac6e0da2f4f042c4034e92925272e3c861
353,800
def sum_book_score(book_idx_list, book_score_list): """ Helper function to get sum of book scores Args: book_idx_list: List of Book Index , book_score_list: List of Book Scores Returns: sum of book scores """ return sum(book_score_list[book_idx] for book_idx in book_idx_list)
0bbae7a7b7c885e83f2bb60dd5aebc2d8e88ef5b
193,985
def interpolateLinear( y1, # y2, # x # weighting [0..1]. 0 would be 100 % y1, 1 would be 100 % y2 ): """ simple linear interpolation between two variables @param y1 @param y2 @param x weighting [0..1]: 0 would be 100 % y1, 1 would be 100 % y2 @return the interpolated value """ return y1 * (1.0 - x) + y2 * x
d2193b8fe313ccc61853407fa75169ca4bf5771f
246,571
def client_superuser(client, admin): """Provides a client with a logged in superuser. """ client.force_login(admin) return client
2433b52f5e9dbaedf73195d77e9015be158a262e
72,387
def cfg_val_or_none(cfg, key): """Look up key in the 'cfg' dictionary. If not found, returns None.""" return cfg[key] if key in cfg else None
b5b59fe5aa29ac4974b5a3dd5bee901d4d019d70
364,322
import re def change_to_count_endpoint(endpoint): """Utility function to change a normal endpoint to a ``count`` api endpoint. Returns the same endpoint if it's already a valid count endpoint. Args: endpoint (str): your api endpoint Returns: str: the modified endpoint for a count endpoint. """ tokens = filter(lambda x: x != '', re.split("[/:]", endpoint)) filt_tokens = list(filter(lambda x: x != "https", tokens)) last = filt_tokens[-1].split('.')[0] # removes .json on the endpoint filt_tokens[-1] = last # changes from *.json -> '' for changing input if last == 'counts': return endpoint else: return "https://" + '/'.join(filt_tokens) + '/' + "counts.json"
19d5931449cd8a1c5e2fd1f864a55c47c392645f
462,936
def execute_commands_on_linux_instances(client, commands, instance_ids): """Runs commands on remote linux instances :param client: a boto/boto3 ssm client :param commands: a list of strings, each one a command to execute on the instances :param instance_ids: a list of instance_id strings, of the instances on which to execute the command :return: the response from the send_command function (check the boto3 docs for ssm client.send_command() ) """ resp = client.send_command( DocumentName="AWS-RunShellScript", # One of AWS' preconfigured documents Parameters={'commands': commands}, InstanceIds=instance_ids, ) return resp
d6938ef7f7ec16d0cb4554f7efdd82ab381ba20f
416,094
def simplify_keys(mapping: dict[str, str]) -> dict[str, str]: """ Simplify/deduplicate dict keys, to reduce variations in similarly-named keys Example:: >>> simplify_keys({'my_namepace:Super_Order': 'Panorpida'}) {'superfamily': 'Panorpida'} Returns: dict with simplified/deduplicated keys """ return {k.lower().replace('_', '').split(':')[-1]: v for k, v in mapping.items()}
5de6cea495d7ab7abf19c4e2487cb53813ef48b8
485,884
def _covcalc(a, b, wc): """ Calculates the covariance from a * b^t :param a: The `a` matrix :type a: torch.Tensor :param b: The `b` matrix :type b: torch.Tensor :return: The covariance :rtype: torch.Tensor """ cov = a.unsqueeze(-1) * b.unsqueeze(-2) return (wc[:, None, None] * cov).sum(-3)
76d6c2d2c368135557478a9afee43183d8840052
141,176
def is_power_of_two(n): """Check whether `n` is an exponent of two >>> is_power_of_two(0) False >>> is_power_of_two(1) True >>> is_power_of_two(2) True >>> is_power_of_two(3) False >>> if_power_of_two(16) True """ return n != 0 and ((n & (n - 1)) == 0)
b5fdbabb959f224018b57c2244bbfe93780ece1c
643,762
def _read_file(fname): """ Args: fname (str): Name of the grammar file to be parsed Return: list: The grammar rules """ with open(fname) as input_file: re_grammar = [x.strip('\n') for x in input_file.readlines()] return re_grammar
9e6fba0bf76f3170a3d26a73ba6bac3c9c8c34be
672,566
def read_single_param_file(src, typename=int): """Read a file with one value This function can be used to read files in Kaldi which has parameter values stored in them. E.g. egs/info/num_archives. Pass the typename in advance to return the value without errors. Args: src: the path to file that contains the parameter value typename (type): The type of value to be expected in the file. Default is int. Any custom value that can take a string can be passed. Returns: Value in the "src" file casted into type "typename" Raises: AssertionError if parameter value is empty. """ param = None with open(src) as ipf: param = typename(ipf.readline().strip()) assert param is not None return param
0b5d4b210f0032e25ea16fe79278a0fe27fb63ad
235,546
import re def parsePlasClass(filename): """ Parse the file into lists of edge names, lengths, and PlasClass scores """ with open(filename) as f: names = [] lengths = [] scores = [] name = '' for line in f: splt = line.strip().split('\t') edge_name = splt[0] # convert name from fastg header format to single edge name name = re.split(':|;',edge_name)[0] names.append(name) length = int(name.split('_')[3]) lengths.append(length) score = float(splt[1]) scores.append(score) return names, lengths, scores
0481c203c03b87c2fd2a69d29f7cafabc876389e
598,035
def find(label, equiv): """ Finds the root label in equivalence classes of labels Parameters: label -> int Value of a labelled pixel, to traverse for finding the root label equiv -> dict Contains equivalence classes for each label Return: minVal -> int The root label """ minVal = min(equiv[label]) while label != minVal: label = minVal minVal = min(equiv[label]) return minVal
48199c10487c0867499e743e6ffbf04c6b9312a0
504,491
import torch def calc_regression_acc(predictions, targets, thld=None): """Calculate accuracy when treating regression as binary classification. Args: predictions (torch.Tensor): The predicted mean. A mean greater than zero will be considered a postive prediction. targets (torch.Tensor): The regression targets. Targets greater than zero will be considered as positive lables. thld (float, optional): If specified, another threshold than zero can be chosen to define the boundary between positive and negative values. Returns: Accuracy. """ if thld is None: thld = 0 labels = targets > thld pred_labels = predictions > thld return 100 * torch.sum(labels == pred_labels) / labels.shape[0]
ffd4df24d1dbcc69176ad46f2d198460de3fc222
396,997
import heapq def heapmerge(*inputs): """Like heapq.merge(), merges multiple sorted inputs (any iterables) into a single sorted output, but provides more convenient API: each input is a pair of (iterable, label) and each yielded result is a pair of (item, label of the input) - so that it's known what input a given item originates from. Labels can be any objects (e.g., object that produced the input stream).""" def entries(iterable, label): for obj in iterable: yield (obj, label) iterables = [entries(*inp) for inp in inputs] return heapq.merge(*iterables)
580ec9f2f0793f8907390f5c7f8eebf4ac539b59
701,533
def parse_port(arg): """Parse port argument and raise ValueError if invalid""" if not arg: return None arg = int(arg) if arg < 1 or arg > 65535: raise ValueError("invalid port value!") return arg
5c746f858c0d2ddf78cc6b0069e765132de20469
301,324
import typing def parse_xlsx(worksheet) -> typing.List[typing.List]: """Parse the Excel xlsx file at the provided path. Args: worksheet: An openpyxl worksheet ready to parse Returns: List of values ready to write. """ # Convert the sheet to a list of lists row_list = [] for r in worksheet.rows: # Parse cells cell_list = [cell.value for cell in r] # Skip empty rows try: # A list with only empty cells will throw an error next(c for c in cell_list if c) except StopIteration: continue # Add to the master list row_list.append(cell_list) # Pass it back return row_list
ef7494a0720a21fdfc99e378132f811effed0e51
97,923
def _prepare_pylint_args(args): """ Filter and extend Pylint command line arguments. --output-format=parsable is required for us to parse the output. :param args: list of Pylint arguments. :returns extended list of Pylint arguments. """ # Drop an already specified output format, as we need 'parseable' args = [a for a in args if not a.startswith("--output-format=")] args.append("--output-format=parseable") return args
0b25072e4b203ccd3a320d7d60178d6d51a456b9
114,965
import random def create_neg_relations(entities, rels_between_entities, rel_type_count, neg_rel_count): """ Creates negative relation samples, i.e. pairs of entities that are unrelated according to ground truth """ neg_unrelated = [] # search unrelated entity pairs for i1, _ in enumerate(entities): for i2, _ in enumerate(entities): if i1 != i2: pair = (i1, i2) if pair not in rels_between_entities: neg_unrelated.append(pair) # sample negative relations neg_unrelated = random.sample(neg_unrelated, min(len(neg_unrelated), neg_rel_count)) neg_rel_entity_pairs, neg_rel_types = [], [] for pair in neg_unrelated: one_hot = [0] * rel_type_count neg_rel_entity_pairs.append(pair) neg_rel_types.append(one_hot) return neg_rel_entity_pairs, neg_rel_types
4a8897b3055cf74106852b64944bb76c67674f71
650,678
from typing import Any def sanitize_path(x: Any) -> str: """Converts `x` to string and replaces any occurrence of "/" with "_".""" return str(x).replace("/", "_")
a162ffd127451e8e1cb4b6b937b1ea61a1373932
393,482
def read_file(path, file): """ reading .txt file and return its content as string :param path: path to file :param file: file (.txt) :return: file_content as string """ file_name = str(path) + str(file) with open(file_name + '.txt', 'r') as myfile: file_content = myfile.read() return file_content
374aa549c808d0e50fa42d133b9115eeca07ee91
265,652
def parse_vertices(vertices_str): """ Parse vertices stored as a string. :param vertices: "x1,y1,x2,y2,...,xn,yn" :param return: [(x1,y1), (x1, y2), ... (xn, yn)] """ s = [float(t) for t in vertices_str.split(',')] return zip(s[::2], s[1::2])
58be48099272a9f9d5251666a0670a0c2b7e1f16
283,082
import math def polysum(n, s): """ n: Number of sides s: Length of each side returns: sum of the area and square of the perimeter of the regular polygon """ area = (0.25*n*s*s)/math.tan(math.pi/n) perimeter = n*s sum = area + perimeter**2 return round(sum,4)
d2e7be6f8f02c7b5d481a08fed7f35aa8aa1c411
624,464
def split_all(s, chars): """Split on multiple character values. >>> split_all('a_b_c_d', '_. ') ['a', 'b', 'c', 'd'] >>> split_all('a b c d', '_. ') ['a', 'b', 'c', 'd'] >>> split_all('a.b.c.d', '_. ') ['a', 'b', 'c', 'd'] >>> split_all('a_b.c d', '_. ') ['a', 'b', 'c', 'd'] >>> split_all('a b_c.d', '_. ') ['a', 'b', 'c', 'd'] """ chars = list(chars) o = [s] while len(chars) > 0: c = chars.pop(0) n = [] for i in o: n += i.split(c) o = n return o
76cd3d5823dec479984ddd570b4162ab11bffec1
594,624
def check_power_of_2(number: int) -> bool: """Checks if given argument represents power of 2. Args: number: is checked for power of 2. Returns: If number represents power of 2 - True, owervise False. """ return (number != 0) and ((number & (number - 1)) == 0)
a26de28dd170eed97fc73b48ae22f6309656ea1c
398,764
def child_or_children(value): """ Return num followed by 'child' or 'children' as appropriate """ try: value = int(value) except ValueError: return '' if value == 1: return '1 child' return '%d children'
a22be46a3fd1086dac116c187189204b5ea1a6db
30,864
def _is_file_relevant(file_name: str, problem_name: str, graph_type: str, p_depth: int): """Check if a filename provided matches the description of a problem instance.""" return problem_name in file_name and "p=" + str(p_depth) in file_name and graph_type in file_name
3cd9072c1b1be92392511e4a7952e4bb453f4206
384,037
def is_changed(local: dict, remote: dict) -> bool: """ Determine if a locally defined monitor has changed from a remote version Excludes silenced config from the check if the monitor may be muted to avoid unmuting any monitors accidentally :param local: A dictionary representing the locally defined monitor :param remote: A dictionary representing the remote defined monitor :return: A boolean value that is true if the local and remote monitors differ """ if local['mute_when']: remote['obj'].get('options', {}).pop('silenced', None) return local['obj'] != remote['obj']
a7b0a08bf6b60fd520c2535bd8a3cfc96420a44c
248,011
import re def strip_interface_speed(speed): """Converts symbol interface speeds to a more common notation. Example: 'speed10gig' -> '10g'""" if isinstance(speed, list): result = [re.match(r"speed[0-9]{1,3}[gm]", sp) for sp in speed] result = [sp.group().replace("speed", "") if result else "unknown" for sp in result if sp] result = ["auto" if re.match(r"auto", sp) else sp for sp in result] else: result = re.match(r"speed[0-9]{1,3}[gm]", speed) result = result.group().replace("speed", "") if result else "unknown" result = "auto" if re.match(r"auto", result.lower()) else result return result
1662ba127e37af207715d9fc5a9bdec924c0b781
305,370
import unicodedata def remove_non_ascii_chars(s): """ Removes non-ascii characters from specified (unicode) string. Basically following examples from http://bit.ly/2umENUv and http://bit.ly/2sFScdQ. """ # latin-1 characters that don't have a unicode decomposition CHAR_REPLACE = { 0xc6: u"AE", # LATIN CAPITAL LETTER AE 0xd0: u"D", # LATIN CAPITAL LETTER ETH 0xd8: u"O", # LATIN CAPITAL LETTER O WITH STROKE 0xde: u"Th", # LATIN CAPITAL LETTER THORN 0xdf: u"ss", # LATIN SMALL LETTER SHARP S 0xe6: u"ae", # LATIN SMALL LETTER AE 0xf0: u"d", # LATIN SMALL LETTER ETH 0xf8: u"o", # LATIN SMALL LETTER O WITH STROKE 0xfe: u"th", # LATIN SMALL LETTER THORN } nfkd_form = unicodedata.normalize('NFKD', s) # decomposing unicode string decomposed = "".join( [char for char in nfkd_form if not unicodedata.combining(char)]) # replacing non-decomposable non-ascii characters return "".join( [CHAR_REPLACE[ord(char)] if ord( char) in CHAR_REPLACE else char for char in decomposed])
12a469ee95853817d8f1addcd3fedfeb43a4c0cc
550,767
def _unwrap_response(resp): """Get the actual result from an IAM API response.""" for resp_key, resp_data in resp.items(): if resp_key.endswith('_response'): for result_key, result in resp_data.items(): if result_key.endswith('_result'): return result return {} # PutRolePolicy has no response, for example raise ValueError(resp)
3902c3f9f78d256e697fe2a3ffa3de9a89f980be
106,503
def strip_suffix(s, suffix): """Remove suffix frm the end of s is s = "aaa.gpg" and suffix = ".gpg", return "aaa" if s is not a string return None if suffix is not a string, return s :param str s: string to modify :param str suffix: suffix to remove :rtype: Optional[str]=None """ if not isinstance(s, str): return None if not isinstance(suffix, str): return s if s.endswith(suffix): return s[: -len(suffix)] return s
8ca0579d68bcb22c7c139583122ab281f79ce9f8
554,890
def count_files_dir(path): """count number of files recursivly in path.""" # IN pathlib path num_f_dest = 0 for f in path.glob("**/*"): if f.is_file(): num_f_dest += 1 return num_f_dest
88da56f91c6afb8d87390e0da4d644991273cb09
125,106
def mass_to_richness(mass, norm=2.7e13, slope=1.4): """Calculate richness from mass. Mass-richness relation assumed is: mass = norm * (richness / 20) ^ slope. Parameters ---------- mass : ndarray or float Cluster mass value(s) in units of solar masses. norm : float, optional Normalization of mass-richness relation in units of solar masses, defaults to 2.7e13. slope : float, optional Slope of mass-richness relation in units of solar masses, defaults to 1.4. Returns ---------- ndarray or float Cluster richness(es), of same type as mass. See Also ---------- richness_to_mass : The inverse of this function. """ richness = 20. * (mass / norm)**(1. / slope) return richness
f048fc823db8df4d8b5e448a80a6244bcb5fab31
192,859
def store_by_id(obj_list): """returns a dict where the objects are stored by their object id""" result_dict = {} for obj in obj_list: obj_id = obj.get('_source', {}).get('id', False) if obj_id: result_dict[obj_id] = obj return result_dict
26da665a2255a1002c8cb6eb90d933d066d96724
539,018
def convert_string_to_list(_string, separator=','): """ splits the string with give separator and remove whitespaces """ return [x.strip() for x in _string.split(separator)]
47aa94e2678ab179310220a6c1e97b3fcd013b0a
329,290
import requests def do_gossip(known_nodes): """ The gossip algorithm - pull. All the known nodes are checked for collecting the available chains. :return: True if our chain was replaced, False if not """ collected_chains = [] # Pull: Collect the blockchains from the neighbours for node in known_nodes: try: response = requests.get(f'http://{node}/chain') if response.status_code == 200: chain = response.json()['chain'] collected_chains.append(chain) except Exception as e: print(f'Exception on node {node}: {e}') return collected_chains
f543db7dba5ae7b6ef6f762ebc277310ad9a1f83
407,040
import math def add_radians(a, b): """Adds two radian angles, and adjusts sign +/- to be closest to 0 Parameters: :param float a: Angle a :param float b: Angle b Returns: The resulting angle in radians, with sign adjusted :rtype: float """ return (a + b + math.pi) % (2 * math.pi) - math.pi
43f33ba646899e2431fee4967335b8a724cad194
46,289
def labels_to_onehot(labels, classes): """ Convert a list of labels (integers) into one-hot format. Parameters ---------- labels : list A list of integer labels, counting from 0. classes : int Number of class integers. Returns ------- list List of one-hot lists. """ for c, i in enumerate(labels): onehot = [0] * classes onehot[i] = 1 labels[c] = onehot return labels
886f7ccc954ffb86cc97db131b5108484ec40fa3
593,208
def contains_entry(entry_list, entry): """ Function for filtering duplicate entries in a list. Args: entry_list (list): List of Pymatgen ComputedEntry objects. entry (ComputedEntry): the Pymatgen ComputedEntry object of interest. Returns: bool """ for ent in entry_list: if (ent.entry_id == entry.entry_id or (abs(entry.energy_per_atom - ent.energy_per_atom) < 1e-6 and (entry.composition.reduced_formula == ent.composition.reduced_formula))): return True
8e716b6549988a23f6ba38edae405b7cf717ed27
133,936
def draw_frame(surface, rect, color_fill, color_border, border=1): """ Creates and draws a rect with a frame. Returns the inside rect object. returns a pygame.Rect() object, which is the filled area inside the frame - surface: the pygame surface to draw this on - rect: pygame.Rect() object for the outer frame - color_fill, color_border: pygame.Color() object for fill and the border - border: border thickness, in pixel (an int) """ surface.fill(color_border, rect) inside_rect = rect.inflate(-border*2, -border*2) surface.fill(color_fill, inside_rect) return inside_rect
2b37a96beb6d1c4d0aa184e677f6c8528b90193e
641,806
def parse_response(response): """ :param response: output of boto3 rds client describe_db_instances :return: an array, each element is an 3-element array with DBInstanceIdentifier, Engine, and Endpoint Address Example: [ ['devdb-ldn-test1', 'mysql', 'devdb-ldn-test.cjjimtutptto.eu-west-2.rds.amazonaws.com'], ['devdb-ldn-test2', 'postgres', 'devdb-ldn-test.cjjimtutptto.eu-west-2.rds.amazonaws.com'], ... ] """ res = [] # json output parse for db in response['DBInstances']: res.append([db['DBInstanceIdentifier'], db['Engine'], db['Endpoint']['Address']]) return res
edaa4abbb695adb06c43dc93d70178bc10a82445
701,633
def ordinal(num : int) -> str: """ Return the ordinal of a number For example, 1 -> 1st , 13 -> 13th , 22 -> 22rd """ remainder = num % 100 if remainder in (11, 12, 13): return str(num) + "th" else: suffixes = ["th", "st", "nd", "rd", "th", "th", "th", "th", "th", "th"] return str(num) + suffixes[num % 10]
59540556844ca7e9eaa9da134edd5ca6de08910b
354,263
import csv import re def lookup_county(county_code, office_code): """ Maps county numbers from a docket number (41, 20, etc.) to county names. The MDJ Docket search requires a user to select the name of the county to search. We can get the name of the county from a Docket Number, but it is not straightforward. MDJ Docket numbers start with "MDJ-012345". The five digits are a county code and an office code. Some counties share the same code, so the name of a county depends on all five of these digits. This method uses a reference table to match the county and office codes to the correct county's name. Args: county_code (str): Two-digit code that (usually) identifies a county. office_code (str): Three more digits that are sometimes necessary to identify a county, when two counties share the same county code. Returns: The name of a county, or None, if no match was found. Raise an AssertionError if multiple matches were found, because then something is wrong with the reference table. """ full_five_digits = "{}{}".format(county_code, office_code) with open("references/county_lookup.csv", "r") as f: reader = csv.DictReader(f) matches = [] for row in reader: if re.match(row["regex"], full_five_digits): matches.append(row["County"]) assert len(matches) <= 1, "Error: Found multiple matches for {}".format( full_five_digits) if len(matches) == 0: return None return matches[0]
45ac7b4bb351da113beed57336300be40588d461
232,813
def get_word_times(word, sen): """ 统计word在sen出现的次数 :param word: 要统计的单词,是一个字符串 :param sen: 句子, 是一个字符串列表 :return: 返回该单词在句子中出现的次数 """ times = 0 for i in sen: if word == i: times += 1 return times
239e1a86f9f397aeb2a9bf750ce236a121416346
300,379
def template_class(this_object): """Dump the object's class.""" cls = this_object.__class__ return '<code>%s</code>' % str(cls)
fe54a334d20cc1811f51c8768e08ebb54b61db4b
104,842
def replace_multiple(string, replacements={}): """Replaces multiple strings inside a string. Args: string (str): String to replace. replacements (dict): Custom replacements for the string. Examples: >>> print(replace_multiple('Replace this ".', ... replacements={'"': 'double quote'})) Replace this double quote. Returns: str: Input string with multiple replaces performed. """ for replacer, replacement in replacements.items(): string = string.replace(replacer, replacement) return string
9e182971669ef3cfb66bcc84379bae04965981a2
346,374
def tochar(v): """Check and convert value to a character""" if isinstance(v, str) and len(v) == 1: return v else: raise ValueError('Expected a character, but found %s' % v)
e406db33807ca0f25e5b348924226b58fcf04da3
659,945
def to_f(c): """Convert Celsius to Fahrenheit""" return round(c * 9 / 5.0 + 32, 1)
1bc2e1c8f3641e8d6d24caf61c54ec69a490525e
360,267
def secret_test_function(context, secrets: list = []): """Validate that given secrets exists :param context: the MLRun context :param secrets: name of the secrets that we want to look at """ context.logger.info("running function") for sec_name in secrets: sec_value = context.get_secret(sec_name) context.logger.info("Secret: {} ==> {}".format(sec_name, sec_value)) context.log_result(sec_name, sec_value) return True
c4a32a89ce35ee994688bfeca9d06deb69d1d81a
182,369
def extract_roles(x, roles): """ x is [N, B, R, *shape] roles is [N, B] output is [N, B, *shape] """ N, B, R, *shape = x.shape assert roles.shape == (N, B) return (x.reshape(N*B, R, *shape)[range(N*B), roles.reshape(N*B)]).reshape(N, B, *shape)
bfa71ca85245fdaa3a16acb68ea8038d21ee580f
274,211
def retrieve_hidden_word(full_word, found_letter): """This function returns a hidden word. The hidden letters are marked with an asterisk *.""" hidden_word = "" for letter in full_word: if letter in found_letter: hidden_word += letter else: hidden_word += "*" return hidden_word
6eb142fe1e04dfd2d53785e21117bc70f773e898
619,944
def is_finish(lst: list) -> bool: """ To be used with the filter function, keep only the bouts that did NOT go the distance in a 3 or 5 round bout. NB: This will also get rid of doctor stoppages between rounds. """ if ( (lst[2] == "3" and lst[3] == "5:00") or (lst[2] == "5" and lst[3] == "5:00") ): return False return True
8182515499f7a262853c70b9265a7154183607e1
451,236
def max_element(l): """ Returns the maximum element of a given list of numbers. """ max_ = None for x in l: if max_ is None or x > max_: max_ = x return max_
1596f33f0bb91839fbcaf2613892bf90fafd6afd
697,432
def script_path(script, test_name=__name__): """Returns a fully qualified module path based on test_name.""" return '{test_path}.{script}'.format(test_path=test_name, script=script)
23ddb5e11ddaa1f85cc571442b0cda74c412cbe5
226,183
import base64 def b64str_to_img_file(src, saveto, urlsafe=False): """ Re-generate image file from any Base64 string generated by img_to_base64_str(), and save it to disk. :param src: The string you want to decode. :param saveto: Specify the path of generated file to save to. :param urlsafe: Trigger using URL-Safe format. It must be consistent with your choice when first generating this string. :return: An integer of the size of the picture """ file_base64 = src.encode('utf-8') if urlsafe: file_byte = base64.urlsafe_b64decode(file_base64) else: file_byte = base64.standard_b64encode(file_base64) OUT_FILE = open(saveto, 'wb') return OUT_FILE.write(file_byte)
b97168a46c5f111e3b0c8d33b647aab538176151
531,932
from datetime import datetime def get_latest_year() -> int: """ Returns the last year if we are not in december yet otherwise returns the current year. """ today = datetime.now() if today.month < 12: return today.year - 1 return today.year
6cd7b36948de39546659bb4a56e113e7e365b68b
124,055
def clip(val, min_val, max_val): """ Clip value in between specified values. """ if val > max_val: return max_val if val < min_val: return min_val return val
86c6d34c4f407cd0d0c8b2778546510c0083dbb7
222,725
def zaction(op, inv): """ Return a function f: (G, Z) -> G g, n |-> g op g op ... (n-1 times) ... op g If n is zero, it returns identity element. If n is negative, it returns |n|-1 times op on the inverse of g. """ def f(g, n): result = op(g, inv(g)) # identity if n < 0: g, n = inv(g), -n for i in range(n): result = op(result, g) return result return f
a75f061221ce28b03f3bcc4ddbbc6985f20339b2
29,376
import requests import time def check_id_permitted(identifier: str, retries: int = 5) -> bool: """Check a user provided identifier is permitted This ID is expected to be a valid URL Parameters ---------- identifier : str identifier URL candidate Returns ------- bool if valid identifier """ _n_attempts = 0 while _n_attempts < retries: try: requests.get(identifier).raise_for_status() return True except ( requests.exceptions.MissingSchema, requests.exceptions.HTTPError, requests.exceptions.ConnectionError, ): _n_attempts += 1 time.sleep(1) continue return False
bece0a3d2e8717ac05aabd809969bedd9ba4ecbc
205,524
import re def parse_chromosome(s): """ Parse and normalize a chromosome string, which may be prefixed with 'chr'. """ match = re.fullmatch(r'(?:chr)?([1-9]|1\d|2[0-2]|x|y|xy|mt?)', s, re.IGNORECASE) if not match: raise ValueError(f'Failed to match chromosome against {s}') return match.group(1).upper()
9b072b204a2da120e2fae9d2fe7c36e15ca858dc
139,225
from pathlib import Path def strip_extension(path): """Function to strip file extension Parameters ---------- path : string Absoluate path to a slide Returns ------- path : string Path to a file without file extension """ p = Path(path) return str(p.with_suffix(''))
b05adb2a37b65e027504f3c85c9c44161f21d126
580,415
def isNan(x): """check for nan by equating x to itself""" return not x == x
f01ec6a5a5d04113d9c7c1630131802e412ade77
603,333
def get_note_type(syllables, song_db) -> list: """ Function to determine the category of the syllable Parameters ---------- syllables : str song_db : db Returns ------- type_str : list """ type_str = [] for syllable in syllables: if syllable in song_db.motif: type_str.append('M') # motif elif syllable in song_db.calls: type_str.append('C') # call elif syllable in song_db.introNotes: type_str.append('I') # intro notes else: type_str.append(None) # intro notes return type_str
621448603581a56af22ec9c559f9854c62073318
698,749
def add_outputs_from_dict( api_current_dict: dict, fields_to_keep: list ) -> dict: """ Filters a dict and keeps only the keys that appears in the given list :param api_current_dict: the origin dict :param fields_to_keep: the list which contains the wanted keys :return: a dict based on api_current_dict without the keys that doesn't appear in fields_to_keep """ if not api_current_dict or not fields_to_keep: return {} group_outputs = {} for field_to_keep in fields_to_keep: if field_to_keep in api_current_dict.keys(): group_outputs[field_to_keep] = api_current_dict.get(field_to_keep) return group_outputs
bfe251de9a8f2634b7777b1e2a89e6071b213ce1
599,786
import textwrap def strip_comment_marker(text): """ Strip # markers at the front of a block of comment text. """ lines = [] for line in text.splitlines(): lines.append(line.lstrip('#')) text = textwrap.dedent('\n'.join(lines)) return text
2c14db3bd25d19f1cdaad8aeab8d847974bf3213
222,378
def white_space(keyword): """``white-space`` property validation.""" return keyword in ('normal', 'pre', 'nowrap', 'pre-wrap', 'pre-line')
5e05ce4bb616d7046548c7a548ca8cb47859b19b
219,960
import asyncio def create_checked_task(coro_or_future): """ Wrapper for `asyncio.ensure_future` that always propagates exceptions. """ def raise_any_exc(task): return task.result() task = asyncio.ensure_future(coro_or_future) task.add_done_callback(raise_any_exc) return task
f1c0df2858bacf679ff07de28463b677d33d40bd
625,361
def remove_last_range(some_list): """ Returns a given list with its last range removed. list -> list """ return some_list[:-1]
ea2063c901d3aaf67caad97f1760f6fb6afb31c1
9,228
import time def datetime2ts(dt): """ Convert a `datetime` object to unix timestamp (seconds since epoch). """ return int(time.mktime(dt.timetuple()))
289c11c47d4cb0e9a6ea620fa5b40f81e4c5644d
633,618
def _format_return_message(results): """ Formats and eliminates redundant return messages from a failed geocoding result. :param results: the returned dictionary from Geoclient API of a failed geocode. :return: Formatted Geoclient return messages """ out_message = None if 'message' in results: out_message = results['message'] if 'message2' in results: if out_message: if out_message != results['message2']: out_message = "{} {}".format(out_message, results['message2']) else: return results['message2'] return out_message
a02f2277378b1c5b5f12ae2a00bb229d514860da
280,261
def compose(*fs): """ Functional compositions of one or more functions. Eg. compose(f1, f2, f3, f4). The innermost function: - may take arbitrary (including zero) positional arguments. - should produce one output value The remaining functions (if there are more than one argument to compose): - should take one input positional argument and produce one output value. """ assert len(fs) >= 1 *fs_outers, f_innermost = fs if len(fs_outers) > 0: return lambda *xs: compose(*fs_outers)(f_innermost(*xs)) else: return f_innermost
5e950e920a740ef79f86f782abefa55a88a8258b
336,829
def absolute_limits(nova_client): """Return the absolute limits as a dictionary.""" limits = nova_client.limits.get() return dict([(limit.name, limit.value) for limit in list(limits.absolute)])
ab9f17650c32e951d323ad7cd36b3c4c152de06e
529,978
def snake_to_camel(name): """convert a snake-cased string to camel-cased""" return name[0].lower() + "".join( "_" + ch.lower() if ch.isupper() else ch for ch in name[1:])
e528d448e46e3a493a586b45cde1ce198ab3e000
613,667