content
stringlengths
39
14.9k
sha1
stringlengths
40
40
id
int64
0
710k
import re def _has_no_hashtag(href): """ Remove sub chapters :Param href: tags with the `href` attribute :Return: True if `href` exists and does not contain a hashtag else return False """ return href and not re.compile("#").search(href)
ef84c7db899a711421d1f1c5a42cfc7b7a91b22d
678,953
def orm_query_keys(query): """Given a SQLAlchemy ORM query, extract the list of column keys expected in the result.""" return [c["name"] for c in query.column_descriptions]
cf9dbe457d369e6da3f83c4cdf74595ad8dcbc83
678,954
def ParsePrimitiveArgs(args, arg_name, current_value_thunk): """Parse the modification to the given repeated field. To be used in combination with AddPrimitiveArgs; see module docstring. Args: args: argparse.Namespace of parsed arguments arg_name: string, the (plural) suffix of the argument (snake_case)...
bfc456f5e6a0c4110a144e2cb38cf01a5e59bfc4
678,955
def select_text_color(r, g, b): """ Choose a suitable color for the inverse text style. :param r: The amount of red (an integer between 0 and 255). :param g: The amount of green (an integer between 0 and 255). :param b: The amount of blue (an integer between 0 and 255). :returns: A CSS color in...
a8663b261c0d6ae087d08e8ecb67a77d51935b10
678,960
def point_to_geojson(lat, lng): """ Converts a single x-y point to a GeoJSON dictionary object of coordinates :param lat: latitude of point :param lng: longitude of point :return: dictionary appropriate for conversion to JSON """ feature = { 'type': 'Feature', 'geometry': { ...
7ff10caab2ea92bd64d1532cac819205806e9e74
678,961
from typing import Mapping def nop(string: str, _: Mapping[str, str]) -> str: """No operation parser, returns given string unchanged. This exists primarily as a default for when no parser is given as the use of `lift(str)` is recommended when the parsed value is supposed to be a string. :param s...
aae2cf22a40a43ff22c3230c1df84f376b1ef245
678,971
import socket def authenticate(port, password): """ Authentication function used in all testcases to authenticate with server """ s = socket.socket(family=socket.AF_INET, type=socket.SOCK_DGRAM) s.sendto(b"AUTH %s" % password, ("127.0.0.1", port)) msg, addr = s.recvfrom(1024) return (s, ms...
6507f295fd047ce87eb96569edb09dd9f7e777df
678,972
import grp def groupmembers(name): """Return the list of members of the group with the given name, KeyError if the group does not exist. """ return list(grp.getgrnam(name).gr_mem)
17ee78b80a6c2b6801c4223931cee223d1e42f70
678,973
import math def rotate_point(angle, point, origin): """ Rotates a point about the origin. Used from http://stackoverflow.com/q/8948001/1817465 mramazingguy asked Jan 20 '12 at 21:20 :param angle: cw from E, in degrees :param point: [x, y] :param origin: [x0, y0] :return: The point, rotat...
37b8ff9c2ca6f2dc87125ff1ddd14e58eb09f324
678,974
def did_to_dirname(did: str): """ Takes a Rucio dataset DID and returns a dirname like used by strax.FileSystemBackend """ # make sure it's a DATASET did, not e.g. a FILE if len(did.split('-')) != 2: raise RuntimeError(f"The DID {did} does not seem to be a dataset DID. " ...
6d37bdc2eda19af6f2791fad7084b64bdc688278
678,976
def parse_genome_size(txt_file): """Pull out the genome size used for analysis.""" with open(txt_file, 'rt') as txt_fh: return txt_fh.readline().rstrip()
f386898478393596e28e6e6d47a7da372a8f6b98
678,979
async def present( hub, ctx, name, lock_level, resource_group=None, notes=None, owners=None, connection_auth=None, **kwargs, ): """ .. versionadded:: 2.0.0 .. versionchanged:: 4.0.0 Ensure a management lock exists. By default this module ensures that the management ...
531f849dc50c4b521e7c1b707e0737b05005bb0f
678,980
def sort_set_by_list(s, l, keep_duplicates=True): """ Convert the set `s` into a list ordered by a list `l`. Elements in `s` which are not in `l` are omitted. If ``keep_duplicates==True``, keep duplicate occurrences in `l` in the result; otherwise, only keep the first occurrence. """ if kee...
0b43367f178e6f69b40c62bc67af760c82ef9206
678,981
import pytz def IsValidTimezone(timezone): """ Checks the validity of a timezone string value: - checks whether the timezone is in the pytz common_timezones list - assumes the timezone to be valid if the pytz module is not available """ try: return timezone in pytz.common_timezones ex...
9e2d8855b710f0d087d04a12a936f6979bc7c5d7
678,989
def xp_to_level(level: int): """Returns the amount of EXP needed for a level. Parameters ---------- level: int The level to find the amount of EXP needed for. Returns ------- int: The amount of EXP required for the level. """ return (level ** 3) // 2
764f6854788dda44277d76e0850c71999a433510
678,994
def gpu_size(wildcards, attempt): """Return model size in gb based on {prot} and {model}""" prot = wildcards.get('prot', 'V3') model = wildcards.get('model', 'protbert') if 'bert' not in model: return 0 if prot == 'V3': return 9*attempt return 12*attempt
02ac56ebf661a1ff6e7e6c024ce6c491d5c8ae42
678,997
def is_prime(P): """ Method to check if a number is prime or composite. Parameters: P (int): number to be checked, must be greater than 1 Returns: bool: True if prime, False if composite """ for i in range(2, P): j = P % i if j == 0: ...
674c39005e62ce7c8d53497b8c0f7aafade730a0
679,000
def h(number): """ convert a number to a hex representation, with no leading '0x'. Example:: assert h(16) == '10' assert hex(16) == '0x10' """ return "%02x" % number
60a5221f2b8dea8f5fdb9573cb4f9e5eb83c238f
679,002
def add_feature_transaction_completed_ratio(profile_updated_df): """ Create feature transcation count to offer completed ratio to avoid np.inf as a result of division, a 0.1 number was added to the denominator """ profile_updated = profile_updated_df.copy() profile_updated['transaction_complet...
88bfc6bf35050dfe0b114a55342137fd16af9af5
679,003
from typing import Sequence def max_len( row: Sequence) \ -> int: """ Max `len` of 1d array. """ return max(len(str(x)) for x in row)
4ad559b67422480360be0c58a374cec96ef6fcbc
679,006
def calculate_air_density(pressure, temperature): """ Calculates air density from ideal gas law. :param pressure: Air pressure in Pascals :param temp: Air temperature in Kelvins :return density: Air density in kg/m^2 """ R = 286.9 # specific gas constant for air [J/(kg*K)] density...
dbc861eff42847ddf63b27e38f5250cd3a1f8fa0
679,007
import pprint def api_message_to_javadoc(api_message): """ Converts vpe.api message description to javadoc """ str = pprint.pformat(api_message, indent=4, width=120, depth=None) return " * " + str.replace("\n", "\n * ")
ca5d862f216ff52f12db8365a520fee8e40b515b
679,008
def set_ranks(taxonomy): """Set ranks for species/subspecies creation.""" default_ranks = [ "genus", "family", "order", "class", "subphylum", "phylum", ] taxon_rank = None if "subspecies" in taxonomy: ranks = ["species"] + default_ranks ...
00a13aa72773efa3928a0cf67d161aeb98a64ad2
679,011
def read_xyz(filepath): """ Reads coordinates from an xyz file. Parameters ---------- filepath : str The path to the xyz file to be processed. Returns ------- atomic_coordinates : list A two dimensional list containing atomic coordinates """ with ...
d699c0d7ef084fca4f9d37d5de39ff4fd9e43adc
679,013
def get_adaptive_eval_interval(cur_dev_size, thres_dev_size, base_interval): """ Adjust the evaluation interval adaptively. If cur_dev_size <= thres_dev_size, return base_interval; else, linearly increase the interval (round to integer times of base interval). """ if cur_dev_size <= thres_dev_size: ...
8ddb8d0fb850eccc37936bfb7dc3e3581b9e95e7
679,014
def convert88to256(n): """ 88 (4x4x4) color cube to 256 (6x6x6) color cube values """ if n < 16: return n elif n > 79: return 234 + (3 * (n - 80)) else: def m(n): "0->0, 1->1, 2->3, 3->5" return n and n + n-1 or n b = n - 16 x = b % 4 ...
5725c77c40020504a71f6eea5127b2895e475db2
679,016
def standard(X): """ standard : This function makes data ragbe between 0 and 1. Arguments: X (numoy array) : input data. -------- Returns: standard data. """ xmin = X.min() X = X-xmin xmax = X.max() X = X/xmax return X
3559b6ec7be4bfd6729b827cdf671b20c5361939
679,018
def list_to_sql_in_list(l): """Convert a python list into a string that can be used in an SQL query with operator "in" """ return '(' + ','.join(f"'{e}'" for e in l) + ')'
01d773406923e77d5d2e5343243f4411e55fd038
679,019
def any(seq, pred=None): """Returns True if pred(x) is true for at least one element in the iterable""" for elem in filter(pred, seq): return True return False
3f878aeceb4f924b5209738f6336e674feb39209
679,024
def vectorize(tokens, vocab): """ Covert array of tokens, to array of ids Args: tokens (list): list of tokens vocab (Vocab): Returns: list of ids """ ids = [] for token in tokens: if token in vocab.tok2id: ids.append(vocab.tok2id[token]) else: ...
da0c86638f898cf1fff594a3e85b9988a79cd9d3
679,028
def generate_symbol_definitions_direct(symbols, prefix): """Generate a listing of definitions to point to real symbols.""" ret = [] for ii in symbols: ret += [ii.generate_rename_direct(prefix)] return "\n".join(ret)
50eed2e86d50462dcb4c16ed335692422349f85c
679,029
import re def cleanOfSpaces(myString): """Clean a string of trailing spaces""" myString = re.sub("^( )+", "", myString) myString = re.sub("( )+$", "", myString) return myString
587945d3afd294622b5a407271e2785a2ac4dd1e
679,030
def get_build_os_arch(conanfile): """ Returns the value for the 'os' and 'arch' settings for the build context """ if hasattr(conanfile, 'settings_build'): return conanfile.settings_build.get_safe('os'), conanfile.settings_build.get_safe('arch') else: return conanfile.settings.get_safe('os_b...
0411ba597fc770bbc6a8c77da27c33b87d32857c
679,031
def observe_rate(rate, redshift): """Returns observable burst rate (per day) from given local rate """ return rate / redshift
13be6db3b3db0763a73be2b8381acb98f6f0ad54
679,033
from typing import Counter def find_occurrences(number_list): """Finds how many times every number in a list occurs.""" counter = Counter(number_list) occurrences = counter.most_common() return occurrences
26c6931d7652d2f60469c36ae6b9c29c3bcb49a9
679,036
def add_vectors(v1, v2): """ Adds 2 vector :param v1: vector 1 :param v2: vector 2 :return: v1 + v2 """ return tuple([v1[i] + v2[i] for i in range(0, len(v1))])
491448bd744638af2ee8b1382d6b4797f29578ed
679,038
def _get_issue_tracker(obj): """Get issue_tracker dict from obj if dict is based on existing tracker""" if not obj: return None ret = obj.issue_tracker if not ret.get('_is_stub'): return ret return None
8e8d490f48d51be88706bf83121c4055c46ac5fd
679,039
import random def ordered(parent1, parent2, point=None): """Return a new chromosome using ordered crossover (OX). This crossover method, also called order-based crossover, is suitable for permutation encoding. Ordered crossover respects the relative position of alleles. Args: parent1 (Li...
11d551c79a92b3f592b223a08c2d177eb2c26dd2
679,042
def _weighted_sum(*args): """Returns a weighted sum of [(weight, element), ...] for weights > 0.""" # Note: some losses might be ill-defined in some scenarios (e.g. they may # have inf/NaN gradients), in those cases we don't apply them on the total # auxiliary loss, by setting their weights to zero. return su...
2fd019caacb8fa36df676dae27243e2962c2cb4a
679,047
def rh_from_avp_svp(avp, sat_vp): """ Calculate relative humidity as the ratio of actual vapour pressure to saturation vapour pressure at the same temperature. See Allen et al (1998), page 67 for details. :param avp: Actual vapour pressure [units do not matter so long as they are the same ...
8ea0832133bae4705371ee98f2aaff35847cb92e
679,048
from datetime import datetime def str_to_timestamp(time_as_str, time_format) -> float: """转换时间字符串为unix时间戳 Args: time_as_str: 时间字符串, 比如: 2019-09-10 15:20:25 time_format: 时间格式, 比如: %Y-%m-%d %H:%M:%S Returns: unix时间戳, 类型: float """ datetime_ = datetime.strptime(time_as_str, ti...
f7a4b9458533a32f2e9ebe21645aa11928233ca2
679,056
from typing import OrderedDict def remove_signature_parameters(s, *param_names): """ Removes the provided parameters from the signature s (returns a new signature instance). :param s: :param param_names: a list of parameter names to remove :return: """ params = OrderedDict(s.parameters.it...
d6cd0a9f5da055a4e278915c892c730eb04ee36a
679,059
def frequencies_imp(word_list): """ Takes a list of words and returns a dictionary associating words with frequencies of occurrence """ word_freqs = {} for w in word_list: if w in word_freqs: word_freqs[w] += 1 else: word_freqs[w] = 1 return word_freqs
78c4628da3a280d621086745849e6260e68176fe
679,062
def transforms_are_applied(obj): """ Check that the object is at 0,0,0 and has scale 1,1,1 """ if ( obj.location.x != 0 or obj.location.y != 0 or obj.location.z != 0 ): return False if ( obj.rotation_euler.x != 0 or obj.rotation_euler.y != 0 or obj.rotation_euler.z != 0 ): retu...
411a5c0211c6a0b6833352e8566814958a8adaab
679,064
def get_distinct_values(df, key): """Get the distinct values that are present in a given column.""" return sorted(list(df[key].value_counts().index.values))
0833a6024f34faa28fb45d73b7ad7e22ac7ba541
679,066
def get_path_array(node): """ Takes an end node and gives you every node (in order) for the shortest path to it. PARAMS: node (node): end node RETURNS: array[nodes]: every note you need to visit (in order) """ if node.shortest_path_via == None: return [node] else: ...
0633fc9bb7e043e57a8356a23807495c7c975d14
679,067
def decode_prefix(byte): """Decode a byte according to the Field Prefix encoding scheme. Arguments: byte: the encoded representation of the prefix Return: fixedwidth: Is the field fixed width (bool) variablewidth: if not fixed width, the number of bytes needed to en...
7808dafcec1dca1dfb28733ccc9822f0b543531e
679,074
import requests def ct_get_lists(api_token=""): """Retrieve the lists, saved searches and saved post lists of the dashboard associated with the token sent in Args: api_token (str, optional): you can locate your API token via your crowdtangle dashboard under Settings...
6d3e0c5524f217a1c24bc6b7dd02710393e77329
679,075
def build_endpoint_description_strings( host=None, port=None, unix_socket=None, file_descriptor=None ): """ Build a list of twisted endpoint description strings that the server will listen on. This is to streamline the generation of twisted endpoint description strings from easier to use command lin...
c0434271ca8fc73ea81daea3936d827c520adbf9
679,078
def force_charge_fit(mol, current_rule, match): """ Forces the formal charges of a rule to match the formal charges of a molecule. Parameters ---------- mol: rdkit.Chem.Mol RDKit molecule object. current_rule: rdkit.Chem.Mol RDKit molecule object of rule match: tuple ...
885f145a8d5dbadc2c416263dc12180e10bb8ddb
679,079
def dataframe_map_module_to_weight(row) -> int: """ Return the weight of a given module from a dataframe row based on the module level and the module name (since the final project is worth more). Args: row (dataframe row): A row from a dataframe containing at least two ...
13457032a2a5b65d64bf0824ff44cc7258ac6a2e
679,080
def is_foreign_key(col): """Check if a column is a foreign key.""" if col.foreign_keys: return True return False
e702484a7b87da5ff7ef3e605934b83355d99156
679,085
def _build_body(res): """ Build the body of the Exchange appointment for a given Reservation. :type res: resources.models.Reservation :return: str """ return res.event_description or ''
e2f25393560acb803e4002019ca95f27491a6013
679,090
def mm_as_m(mm_value): """Turn a given mm value into a m value.""" if mm_value == 'None': return None return float(mm_value) / 1000
7c5525b1e16801f67ee76484a2471ac3f6c17c40
679,091
def verify_positive(value): """Throws exception if value is not positive""" if not value > 0: raise ValueError("expected positive integer") return value
7ee10a0a7d760972e791a0e8b2d0f82e38ec297c
679,093
def get_devices_dict(version, image=None, arch=None, feature=None): """Based on version and image, returns a dictionary containing the folder location and the patterns of the installation files for each device type :param version: build version, e.g. 6.2.3-623 :param image: optional, 'Autotes...
104fb35f8abe4cbe2e6cb1297a3cc778d229d0ed
679,094
def close_enough(v1,v2): """ Helper function for testing if two values are "close enough" to be considered equal. """ return abs(v1-v2) <= 0.0001
d52322cf9ac3bbe17af51af73bf52d8308071c18
679,100
def map_onto_scale(p1, p2, s1, s2, v): """Map value v from original scale [p1, p2] onto standard scale [s1, s2]. Parameters ---------- p1, p2 : number Minimum and maximum percentile scores. s1, s2 : number Minimum and maximum intensities on the standard scale. v : number ...
4b51f16ba7fada925ca9c98169b2064791c7d027
679,105
def _read_phone(text_path): """Read phone-level transcripts. Args: text_path (string): path to a transcript text file Returns: transcript (string): a text of transcript """ # Read ground truth labels phone_list = [] with open(text_path, 'r') as f: for line in f: ...
594377ccf4fd3c10425d05b7c73492f12ddf65b3
679,106
def pytorch_array_to_scalar(v): """Implementation of array_to_scalar for pytorch.""" if v.is_cuda: v = v.cpu() return v.detach().numpy()
a920e6f75583e75c9dbd21977bed00ee9f5f3920
679,108
def create_tagging_decorator(tag_name): """ Creates a new decorator which adds arbitrary tags to the decorated functions and methods, enabling these to be listed in a registry :param tag_name: :return: """ def tagging_decorator(*args, **kwargs): # here we can receive the parameters hand...
26a6b424700dfd79057c1387e108c182e43ef4b5
679,113
def incr(num): """ Increment its argument by 1. :param num: number :return: number """ return num + 1
fd6e1868329b056edeaeab2741030f973a4ea704
679,117
from datetime import datetime def convertDateToUnix(dstr): """ Convert a given string with MM/DD/YYYY format to millis since epoch """ d = datetime.strptime(dstr, '%m/%d/%Y') return int((d - datetime.utcfromtimestamp(0)).total_seconds() * 1000)
a477a20575d05bb268f41e302623b0de721d0856
679,119
def split_text(txt, trunc=None): """Split text into sentences/words Args: txt(str): text, as a single str trunc(int): if not None, stop splitting text after `trunc` words and ignore sentence containing `trunc`-th word (i.e. each sentence has len <= trunc)...
f900d3b75dc541e1aed1326674939f65fc3b0900
679,121
def get_auth_dict(auth_string): """ Splits WWW-Authenticate and HTTP_AUTHORIZATION strings into a dictionaries, e.g. { nonce : "951abe58eddbb49c1ed77a3a5fb5fc2e"', opaque : "34de40e4f2e4f4eda2a3952fd2abab16"', realm : "realm1"', qop : "auth"' } """ amap =...
adb2c6dbcea429ae94c133b5b00148236da216e2
679,124
def build_anthology_id(collection_id, volume_id, paper_id=None): """ Transforms collection id, volume id, and paper id to a width-padded Anthology ID. e.g., ('P18', '1', '1') -> P18-1001. """ if ( collection_id.startswith("W") or collection_id == "C69" or (collection_id == "D...
6dd268b3de74a92849a14db99190588e7c7eb36f
679,125
from typing import Any def assert_key_for_scope(scope: str): """Checks that a key of the given name and type is present in a config.""" def assert_key(config: dict, key: str, instance: Any) -> None: if not isinstance(config.get(key), instance): raise KeyError(f"Missing {key} in {scope}") ...
55ab2c307b1c81b65cad9d1e7a487983924e008e
679,127
def BFSUtility(obj,visited,vertex): """Utility function for Breadth First Search Algorithm.""" stack = [] subGraph = [] stack.insert(0,vertex) visited[vertex] = True while(stack): subGraph.append(stack.pop()) for nbrVertex in obj.adjList[subGraph[-1]]: if visited[nbrV...
cd3beec5e9afaa23a8989728957658680422bf23
679,130
def get_string_before_delimiter(string, delimiter): """ Returns contents of a string before a given delimiter Example: get_string_before_delimiter("banana-kiwi", "-") returns "banana" """ if delimiter in string: return (string[:string.index(delimiter)]).strip() else: retu...
97b5da492834a62c5648f76002e690b659d3ab38
679,132
import json def test_json(filename): """Verify that given filename is valid JSON; if not, return None.""" try: with open(filename, 'r') as f: data = json.load(f) except Exception as e: print(e) data = None return data
85ba7b7366322d02e9e983f4d6ad57c6dbed8371
679,133
def contains(seq, value): """ Description ---------- Checks to see if a value is in the sequence or dictionary. Parameters ---------- seq : (list or tuple or set or dict or string) - sequence/dictionary to search in\n value : any - value to search for Returns ---------- boo...
ca408206626d230ac5c59157f9012046071fd164
679,140
def stage_title(stage): """Helper function for setting the title bar of a stage""" stage_txt = ("Name", "Vocation", "Character Design and Details", "Stats and Skills", "All Done: Thank You!") stage_cmd = ("{w@add/name <character name>{n", "{w@add/vocation <character's vocation>{n", ...
badd7ad6a59c52a0bbc4f186aca7fd4c653a0910
679,143
from functools import reduce import operator def get_location(nested_dict=None, keys_list=None): """ Description ----------- Static function to get a value of a nested key from a nested dictionary :param nested_dict: Nested dictionary from which the nested value is to be retrieved :param keys_...
f86dd324d1c0d05af4101c14a7c6803efd5322fb
679,145
def add_weight_decay(model, weight_decay=1e-5, skip_list=()): """Splits param group into weight_decay / non-weight decay. Tweaked from https://bit.ly/3dzyqod :param model: the torch.nn model :param weight_decay: weight decay term :param skip_list: extra modules (besides BN/bias) to skip :ret...
786993f755adabf09b34a36bade30cbad71d76ce
679,149
from typing import List def remove_stubs(packages: List[str]) -> List[str]: """Remove type stubs (:pep:`561`) from a list of packages. >>> remove_stubs(["a", "a.b", "a-stubs", "a-stubs.b.c", "b", "c-stubs"]) ['a', 'a.b', 'b'] """ return [pkg for pkg in packages if not pkg.split(".")[0].endswith("...
20f5c1e203db1cf10cb21932ac5c600a41a15438
679,151
def to_csv(dictionary, filename=None, headers=None, nm=False): """ Save spectral data as csv. Parameters ---------- dictionary : dict The dictrionary containing spectral data. Get using Image.get_spectral_data() The epected unit for wavelength is Angstrom. filename : str...
8ef3e3ba56b18035ae3052003e671e747a7c0077
679,154
from pathlib import Path def get_tf_version(tf_path): """ Traverse “up” the given directory tree looking for a .terraform-version file and return its contents, raise an exception if we reach root without having found anything. """ current_path = tf_path while current_path != Path('/'): ...
10db32a2701fd8577589afe5f8fb8ff64bbeda97
679,167
def combine(hi, lo): """Combine the hi and lo bytes into the final ip address.""" return (hi << 64) + lo
0662305da0f258e67d5e9abf31a875dc9d605df6
679,168
def assert_equal_length(psg, hyp, sample_rate): """ Return True if the PSG and HYP have equal lengths in seconds """ return psg.shape[0] / sample_rate == hyp.total_duration
968776dee6058b137c3c4445e0e8e87b4223e96c
679,172
async def time_event() -> dict: """Create a mock time_event object.""" return { "id": "290e70d5-0933-4af0-bb53-1d705ba7eb95", "bib": 1, "event_id": "event_1", "name": "Petter Propell", "club": "Barnehagen", "race": "race_name", "race_id": "race_1", ...
494c9f9ed57535b5e1b607ee5055764947d9e69a
679,175
def convert_8_to_16(value): """Scale an 8 bit level into 16 bits.""" return (value << 8) | value
e94dc436c96a7b9aae006679f85d4872d702823d
679,176
def size_of(rect): """Return size of list|tuple `rect` (top, left, bottom, right) as tuple (width, height)""" return (rect[3] - rect[1], rect[2] - rect[0])
07f50d974e74efca3b7985822fe3b3c84cdc2538
679,177
import re def uncolorize(s): """ Remove ANSI color escape codes from the string `s` and return the result. Works with text colorized with the `colorama` module. """ return re.sub("\033\[([0-9]+;)*[0-9]*m", "", s, flags=re.UNICODE)
5ea4b0c5f1b011d0947af69a5579f2804ca10a24
679,178
import numbers def is_number(a): """Check that a value `a` is numeric""" return isinstance(a, numbers.Number)
0ae599682dad264c6705e0f37dc15969628db9ca
679,180
def transform_len(val, default=None): """ Calculate length <dotted>|len len(val) or raises <dotted>|len:<default> len(val) or <default> """ try: return len(val) except TypeError: if default is not None: return default raise ...
dbdd0757b387214c44a8341ac5b8b56e741a3b7c
679,181
from typing import Iterable def nested_depth(iterable:Iterable) -> int: """ calculate the nested depth of an iterable Args: iterable (Iterable): the iterable to calculate the depth of Returns: int: the depth """ depth_func = lambda L: isinstance(L, (list, tuple)) and max(map(...
47e60775c67e55c43d55d8b34d07a7e17c101d6d
679,182
def post_process_fieldsets(context, fieldset): """ Removes a few fields from FeinCMS admin inlines, those being ``id``, ``DELETE`` and ``ORDER`` currently. Additionally, it ensures that dynamically added fields (i.e. ``ApplicationContent``'s ``admin_fields`` option) are shown. """ # abort i...
714145bb42fc4c685a54998700445d7c8a96f5e8
679,183
def sos_gradient(params): """Calculate the gradient of the sum of squares function.""" return 2 * params["value"].to_numpy()
7a16dde8638b397c8caabd0f359bc6ca0e477216
679,186
import numbers def commanum(v): """ Makes large numbers readable by adding commas E.g. 1000000 -> 1,000,000 """ if isinstance(v, numbers.Number): return "{:,}".format(v) return v
202b3b5cabdbb347b7491583c03badddd879fc7c
679,187
import glob def createPlotString(postAnalyzerPath, description): """ Create the plotFile readable by the PostPlot*.py program. Args: postAnalyzerPath: Path to the output from PostAnalyzer description: description of the results (for instance canonical or submatrix) ...
b635d273150eb3fa3d14d53cde2ea8ac34f02f08
679,188
import math def vector_normalize(vect=()): """ Generates a unit vector from the input. :param vect: input vector :type vect: tuple :return: unit vector :rtype: list """ if not vect: raise ValueError("Input argument is empty.") sq_sum = math.pow(vect[0], 2) + math.pow(vect[1],...
35ad0aec6bc6e5c2856ab0d93d32120435a9767f
679,194
from typing import List def remove_nulls(obj): """Recursive function to remove nulls in a dict.""" if isinstance(obj, List): return [remove_nulls(list_item) for list_item in obj] if not isinstance(obj, dict): return obj return {k: remove_nulls(v) for k, v in obj.items() if v is not Non...
f052b45a65fc39095959d37ad17fc1180dac792d
679,198
def are_disjoint(sa, sb): """ :param sa: set 1 :param sb: set 2 :return: True if two sets are disjoint, otherwise False """ return True if sa & sb == set() else False
4a410a3246766781ead5ca007f3f31bc15d72e4b
679,199
def create_coordinate_matrix(sp, xn, yn, lons, lats): """ Creates xn times yn matrix of GNSS points. :param sp: Starting GNSS point. :param xn: Number of rectangles (columns). :param yn: Number of rectangles (rows). :param lons: Longitude step. :param lats: Latitude step. :return: Matrix...
c0c8a4475c24f19db4db743be11488af7295c991
679,201
def sanitize_identifier_for_cpp(identifier: str) -> str: """ Convert the provided identifier to a valid C++ identifier :param identifier: the name which needs to to sanitized :return: str: sanitized identifier """ if not identifier: return '' sanitized_identifier = list(identifi...
cb7bbd26efd9a20a6f230bb2979a2701b089ac79
679,205
def readfile(filename, current_dir_path): """Return the contents of a file as a string given a Path object to it. Parameters ---------- filename : str Name of the file to read. current_dir_path : Path pathlib.Path object for where the file is found on the system. """ file_pat...
7e1709df79a0dc47830fe7a99ab0082a722ca3fb
679,206
def find_best_match(path, prefixes): """Find the Ingredient that shares the longest prefix with path.""" path_parts = path.split('.') for p in prefixes: if len(p) <= len(path_parts) and p == path_parts[:len(p)]: return '.'.join(p), '.'.join(path_parts[len(p):]) return '', path
e90c8d19eb3fcf97f88a2ed5552973e0b70b4a44
679,207
import time def wait_for_influxdb(db_client): """Function to wait for the influxdb service to be available.""" try: db_client.ping() print("connected to db") return None except ConnectionError: print("not yet") time.sleep(1) wait_for_influxdb(db_client)
9c67c0421fc6542072ff561b111f053963856b84
679,208
def wc1(file_): """Takes an absolute file path/name, calculates the number of lines/words/chars, and returns a string of these numbers + file, e.g.: 3 12 60 /tmp/somefile (both tabs and spaces are allowed as separator)""" with open(file_) as f: content = f.read() num_lines =...
c812b14d6eb786c396901740d6095c05cb478447
679,211
def rjust(s, width, *args): """rjust(s, width[, fillchar]) -> string Return a right-justified version of s, in a field of the specified width, padded with spaces as needed. The string is never truncated. If specified the fillchar is used instead of spaces. """ return s.rjust(width, *args)
e43231268288c3488863729cf388e5573c7138d4
679,215