content
stringlengths
39
14.9k
sha1
stringlengths
40
40
id
int64
0
710k
def kilometers_to_miles(km): """ Convert from units of kilometers to miles PARAMETERS ---------- km: float A distance value in units of kilometers RETURNS ------- miles: float A distance value in units of miles """ #convert km to miles: return km*0.621371
564821eb0fbb60c0a637690e30364175f315b71f
599,390
import inspect def get_kwargs_applicable_to_function(function, kwargs): """Returns a subset of `kwargs` of only arguments and keyword arguments of `function`.""" return {key: value for key, value in kwargs.items() if key in inspect.getfullargspec(function).args}
271a21f29d32b2e8f8de9c0370b6c004a8ab8a82
599,391
def make_ranges(name): """ Return a start and end range values for a range vertex. """ return ( {'line': name.line, 'character': name.lo}, {'line': name.line, 'character': name.hi}, )
7f4b73bbefe022a53250b8fc7b9f4641a78f90c2
599,393
def mean(weights, mean): """ Calculate the negative mean return of a portfolio :param weights: asset weights of the portfolio :type weights: np.ndarray :param expected_returns: expected return of each asset :type expected_returns: pd.Series :return: negative mean return :rtype: float ...
c0567a70c7923211ea9df012f8619a137d79bdd4
599,400
def confusion_matrix(rater_a, rater_b, min_rating=None, max_rating=None): """ Returns the confusion matrix between rater's ratings """ assert(len(rater_a) == len(rater_b)) if min_rating is None: min_rating = min(rater_a + rater_b) if max_rating is None: max_rating = max(rater_a +...
4852e97cffeb6a6410c8d4a6f9ea7a35dad43985
599,402
from sympy import diff, symbols, lambdify def newton1D(f, x_0, df=None, delta=0.00001): """ Find solution to f(x) = 0 with newton's method :param f: function f :param x_0: starting point for x :param df: first order derivative of f :param delta: threshold for solution :return: x """ ...
85199d3caf9d54c6ce087c01aaec6bbaa56cbc93
599,403
def is_divisible(x, y): """ checks if x is divisible by y""" return x >= y and float(x) / y == x // y
3392321751e37ac0f4facec77d76adb1375a2582
599,406
def yaml_padding_from_line(line: str) -> int: """Calculate number of spaces required to create a YAML multiline string. eg: line='foo: bar' -> 2 line=' foo: bar' -> 4 """ last_c = None padding = 0 for i, c in enumerate(line): if i == 0 and c != ' ': padding ...
66f419dfb62ed01cee653c42386beb89d28ea2f2
599,408
def _get_codons_from(codons_dict): """Extract all codons from dictionary in a single list. Parameters ---------- codons_dict : dict Returns ------- list """ all_codons = list() for codons_list in codons_dict.values(): all_codons.extend(codons_list) return all_co...
23a4c789a8c61c43c7232ee34c65c6861a30eeee
599,414
def gradient_descent_step(g, learning_rate=0.00001): """ simple gradient descent :param g: the gradient :param learning_rate: the learning rate :return: the corrective term for the parameters the gradient belongs to """ return learning_rate * g
afbd2ed50d07fb6944b8af03dd5490cbbaea3df9
599,416
def purify(string): """ This function simplifies the given string as much as possible and returns the pure version of it. It is supposed to work basically for Greek words, but other languages shouldn't cause trouble. Its actual operation includes removing all accents from given string, lowering all ...
1accda9b53f104442dca3c54166303da98751cfc
599,419
def get_rmg_polynomial(las, has, temps=[200., 1000., 1000., 3000.]): """ Return NASA polynomial as a dictionary in RMG format: NASA Polynomial, seven or nine coefficients, Tmax and Tmin = valid temperature range polynomials = [{'coeffs':[2.3443,0.00798042,-1.94779e-05,2.0157e-08,-7.37603e-12,-917.924,0...
f68179cca90b560dd2e5279c3f6d364f8890f67d
599,420
def sequence_index_map(gapped_sequence): """ Creates a list that maps index positions in the non-gapped version of a sequence to the positions in the gapped sequence """ return [i for i,x in enumerate(gapped_sequence+'$') if x != '-']
6073691a6301b0c70624a7030412c1b3d67d7727
599,422
def weighted(category): """ Category status is the average over each weighted module status. Unrated modules are not taken into account, as well as modules with negative status value. """ status = 0.0 total = 0.0 for mod in category.module_list: if mod.dataset is None: # equivalent t...
716dd91843017b7c46a6994720aae9900f460b1a
599,423
def mail_test(str): """Tests to see if the line starts with MAIL FROM (loose case)""" testcase = str[0:5] testcase2 = str.replace(" ", "") #testcase = testcase.upper() #testcase2 = testcase2.upper() if testcase == "MAIL ": if testcase2[4:9] == "FROM:": return True else: return False else: return Fa...
69a64f35590f832ce04f3dd3825b117163dba799
599,425
def day_fraction(time): """Convert a 24-hour time to a fraction of a day. For example, midnight corresponds to 0.0, and noon to 0.5. :param time: Time in the form of 'HH:MM' (24-hour time) :type time: string :return: A day fraction :rtype: float :Examples: .. code-block:: python ...
be0b617619744ee8ad2c0def4489383ddee25146
599,426
import pathlib def check_dir(path, name): """Check that a directory exists. Args: path (:obj:`pathlib.Path` or :obj:`str`): Path to check. name (:obj:`str`): Reference name of path. Raises: :exc:`Exception`: If path does not exist. Returns...
34c2492839dc0d85c91520e3372c9e97ca4e9c7f
599,427
import time def current_time_millis() -> float: """Current system time in milliseconds""" return time.time() * 1000
ee45b138a42ca127ef5f6cd51d67123f6e958b10
599,434
def ksw_func( d50, rh=0., rl=1.e-6, theta=0. ): """ Calculate wave roughess Input: d50 - median grain size (m) rh - ripple height (m) rh - ripple wavelength (m) theta - time-averaged absolute Shields stress Returns: ksw - roughness (m) Based on Ribberink (199...
bf19680b928b254a2698a35ed2cd3a113474c9dc
599,435
from typing import Counter def is_unique_list(board_list): """Check if items are unique excluding None""" items = Counter(board_list) items.pop(None, None) if len(set(items.values())) > 1: return False return True
768ab854307017264c48ef9886b91df358c4bec0
599,438
import random def insert_mutation(genome): """Performs an insert mutation operation on the provided genome. First, picks two alleles at random and moves the second allele to be right after the first allele and shifting the rest of the genome to accommodate the change. This can be performed on any type...
31d5eaa670435ae41ef1ed5c3a8e5fb1f111a9c5
599,440
import json def load_json(filename): """ json loader to load Nematus vocabularies Note that we use unicode representations (not str) :param filename: :return: """ with open(filename, mode='rb') as f: return json.load(f)
6df9c234c37a7ed01cf00d24ed49578bc447e38e
599,445
def vertices_to_edges(vertices): """ takes a list of vertices which length is >= 2, return a list of tuple pairs of edges """ length = len(vertices) if length <= 1: return vertices # stop trolling, you call a list of a vertex a path? edges = [] last = vertices[0] # let's begin with...
708533995452e9101fae992738c6ebf123226769
599,448
def getint(data, offset, intsize): """ Retrieve an integer (big-endian) and new offset from the current offset """ value = 0 while intsize > 0: value = (value << 8) + data[offset] offset += 1 intsize -= 1 return value, offset
9ac2d3b41ca24435fc132a12034b1ec22518e7a5
599,450
def is_in_range(value, low_lim, up_lim, limits="Inclusive"): """Check if a value is bewteen a lower and upper limit""" if limits == "Inclusive": if low_lim <= value <= up_lim: return True else: return False elif limits == "Exclusive": if low_lim < value < up_lim: return True else: return False
f7bfc3644d8c15aff124505dbe30595256f5ba3e
599,453
def compile_hierarchy_req_str_list(geo_list: dict, str_list: list) -> list: """Recursively go through geo config to get list ids and combine with their str. An example of hierarchial required geo ids would be: county subdivision: { '<state id>': { '<county id>': {...
2de7df35c975f5842d4c88124e52da2698764a4b
599,457
import six def dict_meta(d): """ Convert a dictionary to metadata. """ return '\n'.join( [': '.join(map(str, [k, v])) for k, v in six.iteritems(d)] )
199dea8c6aa6926abd744e6110a33f68ab3a5062
599,458
import re def check_eth_dest(eth_dests): """Check if --eth-dest option is valied Format of --eth-dest for port X should be 'X,MM:MM:MM:MM:MM:MM'. This options can be given for several ports and 'eth_dests' arg is passed as a double array as below. [['0,ca:a4:45:e7:6a:ee'], ['1,ca:a4:45:e7:6a:...
7098a14c39fcc21d8dfdcfdaf075e8d271568dd1
599,460
def makeWheel(population): """Helper for the RWS in creating a proportional distribution among elements in a given array Args: population(list): List of int/float Returns: list: The generated wheel """ wheel = [] total = sum([p for p in population]) top = 0 ...
54eca37b2ce9b9cb86a593a88163cf4b8bf0c572
599,461
def calc_dims(x, y): """ Given the X and Y bounds generated with calc_bounds() calculate the X and Y dimensions :param x: :param y: :return: The X and Y dimensions """ xd = x[1] - x[0] yd = y[1] - y[0] return xd, yd
bbac0c6fcca157d751817fdbaa832260ee45adb1
599,463
import math def ols(dist, scale, kappa): """Calculate OLS based on distance, scale and kappa.""" e = dist ** 2 / 2 / (scale ** 2 * kappa) return math.exp(-e)
666eb6ba1b4ca4b93953930ebf049d8a76771f51
599,464
def splitparams(path): """Split off parameter part from path. Returns tuple (path-without-param, param) """ if '/' in path: i = path.find(';', path.rfind('/')) else: i = path.find(';') if i < 0: return path, '' return path[:i], path[i + 1:]
fe78bb204b3dba0e710d29c7429b4f57931c34e6
599,466
def rgb_to_RGB(r, g, b): """ Convert rgb values to RGB values :param r,g,b: (0,1) range floats :return: a 3 element tuple of RGB values in the range (0, 255) """ return (int(r * 255), int(g * 255), int(b * 255))
7358f0a0263125c4c036cb6ebc170455c24bf05b
599,467
import re def extract_md5_from_text(text): """ extract base-128 hash from string Args: text(str): string output from gsutil command Returns: hash(str) or None """ m = re.search("[0-9,a-f]{32}", text.lower()) if m: return m.group(0) else: return None
9104d78fc16a25b6a0dc1ed0adb1457c8b56e05f
599,469
def _has_two_cycles( dg ): """ Return True if the input digraph has a 2-cycle and False otherwise. EXAMPLES:: sage: from sage.combinat.cluster_algebra_quiver.mutation_class import _has_two_cycles sage: _has_two_cycles( DiGraph([[0,1],[1,0]])) True sage: from sage.combinat.c...
44cb81cc751ef8ce1d7e79c9565ccaa75d874bb1
599,473
from typing import Union from datetime import datetime def epoch_to_datetime(epoch: Union[int, float, str]) -> datetime: """Converts an epoch timestamp to a datetime object. Args: epoch - (int) Epoch time. Returns: datetime - Datetime equivalent of the epoch provided. """ ret...
bcfc1968b705fc88d8e01a6ba626a27943a7f926
599,475
from typing import Dict from typing import Tuple def encode_and_pad( input_sents: list, word_map: Dict[str, int], word_limit: int ) -> Tuple[list, list]: """ Encode sentences, and pad them to fit word_limit. Parameters ---------- input_sents : list Sentences ([ word1, ..., wordn ]) ...
19cadffd406994b0b50a925dda96d9296f166a29
599,476
def triggers(data_dir: str, include_trg_type: bool = False): """Read in the triggers.txt file. Convert the timestamps to be in aqcuisition clock units using the offset listed in the file (last entry). Parameters: ----------- data_dir - data directory with the triggers.txt file include_t...
98ee96ff675b2935e0d1eea4b6755196e8eacfe1
599,479
def matches(expanded_solution, constraints): """ solution is a tuple of spaces, the output of solve1 constraints is a tuple of values from 1, 0 and -1, that mean: 0 -> OFF 1 -> ON -1 -> not constrained """ for s, c in zip(expanded_solution, constraints): if c ==...
c9c7a4a6e7b6c90e06314884fce7e7827c0a8e11
599,481
def getDagPathIterator(childrenDict, startNode): """Returns an iterator over full paths through a DAG starting at a node. Here DAG stands for directed acyclic graph. A full path is a path for which the last node has no children. """ def isLastChild(node, childIndex): return childIndex == le...
a5da896432f311ecd1db44925b5dca8bde25e015
599,482
def normalize(img): """ Normalize the image """ return (img - 128)/128
cdfd949f62daf7fb921e32533d75b40a26ea2166
599,487
import hashlib def sha256sum(input_file_name): """Computes the SHA256 hash of a binary file Returns the digest string or '' if an error occurred reading the file""" chunk_size = 1048576 # 1 MB file_sha256 = hashlib.sha256() try: with open(input_file_name, "rb") as f: byte = f.r...
67a1aee9fb71a3a2439470b23d8bb207c67fe737
599,492
def get_url(x, y, z, tileserver): """Return the URL to the image tile (x, y) at zoom z.""" return tileserver.format(z=z, x=x, y=y)
1b9f58474cb1ed57167a6168d224bce7a980f0fa
599,493
def is_hyperopt(x): """Check whether a given object is a hyperopt argument The format expected is ('hp_NAME_OF_FUNCTION', 'name for hyperopt', remaining, arguments) """ if isinstance(x, (tuple, list)): if isinstance(x[0], str): s = x[0].split("_", 1) if s[0] == "hp": ...
9d65a04f9ccc694063d44aea8b5b48f5ec272cb7
599,497
from pathlib import Path def cif_ttl(top_dir: Path) -> str: """Read and return CIF-Core minimized Turtle file (generated from the accompanying dictionary). NOTE: The comment conerning the file location has been removed manually from this file. """ return ( top_dir / "tests/dic2owl...
4252dc7f68e6281ef7e227834977689d97c68956
599,498
from typing import Callable from typing import Any import time def time_it(search: Callable[[list, Any], Any], L: list, v: Any) -> float: """Time how long it takes to run function search to find value v in list L. """ t1 = time.perf_counter() search(L, v) t2 = time.perf_counter() r...
8e1869807ade29a99a2be00b6727989165a1e6b8
599,502
def get_rxn_params_dt(rxn, rev=False): """Write evaluation of the forward/reverse reaction rate constant Parameters ---------- rxn : `ReacInfo` The reaction to consider rev : bool, optional If true, get the reverse constant rate constant derivative Returns ------- jline...
1c33285a13ec3710e0f1bfcaba676ef7c4a7d3c2
599,507
import typing def prime_factorize(n: int) -> typing.List[int]: """Prime factorization trial division Parameters ---------- n max n < 10**12 Returns ------- list of factor Notes ----- Time complexity O(√n) References ---------- ..[1] https:/...
ae6bd4087dc6f89817c22fe6a72c086a666b8352
599,511
def safe_get_version(dist): """Get the distribution version, and returns an empty string when this results in a ValueError. This is necessary to avoid crashes when PKG_INFO is missing. @return: a version string """ try: return dist.version except ValueError: ...
987d22844a4316f6cecda6924677282b3aaace77
599,515
from typing import Mapping def flatten_dict(results, delimiter="/"): """ Expand a hierarchical dict of scalars into a flat dict of scalars. If results[k1][k2][k3] = v, the returned dict will have the entry {"k1/k2/k3": v}. Args: results (dict): """ r = {} for k, v in results.i...
e650fe61e48a5c438b834b6b5152b52e565a6bec
599,516
def inverse_interleave(a, b): """ Given a coordinate where `a` has been interleaved and `b` hasn't, return the value that `a` would have at `b=0`. """ if a % 2 == 0: return a + b % 2 else: return a - (b+1) % 2
3b6c767dafcd1a316eb547e714b0cdd5e063400d
599,518
def max_actions(points, action_cost, recover_cost, limit): """ Returns the max number of actions. It will weight the action cost against the available points, adding the recovery cost each time it runs out of points. """ if limit <= 0: actions = 0 elif action_cost <= 0: actions =...
e4fa17838bdd37b096a5bb2e7b43a92c18c98dfb
599,519
def _is_a_vertex_of_polygon(x, y, polygon): """ Check if the `x`/`y` coordinate is a vertex of the `polygon`. >>> polygon = ((0.0, 0.0), (1.0, 0.0), (1.0, 1.0), (0.0, 1.0)) >>> _is_a_vertex_of_polygon(0.0, 0.0, polygon) True >>> _is_a_vertex_of_polygon(0.5, 0.5, polygon) ...
81095fd9d753b4c10f5023523959c4ad89cd7d0e
599,521
def _is_undefok(arg, undefok_names): """Returns whether we can ignore arg based on a set of undefok flag names.""" if not arg.startswith('-'): return False if arg.startswith('--'): arg_without_dash = arg[2:] else: arg_without_dash = arg[1:] if '=' in arg_without_dash: name, _ = arg_without_das...
a058a89836e32e749c3aeb0d583553f90e079185
599,526
import functools from warnings import warn def _deprecated_alias(alias, for_, version): """Create a deprecated alias Parameters ---------- alias : str Name of the alias. for_ : callable New function (replacement). version : str Version in which the feature will be remo...
bfe5c9a07e73d466fc3684c8aafc7541b27000a7
599,533
def get_channel_youtube_url(channel_code): """ Get the Youtube Channel URL given its code Example: UC6gsueJf0YTIF3inlGKWLPg must return: https://www.youtube.com/channel/UC6gsueJf0YTIF3inlGKWLPg """ return "https://www.youtube.com/channel/{:s}".format(channel_code)
3b94e53de783204e718fc4a938c4ec34224d357e
599,534
import re def replace_http(url): """ Replace the http/https in a URL with www. >>> replace_http("http://google.com") www.google.com """ data_regex = re.compile(r"^https?://") if data_regex.match(url) and "www." not in url: data = url.split("//") data[0] = "www." return ''.j...
e9467cf5769a23a3cc5fc31ab0f2e4842b41d0f9
599,537
from typing import Iterable def worker_story(keys: set, log: Iterable) -> list: """Creates a story from the worker log given a set of keys describing tasks or stimuli. Parameters ---------- keys : set A set of task `keys` or `stimulus_id`'s log : iterable The worker log R...
1c1dcdbf1af00cc14498fc74e8f743d2aa3858d4
599,538
def extract_month_of_daily(daily, year, month): """Given daily values, extract a given month Parameters ---------- daily : DataFrame must of columns {'year', 'month'} year, month : int The year and month of interest Returns ------- DataFrame Indexed on days f...
f20c2c5f87a5d3a9300142f97c55aa820820681e
599,544
def sequence_dist(s1, s2): """ the hamming distance between two sequences Arguments ---------- s1: the first sequence s2: the second sequence Both s1 and s2 are lists of tuples with the integer position and the allele s1 and s2 can be the returns of parse_allele(...) Returns ---------- int distance N...
6416718f9b6069cfaf378794303a46fb0e5c6f9d
599,546
def try_int(x): """Safely convert anything that can be converted to int""" try: return int(x) except ValueError: return x
991e3cebf45c76336b851ab6d59d07efcc1842e7
599,548
def create_dictionairy(variables,names): """ Function to create a dictionary with as keys: names and as values: variables. """ params = {} for i in range(0,len(variables)): params[names[i]] = variables[i] return params
69855dbdeddf80aed092ef68d4bc9e0920cd3eb1
599,554
def check_options(options): """ Checks user-supplied keyword options and assigns them Parameters ---------- options : dict Dictionary of options controlling electronic structure code parameters Returns ------- keyword_options : dict Dictionary of options controlling ele...
e1b55fc9d732b7789fe9b32ad49569fe81612047
599,555
def recipe_prior_step(recipe, step): """Compares a recipe and a step, and returns the prior step """ steps = recipe['recipe'] if steps.index(step) == 0: return step return steps[steps.index(step)-1]
e8825373186e0e85551de29d757bef4764e0cf6f
599,556
def eval_align_batchN(model, loader, P=256): """ return: predictList: (N, P) e.g. (N, 256) lossList: (B, ) """ predictList = [] # sample_num x point_num(256) lossList = [] # model.clear_confusion() for data in loader: loss, out = model.test(data, if_eval=True) loss...
f811b7feac627e136181cce0092727d121118ade
599,559
from typing import Optional import collections def parse_content_type(c: str) -> Optional[tuple[str, str, dict[str, str]]]: """ A simple parser for content-type values. Returns a (type, subtype, parameters) tuple, where type and subtype are strings, and parameters is a dict. If the string could not be...
37bfe7571c364b1ad9f70bc63a097b8bfbe637ce
599,560
def readable_duration(nsecs): """ Turn a duration in seconds into a reabable string. """ m = round(nsecs / 60) # return f"{m//60:.0f}h{m%60:.0f}m" return f"{m//60:.0f}:{m%60:02.0f}"
10ac7d88e51eba4252f30a2223f3487a48204649
599,562
import re def make_identifier(name): """Make a string safe to use as an identifier. Valid characters are lowercase alphanumerics and "-". This function may raise ValueError if it can't come up with a suitable identifier. This function is useful for scripts which add things with names. """ if...
fa0c790a2695e4f01660e202bca6d3d70b76cc21
599,565
def row(dict_2d, row_key): """ returns a dict of the contents of row **row_key** of dict_2d """ return dict_2d[row_key]
279566670cf7ae79e1dbdbbdec21d0458427ca7c
599,567
def create_category_dictionary(post): """ This function creates a dictionary from an HTTP Request Post that contains category names as keys and their weights as values. :param post: A dict, the POST from the HTTP Request :return: A dict """ cat_dict = dict() for key, value in post.items(...
6ba0059afcaaaa6df7e477f9f4bdf398af99b899
599,571
def trace_ensembles_for_replica(replica, steps): """ List of which ensemble a given replica was in at each MC step. Parameters ---------- replica : replica ID steps : iterable of :class:`.MCStep` input data Returns ------- list list of ensembles """ ...
8fe800a6c4a1d7b8acf109ceced3920978699085
599,574
def tokenize_de(text,spacy_de): """ Tokenizes German text from a string into a list of strings """ return [tok.text for tok in spacy_de.tokenizer(text)]
84ef624ec72d0677e7669a1daa3d83ac6f1f267e
599,578
def merge_two_dicts(first_dict, second_dict): """ Merges two python dicts by making a copy of first then updating with second. Returns a copy. """ return_dict = first_dict.copy() # start with x's keys and values return_dict.update( second_dict ) # modifies z with y's keys and values &...
a6d8e8d1cfe5b59e78ae48bb732d91031410004b
599,581
import re def _slug_strip(value, separator='-'): """ Cleans up a slug by removing slug separator characters that occur at the beginning or end of a slug. If an alternate separator is used, it will also replace any instances of the default '-' separator with the new separator. """ separato...
e60d83df1b6b11a888ef44cb297e895a4f9715ff
599,585
import socket def check_ip(addr): """Check if ip address is correctly formatted Args: addr (str): Returns: True of False """ try: socket.inet_aton(addr) return True except socket.error: return False
1ba2a09db259cc948cfa57338bc17de17f166791
599,586
import random def randweight(vals): """ Chooses alternative at random applying weigths for each alternative; values are given as a dict with {opt:weight} """ wgtsum = sum(vals.values()) randres = random.randint(1, wgtsum) check = 0 for key in vals.keys(): check += vals[key] ...
f4c9bd59356aa32f40df9ba0cb0bb85200337c91
599,587
def rightmost_from_read(read): """Function that takes as input a read a returns its rightmost mapping position""" rightmost = 0 #matches, deletions and ref skip consume reference for cigar in read.cigar: if cigar[0] == 0: rightmost += cigar[1] elif cigar[0] == 2: ...
d04186cc9172046fccec8e74c48522051a819ea3
599,597
def get_estimated_scale(scale_filename): """Read the estimated scale from file.""" with open(scale_filename) as scale_file: lines = scale_file.readlines() # We use the latest estimated scale. return float(lines[-1].split(' ')[1])
209bf4ac372bfe8b6432e4c4a6f35c5c20c6565c
599,598
import functools import time def timeit(func): """ This function can be used as a decorator as @timeit. It will print out how long the function took to execute. :param func: The decorated function :return: The wrapped function """ @functools.wraps(func) def new_func(*args, **kwargs):...
74f4e4f5e8cf26f4d6710ae5fc20453e10e630ea
599,599
import torch def get_lookahead_mask(padded_input): """Creates a binary mask for each sequence which maskes future frames. Arguments --------- padded_input: torch.Tensor Padded input tensor. Example ------- >>> a = torch.LongTensor([[1,1,0], [2,3,0], [4,5,0]]) >>> get_lookahea...
aadae58fa98f2c8450acbf05ccd40ccd13de9c6f
599,602
def canberra(v1, v2): """ Computes Canberra distance between two points. http://en.wikipedia.org/wiki/Canberra_distance """ return sum(( (abs(v[0] - v[1]) / (abs(v[0] + abs(v[1])))) for v in zip(v1, v2)))
890e3cfd021549067ed845396079a3053126f69f
599,603
def get_update_components(options): """ Same as get_insert_components but for update queries. Returns a tuple in the form (placeholders, values) to be used as follows: c.execute('UPDATE Table SET {placeholders}', values)""" placeholders = ','.join( '{}=?'.format(opt[0]) for opt in options ) values = tuple(opt...
088a462777e4f656e4d11ab8eaa4d511277377b4
599,608
def generate_grid_coordinates(feature_length): """ A list is created with each element corrosponding to a coordinate of a feature_length x feature_length grid. The list is then broken up into roughly equal chunks so each chunk can be sent to a different core. Parameters ---------- feature...
43fe20bd2f046e660b541a5fd7ff5a67b18595f5
599,618
import re def _parse_strand_label(s:str) -> list[str]: """Breaks a strand label specifiction in to a list of labels Args: s (str): see get_strand_ids() for details Returns: list[str]: list of strand labels. """ clean_s = re.sub("[(]+", "(", re.sub("[)]+", ")", s)) is_combo...
697389ef2d3d4aaaf582192ef945340c27d27536
599,620
def str2sec(time_str): """ Convert hh:mm:ss to seconds since midnight :param time_str: String in format hh:mm:ss """ split_time = time_str.strip().split(":") if len(split_time) == 3: # Has seconds hours, minutes, seconds = split_time return int(hours) * 3600 + int(minutes...
c55290e294742e33a38f47edcb1ad4548c9d3042
599,621
def depth_first_search(root, visit=lambda node: False, traversable=lambda node, edge: True): """ Simple, multi-purpose depth-first search. Visits all the nodes connected to the root, depth-first. The visit function is called on each node. Recursion will stop if it returns True, and ubsequently dfs...
221e4b1b296540fa8ff57d44793f337e171dda70
599,624
import yaml def load_metadata(yaml_file, metadata_path : str ='pdfs'): """ Returns a dict where - the key is the filename and - the value is the information about the document """ d = yaml.safe_load(yaml_file) return dict([(v['filename'], v) for v in d[metadata_path]] )
aa8905fe1c227df41544c43667187fcf8ca100b6
599,625
def replace_insensitive(string, target, replacement): """ Similar to string.replace() but is case insensitive.""" no_case = string.lower() index = no_case.rfind(target.lower()) if index >= 0: return string[:index] + replacement + string[index + len(target):] else: # no results so return the...
3555e0c4fea0b9d5c2aad0debabd76cc15518448
599,633
from typing import Union from typing import Tuple def parse_deformation_potential( deformation_pot_str: str, ) -> Union[str, float, Tuple[float, ...]]: """Parse deformation potential string. Args: deformation_pot_str: The deformation potential string. Can be a path to a deformation.h5...
f801e72f4a9ac26905ba55e4e200110429f7ad13
599,635
def ij(n): """Returns upper triangular indices for looping over a square matrix""" rn = range(n) return [ (i,j) for i in rn[0:-1] for j in rn[i+1:n] ]
6a8b5449fab8370eb6859a254af3d4c6e6a0c365
599,638
def _unit_change(value_to_be_changed, unit): """ Changes value based on given unit Parameters ---------- value_to_be_changed : float value that is returned once it is changed unit : string unit the value should be converted to """ if unit is 'micro': return value_...
bf637eaf105628f8c1a6e7d958f51d229fe7f168
599,641
from operator import mul def is_mul(var): """ Match a variable with `x * y * z * ...`. Parameters ---------- var The Variable to analyze. Returns ------- object A list [x, y, z, ...] if `var` is of the form `x * y * z * ...`, or None if `var` cannot be cast in...
6713e138039bc7625f2b03cf94ca36da389e31fa
599,644
def chats(cursor): """Returns a dict of chats that form (ROWID, guid) pairs.""" sql_chats = cursor.execute("SELECT ROWID, guid FROM chat").fetchall() all_chats = dict() for chat in sql_chats: rowid, guid = chat all_chats[rowid] = guid return all_chats
d9ea5d9aba51e15e25571719bef0f75429dc0c61
599,648
def lines(text): """ Returns each non-blank line in text enclosed in a list. See http://pypi.python.org/pypi/textdata for more sophisticated version. """ return [l.strip() for l in text.strip().splitlines() if l.strip()]
c24b7ec8a7078c5fbf58f9c6707cf79d714c55fd
599,650
def BPyMesh_meshWeight2List(vgroup, me): """ Takes a mesh and return its group names and a list of lists, one list per vertex. aligning the each vert list with the group names, each list contains float value for the weight. These 2 lists can be modified and then used with list2MeshWeight to apply the chang...
86f5dcf07dcf62169fad5b59e381e9758c9dc7db
599,652
def mod(x:float, y:float, z:float=0.0) -> float: """ Return the remainder on division of x by y with offset z. Note, float value is returned """ return x - ((x - z) - (x - z) % y)
2fd703413fed6e91ac0272f27839748ce4f3eeee
599,654
def find_degree(poly_list): """ Finds the degree needed for the Macaulay matrix Parameters ---------- poly_list : list Polynomials that will be used to construct the matrix. Returns ------- int Needed degree for Macaulay matrix. Notes ------- For polyno...
eb111630789a0d59a2885daca63c436e50aa1d69
599,655
def substring_list(s, k): """ Takes a string, s, and and length, k, and returns a list of all the substrings in s of length k (including overlap). >>> substring_list('abcdefg', 2) ['ab', 'bc', 'cd', 'de', 'ef', 'fg'] """ my_list = [] # create empty list ...
da1f7a1e261d07b1aef27ee653ff0b29e42ea147
599,658
import re def collect_all_links(section_with_all_links, regex_skip_sections_start, regex_skip_sections_end): """ Goes through a section and extract all inlined links it can found. :param section_with_all_links: An array of lines representing a section. For this...
75453bc53261001db7a3bf5f34215e1460e83338
599,659
def build_message(valid_dm): """ Build notification message """ message = ''' The following domains are setup on the staging environment without the meta tag robots noindex/nofollow.\n Action is required!\n\n''' for domain in valid_dm: message += "- "+domain+"\n" return message
01f48ef0dfe869a44dcd99067edaa90f74482bce
599,661