content
stringlengths
39
14.9k
sha1
stringlengths
40
40
id
int64
0
710k
def format_import(source_module_name, source_name, dest_name): """Formats import statement. Args: source_module_name: (string) Source module to import from. source_name: (string) Source symbol name to import. dest_name: (string) Destination alias name. Returns: An import statement string. """ ...
7e11642cf0b8bd5fae42d34eb1b7233e7921be49
650,087
def longest_in_dict( d:dict ) -> str: """ Returns longest item's string insde a dict """ longest:str = '' for i in d: if len(str(i)) > len(longest): longest=i return longest
ea6a8f1cc14c614b345f0c0d6df7906e18e0510f
650,089
import math def RelToAbsHumidity(relativeHumidity, temperature): """Convert Relative Humidity to Absolute Humidity, for a given temperature.""" absoluteHumidity = 6.112 * math.exp((17.67 * temperature)/(temperature+243.5)) * relativeHumidity * 2.1674 / (273.15+temperature) return absoluteHumidity
e339144a2a1862891cedeca540dc949215da09f5
650,090
import hashlib import json def get_app_hash(raw_cwl): """If the CWL has a field "sbg:hash" (as used by sevenbridges-cwl) use that, else compute it (again, just like sevenbridges-cwl) :param raw_cwl: :return: """ if "sbg:hash" in raw_cwl: return raw_cwl["sbg:hash"] else: sh...
490e6b416e2024711cccbd3de37652fcc8b16cc0
650,092
import yaml def data_file_read_yaml(filename): """ Reads a file as a yaml file. This is used to load data from fuzz-introspectors compiler plugin output. """ with open(filename, 'r') as stream: try: data_dict = yaml.safe_load(stream) return data_dict except ...
1ac2aa98d9628aab6637048a8f07f5ffa84aa750
650,093
def clsn(obj): """Short-hand to get class name. Intended for use in __repr__ and such.""" if isinstance(obj, str): return obj else: return obj.__class__.__name__
e030359e86cf07db8e6869c219575c74c620de6a
650,096
def count_values(tokens): """Identify the number of values ahead of the current token.""" ntoks = 0 for tok in tokens: if tok.isspace() or tok == ',': continue elif tok in ('=', '/', '$', '&'): if ntoks > 0 and tok == '=': ntoks -= 1 break ...
6e63f0e48a8a2014307f7a50738cc5f1035c8c4a
650,098
def quoteIfNeeded(txt, quoteChar='"'): """ quoteIfNeededtxt) surrounds txt with quotes if txt includes spaces or the quote char """ if isinstance(txt, bytes): txt=txt.decode() if txt.find(quoteChar) or txt.find(' '): return "%s%s%s" % (quoteChar, txt.replace(quoteChar, "\\%s" % quoteChar), quoteC...
7144d65a19c938789f2a6b9bcfc58021e89d4d43
650,099
def get_slurm_script_gpu(log_dir, command): """Returns contents of SLURM script for a gpu job.""" return """#!/bin/bash #SBATCH -N 1 #SBATCH --ntasks-per-node=1 #SBATCH --gres=gpu:tesla_p100:1 #SBATCH --mem=32GB #SBATCH --output={}/slurm_%j.out #SBATCH -t 5:59:00 module load anaconda3/2019.10 cudatoolkit/10.1 cudnn...
ffdd9d51a8d704013016f7126a53b8a13653055d
650,102
def make_jobjects(entities, transformer, *args): """Run a sequence of entities through a transformer function that produces objects suitable for serialization to JSON, returning a list of objects and a dictionary that maps each entity's key_name to its index in the list. Item 0 of the list is always Non...
6d891488dc95f6c3ed6d69ab21f743c2fa721177
650,103
import ctypes def _encode_string(value): """Encode a Python3 string in preparation to be passed across DLL boundary""" return ctypes.c_char_p(value.encode('utf-8'))
12bb88faf21431dfec433724eb2056366833f2e0
650,106
def _get_bin_sum(bin_result): """ Get the [min, max] of the sample; best-fit scatter and error. """ min_val = bin_result['samples'].min() max_val = bin_result['samples'].max() sig = bin_result['sig_med_bt'] err = bin_result['sig_err_bt'] return min_val, max_val, sig, err
7f7d7a9705fb0e4da80689e1c98cb159e90e3b32
650,108
def _modify_permissions_request_factory(path, settings): """ Constructs modify permissions request :param path: A path to apply permissions :param settings: An instance of ModifyPermissionsSettings :return: A constructed request """ modify_permissions_request = settings.to_pb() modify_pe...
4830d93fc94559940cc8f85a887476874f7e442f
650,109
import platform import pwd def GetUserId(user): """ On a Linux system attempt to get the UID value for a give 'user'. This uses a system call to obtain this data. :param user: User name to lookup. :return: UID value if the user is found, otherwise None """ if isinstance(user, int): ...
870556d8beedc513e6b4aa321a9f80807e9570ee
650,110
from typing import Tuple def cmyk_to_rgb(c: float, m: float, y: float, k: float) -> Tuple[int, int, int]: """Convert CMYK (Cyan Magenta Yellow Black) to RGB (Red Green Blue). :param c: Cyan (0.0 to 1.0 inclusive). :param m: Magenta (0.0 to 1.0 inclusive). :param y: Yellow (0.0 to 1.0 inclusive). ...
375481b55571b9ef456612c7544afe2dca4ef7ac
650,113
def get_url(artist): """ Get the url link for the artist in www.lyrics.com """ return f"https://www.lyrics.com/artist/{artist}"
84101cda872070f9106a3fb5e6349161ac20cc3c
650,114
def resolve(var_name, scope): """ Finds the given symbol (a function or a variable) in the scope. Reports error if not found. Args: var_name (str): Name of the symbol to be found. scope (dict): Local variables. Returns: Found variable or a function. """ variable = scope...
ce6983070d3425ce843593b7392090f1e3fe6186
650,116
def anySubs(UserDetails): """ Checks if the user has any subscriptions yet """ if('subscriptions' in UserDetails.keys()): return True return False
80f3c4e93300faea85247654b7c2328312e107c6
650,119
def __parse_version_from_service_name(service_name): """ Parse the actual service name and version from a service name in the "services" list of a scenario. Scenario services may include their specific version. If no version is specified, 'latest' is the default. :param service_name: The name of the ser...
7fc634b7159e7141e99cbec090275388f00e27c5
650,120
import random def class_colors(names): """ Create a dict with one random BGR color for each class name """ return {name: ( random.randint(0, 255), random.randint(0, 255), random.randint(0, 255)) for name in names}
a91f84aa1e3012fc553744e941abd5e9aeca9074
650,121
def collect(delta): """Return the states and alphabet used in the transition function delta.""" Q = set() Sigma = set() for (q, a), r in delta.items(): Q.add(q) Q.add(r) Sigma.add(a) return Q, Sigma
f300553f0ac8a9b03dfc371279b5af056fed9171
650,126
import torch def convert_to_one_hot(tensor, num_classes=None): """Convert dense classification targets to one-hot representation Parameters ---------- tensor : torch.Tensor Tensor of dimensionality N num_classes : int Number of entries C of the one-hot representation. If None, use maximum value...
48bfe87a0aea539b05076951c211353c85a3dd19
650,127
def enum_list_to_bitfield(enum_list, bitfield_enum_type): """ Converts a list of enums to a bitfield value. Args: enum_list (List[enum.Enum]): Specifies the list of enums. bitfield_enum_type (enum.Enum): Specifies the bitfield enum type from which to mask and extract the enum va...
7f64eebcfed27a027e7d40c127914cfe720b731c
650,128
def calcSurroundingIdxs(idxs, before, after, idxLimit=None): """ Returns (idxs - before), (idxs + after), where elements of idxs that result in values < 0 or > idxLimit are removed; basically, this is useful for extracting ranges around certain indices (say, matches for a substring) that are contained fully in an ...
72b064dd8f79762e18d1dd2a9d1ab84628a4e1a8
650,130
def islist(thing): """ return True if a thing is a list thing, False otherwise """ return isinstance(thing, list)
d2658b137a06b3b26cafe94bd9360607da49a466
650,132
def readLines(file, map=lambda line: line.strip()): """ Read and return a file as a list of files. Optionally, @map argument can be set to process the lines. """ # Read file line by line. results = [] with open(file, 'r') as infile: for line in infile: results.append(map(line)) return results
554e9360f2c52e7450455d92726296f2638ce99f
650,136
import torch def load_checkpoint(model, optimizer, device, checkpoint_file: str): """Loads a model checkpoint. Params: - model (nn.Module): instantised model to load weights into - optimizer (nn.optim): instantised optimizer to load state into - device (torch.device): device the model is on. -...
d37787c2aa97d86f5118c5d4bb8a36c7b75ad136
650,141
def device_get_from_facts(module, device_name): """ Get device information from CVP facts. Parameters ---------- module : AnsibleModule Ansible module. device_name : string Hostname to search in facts. Returns ------- dict Device facts if found, else None. ...
55549b178f14f665f3c48a4e750be39ca70d61ab
650,143
def image_resize(image, resize=None): """ Given an image and resize tuple (w,h), return an image with new size. """ if resize is not None: image = image.resize(resize) return image
d3af9d83cdd96956cffaf12f48763fd0528a696d
650,145
def process_views(df): """Takes a dataframe and quits commas. Parameters ---------- df : The dataframe to search. Returns ------- The dataframe processed. """ df['views'] = df['views'].str.replace(',', '').astype(float) return df
233a27ea67c7205cb1c7cedaf789ac70fbc91cee
650,146
def temperature_trans(air_in, fuel_in, ex_out): """ Convert degree celsius to kelvin. Optional keyword arguments: --------------------------- :param air_in: temperature of air coming in to fuel cell(FC) :param fuel_in: temperature of fuel coming into (FC)/ temperature of refo...
8b53781636062626fa8bfd93fb08ff783809d8ca
650,147
import re def parse_url(url): """Return a tuple of ``(host, port, ssl)`` from the URL specified in the ``url`` parameter. The returned ``ssl`` item is a boolean indicating the use of SSL, and is recognized from the URL scheme (http vs. https). If none of these schemes is specified in the URL, the...
8f3e3f824b3f6d49d95ff883917e70dd3d804766
650,148
def get_bytes_from_gb(size_in_gb): """ Convert size from GB into bytes """ return size_in_gb*(1024*1024*1024)
9bfd7a0791a08a88ad83b388e25030ef8cc2df6b
650,150
def v12_add(*matrices): """Add corresponding numbers in given 2-D matrices.""" matrix_shapes = { tuple(len(r) for r in matrix) for matrix in matrices } if len(set(matrix_shapes)) > 1: raise ValueError("Given matrices are not the same size.") return [ [sum(values) for ...
934dbd82be527f113eeb2eaad01f8c867100a869
650,152
def mib_to_gib(value): """ Returns value in Gib. """ return float(float(value) / 1024.0)
5e6d3d15ab7f98a61805e922d25ab2b8a32f1c6d
650,153
def read_smi_file(file_path): """ Reads a SMILES file. :param file_path: Path to a SMILES file. :return: A list with all the SMILES. """ with open(file_path, "r") as smi_file: return [smi.rstrip().split()[0] for smi in smi_file]
08d744a126814897323b45a4cbe0f4e7e977843c
650,159
import logging def get_mfa_response(mfa_result): """Extract json from mfa response. :param mfa_result: raw response from mfa api :return verify_mfa: json response from mfa api """ try: verify_mfa = mfa_result.json()["response"] except Exception as parse_error: logging.error( ...
d0cac07246d3d9367ff8cafd941d5c1b6e2f0957
650,163
import six def encode_ascii_xml(x): """Encode a string as fixed-length 7-bit ASCII with XML-encoding for characters outside of 7-bit ASCII. Respect python2 and python3, either unicode or binary. """ if isinstance(x, six.text_type): return x.encode('ascii', 'xmlcharrefreplace') elif is...
2303fc4c4a14984d0f457edb7ef7c2e254775499
650,164
def get_boolean_from_request(request, key, method='POST'): """ gets the value from request and returns it's boolean state """ value = getattr(request, method).get(key, False) if value == 'False' or value == 'false' or value == '0' or value == 0: value = False elif value: value = True ...
3ff2bbcfb7675bca508e712861672accae663328
650,167
def build_insert(table: str, to_insert: list): """ Build an insert request. Parameters ---------- table : str Table where query will be directed. to_insert: iterable The list of columns where the values will be inserted. Returns ------- str Built query strin...
ab9c0e9b0868429a684825fab9ca53820b19f63f
650,173
def clean_nodata(series, nodata=None): """ Given a series remove the values that match the specified nodata value and convert it to an int or float if possible Parameters ---------- series : pandas series nodata : string, int, or float Nodata placeholder Returns ------- pandas ...
848d6a1d2dd77a0af6ba69217f93566c8164af83
650,174
def field_values_valid(field_values): """ Loop over a list of values and make sure they aren't empty. If all values are legit, return True, otherwise False. :param field_values: A list of field values to validate. :returns: False if any field values are None or "", True otherwise. """ for ...
44a1bd799bc3f36cc8695b8691640a140d3b29a8
650,178
def normalize_name(s): """Normalizes the name of a file. Used to avoid characters errors and/or to get the name of the dataset from a config filename. Args: s (str): The name of the file. Returns: new_s (str): The normalized name. """ if s is None: return '' s = s....
a0921b12ea2d6c855e5443ab81df33ba83d587c8
650,179
from datetime import datetime def fromtimestamp(timestamp): """ Return datetime object from provided timestamp. If timestamp argument is falsy, datetime object placed in January 1970 will be retuned. """ if not timestamp: return datetime.utcfromtimestamp(0) return datetime.fromtimestam...
cfac5db5eeb11a71b4ca2109c682da8c5c2267f6
650,181
def get_x_y_values(tg, num_words=50): """ Gets a list of most frequently occurring words, with the specific number of occurrences :param tg: (TermGenerator) Object with the parsed sentences. :param num_words: (int) Number of words to be processed for the top occurring terms. :return: (List) List of ...
9584851d7261f4c5d8d279fa721fbe281e40e5b6
650,188
import select def wait(fd, timeout=2): """ Wait until data is ready for reading on `fd`. """ return select.select([fd], [], [], timeout)[0]
dfe41ab278db4c793f6436d6349754e648187230
650,190
def parse_module(module, keyword): """ Returns a list of keywords for a single module :param module: list of strings :param keyword: Module keyword you are looking for :return: list of lines with the specified keyword """ keys = [] for line in module: keyw = line.split(" ")[0] ...
0ac00fb05983ad1306f09565a8f19aeb2f980696
650,196
from typing import Union from typing import Sequence from typing import Iterable def check_parity( bitstring: Union[str, Sequence[int]], marked_qubits: Iterable[int] ) -> bool: """Determine if the marked qubits have even parity for the given bitstring. Args: bitstring: The bitstring, either as a ...
f81b2e45611d987d14f50144068d7d596da7ca06
650,200
def fnv1a(data): """Fowler–Noll–Vo hash function; FNV-1a hash.""" hash_ = 2166136261 data = bytearray(data) for c in data: hash_ = ((hash_ ^ c) * 16777619) & 0xffffffff return hash_
4b4c39100430471bb55076d5bc2d721fd74f9f95
650,204
import ipaddress def _GetIpv4CidrMaskSize(ipv4_cidr_block): """Returns the size of IPV4 CIDR block mask in bits. Args: ipv4_cidr_block: str, the IPV4 CIDR block string to check. Returns: int, the size of the block mask if ipv4_cidr_block is a valid CIDR block string, otherwise None. """ networ...
99c4d575314a30863ca3a104ba0334d9886602b6
650,205
import functools def memoize_full(func): """ >>> @memoize_full ... def f(*args, **kwargs): ... ans = len(args) + len(kwargs) ... print(args, kwargs, '->', ans) ... return ans >>> f(3) (3,) {} -> 1 1 >>> f(3) 1 >>> f(*[3]) 1 >>> f(a=1, b=2) () {'a...
a0dd196b701c2d6e18346f4db635b4086c37ac20
650,208
def max_sum_from_start(array): """ This function finds the maximum contiguous sum of array from 0 index Parameters : array (list[int]) : given array Returns : max_sum (int) : maximum contiguous sum of array from 0 index """ array_sum = 0 max_sum = float("-inf") for num in ar...
320632d92903ba745339a357cc0792469093fd95
650,213
import typing import pathlib def parse_requirements_file (filename: str) -> typing.List: """read and parse a Python `requirements.txt` file, returning as a list of str""" with pathlib.Path(filename).open() as f: # pylint: disable=C0103 return [ l.strip().replace(" ", "") for l in f.readlines() ]
f5a3574b49d492d5671ceb0946df771673070d74
650,215
def dl1_tmp_path(tmp_path_factory): """Temporary directory for global dl1 test data""" return tmp_path_factory.mktemp("dl1")
9fb49713aff0edd9135de1ac1ba0df8d36c868fe
650,222
def PrintSeconds(seconds): """Return a string representing the given time in seconds.""" orig = seconds minutes = seconds // 60 seconds %= 60 hours = minutes // 60 minutes %= 60 days = hours // 24 hours %= 24 s = "" if days > 0: s += "%dd " % days if hours > 0: s += "%02dh " % hours if ...
0c0d40f8b5bea760a67b7739ca9738e1812b792f
650,224
def _prod(x): """Compute the product of an iterable.""" out = 1 for a in x: out *= a return out
b8c6f2dea83e629fef0ae7e882830777d089d22e
650,227
def isInside(point, leftTop, rightBottom): """ return True if point is in the rectangle define by leftTop and rightBottom """ if not (leftTop[0] < point[0] < rightBottom[0]): return False if not (leftTop[1] < point[1] < rightBottom[1]): return False return True
f9727e5ac11011ea45d05d5db1a439848c882481
650,229
import random def tournamentSelection(population,popSize): """ Function to select some 'good' parents from the population using tournament selection. This implementation selection n pairs of parents, where n = population size // 2 Parameters: population (list) - list of solutions. po...
ba2a4d21b076d81f59e23886dd671ffc4bdb1c3d
650,235
def get_tags(sync_config): """ return a list of tags with, there name, and displayName """ tags = [] for tag in sync_config['tags']: tags.append({'name': tag['name'], 'displayName': tag['displayName']}) return tags
9872ea57726d033840b585508eccd8c91c6addd8
650,236
def IsOperator(value): """ Check if the passed value is 'operator' """ if value != None and value == "operator" : return True return False
429eb0232bd4c1f93fc052ec3512958a9fcaa998
650,238
def _build_snapshot_tree(snapshots): """ Builds a tree fro the given snapshot. Parameters ---------- snapshots : `list` of ``BaseSnapshotType`` The snapshot to build tree from. Returns ------- snapshot_tree : `dict` of (``client``, `dict` of (`type`, ``BaseSnapshotType`...
913df7dde309e95ee2908087de36946acbc1c2da
650,243
def pis_map(diffn_img, index_low_b_val, index_high_b_val): """ Produces the physically implausible signal (PIS) map [1]. Parameters ---------- diffn_img index_low_b_val : int index into the DWI identifying the image with lower b-value. Usually 0 referring to the b=0 (non-DW) im...
b799bac8f7e6925db9592325519425fa7f3a3831
650,251
def count_slash_for(s): """ Returns the number of times '/' appears in string s Parameter s: the string to search Precondition: s is a (possibly empty) string """ # Accumulator count = 0 # Loop variable for i in range(len(s)): if s[i] == '/': count= coun...
9d0ef4f018eaa467daa00ad5dca077d806ba6e50
650,253
def get_labels(label_filename): """ Get the label of a given set The labels are read from a text file, and a dictionary is built. The key is the file stem and the value is the label (either 0 for an attack or 1 for banafide access). Parameters ---------- label_filename: str The path to the fi...
6aedacfd8edc7c720ffb62ca4f826531c691a932
650,254
def composition_to_oxidcomposition(series, **kwargs): """ Adds oxidation states to a Composition using pymatgen's guessing routines Args: series: a pd.Series with Composition object components **kwargs: parameters to control Composition.oxi_state_guesses() Returns: a pd.Series ...
328cb00837e8c341792d13f088f0ceb714e869e2
650,256
def update_available(data, recent_pick): """ Reduce available pokemon set by most recent pick. Parameter --------- data: DataFrame with available Pokemons recent_pick: Picked Pokemon name """ df = data.copy() return df.loc[df["Name_1"] != recent_pick]
96015add1b2689c933d9d32372de1bdde0ce4233
650,258
def _create_style(parameter_list): """Formats and translated the provided parameters to an ANSI escape sequence""" return "\033[%sm" % ";".join(parameter_list)
ffd0e9960835a911805b8528082d26409c6cbd36
650,265
def filter_pheno_nan(x_species, y_pheno, pheno_name, verbose=False): """Filter X and Y to have same index and drop NANs """ y = y_pheno[pheno_name] y.dropna(axis=0, how='all', inplace=True) X = x_species X = X.reindex(y.index) return X, y
64d7f787d88d405821842d04dabc9b6003b9bcfd
650,266
def time_from_utc(utc_offset, time): """ (number, float) -> float Return UTC time in time zone utc_offset. >>> time_from_utc(+0, 12.0) 12.0 >>> time_from_utc(+1, 12.0) 13.0 >>> time_from_utc(-1, 12.0) 11.0 >>> time_from_utc(+6, 6.0) 12.0 >>> time_from_utc(-7, 6.0) 23.0 ...
9c8f05d09c6a9418d07178cabc24ba5c87ddd00b
650,267
def replace_u_to_t(seq): """Replaces the U's in a sequence with T's. Args: seq (str): A nucleotide sequence. Returns: str: The sequence with the U's replaced by T's. Examples: >>> replace_u_to_t("ACGU") 'ACGT' >>> replace_u_to_t(None) """ ...
a8210167b8b97ebbd7482d9d4382dbd4e052549d
650,268
def get_max_release_version(version_id): """ Returns current release version of 3ds Max :param version_id: int, release ID of the current Max version :return: 3ds Max release version :rtype: long .. code-block:: python import MaxPlus from dccutils.max import app versi...
9f672b543c1642d30364240362cbfae7b3e42170
650,270
def extract(line): """Return a tuple (uin, nick) from 'O11111111 nickname'""" line = line.replace("\n", "") uin = line[1:line.find("\t")] # fix uin uin2 = "" for c in uin: if c.isdigit(): uin2 += c uin = uin2 nick = line[1+line.find("\t"):] nick = nick.replace("/", "_") nick = nick.replace(":", "_...
7a899d0a087a262fe153a72ae17f8042c49f21b6
650,271
def _ConvertValueNameToChartAndTraceName(value_name): """Converts a value_name into the equivalent chart-trace name pair. Buildbot represents values by the measurement name and an optional trace name, whereas telemetry represents values with a chart_name.trace_name convention, where chart_name is optional. Thi...
7ca3e1371ef01084131890db1d0defb2769c4f1e
650,275
def summy(string_of_ints): """This function takes a string of numbers with spaces and returns the sum of the numbers.""" numbers = string_of_ints.split() answer = 0 for i in numbers: answer = answer + int(i) return answer
e04fae85798b899f511d797da77aa8a02ca5f5b4
650,276
def get_min(current_min, input_score): """ compare two input numbers, and return smaller one. :param current_min: int, the current min score. :param input_score: int, the score just input. :return: int, compare two numbers and return smaller one. """ if current_min != 0 and current_min < inp...
6d5ab921a179e3629af766ceab43c4197961e9a5
650,280
def create_css_rule(selectors: list, properties: dict) -> str: """ Return CSS rule properly formated. Paramters --------- selectors : list of string list of the CSS selector to apply all the properties properties : dict dictionnary of CSS properties to apply Returns ---...
50a20e643de2d39f470931782d995219c40e64e2
650,281
def adjust_displacement(n_trials, n_accept, max_displacement): """Adjusts the maximum value allowed for a displacement move. This function adjusts the maximum displacement to obtain a suitable acceptance \ of trial moves. That is, when the acceptance is too high, the maximum \ displacement is incre...
cc513be27481d239cf8c937bd260e1db8f182775
650,283
def wildcard_to_regexp(instring): """ Converts a player-supplied string that may have wildcards in it to regular expressions. This is useful for name matching. instring: (string) A string that may potentially contain wildcards (* or ?). """ regexp_string = "" # If the string starts with an...
f70737b9186882907cefddb02a94de68e5ec8783
650,285
def makeHtmlInlineImage(text): """Create HTML code for an inline image. """ return """<IMG SRC="%s" ALT="%s">""" % (text, text)
b10072cb6c1b703ee9cf0a2ed1942415ce66a191
650,286
def rollout(env, sess, policy, framer, max_path_length=100, render=False): """ Gather an episode of experiences by running the environment. Continues until env.done is True or length of episode exceeds max_path_length """ t = 0 ob = env.reset() obs = [ob] logps = [] rews = [] acs...
67b5e5dfe35cbe382e552e94758a595e80d09f4f
650,287
def lower_case(text: str) -> str: """Convert `text` to lower case. Args: text (str): The text to convert to lower case. Returns: The converted text. """ return text.lower()
24b93a43f11d61194ff2429e4d5ee731a88a0a6c
650,288
import torch def reverse(input, dim=0): """ Reverses a tensor Args: - input: tensor to reverse - dim: dimension to reverse on Returns: - reversed input """ reverse_index = input.new(input.size(dim)).long() torch.arange(1 - input.size(dim), 1, out=reverse_index) ...
7924d55daec78743afff99eda093b10c2f2d32d2
650,289
def get_last_col(worksheet, row_num: int = 1) -> int: """Retrives the last nonblank column on Google Sheets Parameters ---------- worksheet : Google Sheets worksheet The worksheet being queried row_num : int, optional Row that's indicative of the overall data length, by default 1 ...
1e3c422bc1425b2f47aa32f08e5662c346c6cd66
650,291
def pairwise(iterable): """ Iter over an iterable, two items by two items >>> list(range(10)|pairwise()) [(0, 1), (2, 3), (4, 5), (6, 7), (8, 9)] """ a = iter(iterable) return zip(a, a)
b10528ab7315f6eb5ed78accfdf9135ae90c5b9a
650,294
def bc(val): """ Convert bool to single letter T or F """ if val is True: return "T" return "F"
628255892a5c6545f20a3df4f4f20ca0615323b4
650,296
def assign_county(point, counties): """Assign a single point to its county.""" try: match = next( county['NAME'] for _, county in counties.iterrows() if point.intersects(county['geometry']) ) except StopIteration: match = None return match
b884ce7ca4727967e412633b44edca5140e19edc
650,299
import mpmath def cdf(x, mu=0, sigma=1): """ Log-normal distribution cumulative distribution function. """ if x <= 0: return mpmath.mp.zero lnx = mpmath.log(x) return mpmath.ncdf(lnx, mu, sigma)
7c984386d5947e0882fc115e68afcdb26197b960
650,300
import torch def broadcast_to_tensor(tensor, encoding, ch_axis): """ This helper method takes n-dimension tensor and a 1-dimension encoding. And the encoding is broad-casted to match the n-dimensional tensor :param tensor: Tensor to use as target for the broadcasting operation :param encoding: Enc...
8a15c0fade8793ea9e327eb788aae58264133405
650,302
import yaml def write_yaml_data(filepath, data): """Write data to YAML file Args: filepath: the path to the YAML file data: a dictionary to write to the YAML file """ with open(filepath, 'w') as stream: yaml.safe_dump(data, stream, default_flow_style=False, indent=2) return (...
7706ded443e2a110770f742166481fa6e6ccb12d
650,304
import re def get_space_normalized_segment(segment): """Remove leading/trailing as well as multiple spaces from a string. :param str segment: a segment (sentence) :return: a string with no leading/trailing spaces and only containing single whitespaces :rtype: str """ return re.sub(r'\s{2,}', ...
5f1c04f28e5fda8fc501f979652846aacbb33cd8
650,305
def decimal_digits(x: float, precision: int) -> int: """Forms an integer from the base-10 digits of a floating-point number. Args: x: A floating point number, which may be negative. precision: The number of digits after the decimal point to include. Returns: An integer containing a...
7a0d6b3ef34efa276a9537cefa899be6ed16a60a
650,307
def describe_class_or_specification(obj): """ Simple description of a class or interface/providedBy. """ return obj.__name__ if obj is not None else 'None'
dd298eb8febaad889b0019b87ee9cd7c43009279
650,311
from typing import Any from typing import Sequence def a_seq_int(request: Any) -> Sequence[int]: """Provide random values that are sequences of ints.""" return request.param[1]
c7c2c6901b274f747364ac7b9790208c0eddf341
650,313
def _extract_synonym(rest_of_line: str) -> str: """ Extracts synonym name from obo line. :param rest_of_line: string containing line except for "synonym: " :return: """ synonym = rest_of_line.split('"')[1].lower() return synonym
1b2ea52bf2673646e43f5e2d03250e35795e16c5
650,315
def color_temp_post_response_ok(devid, color_temp): """Return color temp change response json.""" return ''' { "idForPanel": "''' + devid + '''", "colorTemperature": ''' + str(int(color_temp)) + ''' }'''
bb110f55e5cf8e8c62cab43bced1461df1937938
650,318
def ord_word(word): """ Convert an alphanumeric string to its ASCII values, used for ES keys. """ return ''.join([str(ord(letter)) for letter in word])
db6f6742b203b000bf6027be24f81b4b10a9e20e
650,319
def cleanup_libs_list(libs): """Cleans up libs list by removing invalid entries""" cleaned = [] for lib in libs: lib = lib.strip() if not lib.endswith('.lib.recipe'): cleaned.append(lib) return cleaned
2fc9efec02af449793b2f3b98f3e13e67ea7477f
650,321
def read_num_from_file(file_with_path): """ read a number from a file """ with open(f"{file_with_path}", "r", encoding='utf-8') as text_file: return int(text_file.read())
8b87b746a03308724c5cc15fd7eca4cf4e85b283
650,331
def _FlattenList(l): """Flattens lists of lists into plain lists, recursively. For example, [[4, 5, 6], [7, 8], []] will become [4, 5, 6, 7, 8]. Non-list elements will get wrapped in a list, so 'foo' becomes ['foo']. None becomes []. Args: l: a list, or not. Returns: A flattened list. """ re...
ca4df94f51568e93e217bdf50987f47fd0a257f8
650,332
import re def feat_tokens(for_artist=True): """Return a regular expression that matches phrases like "featuring" that separate a main artist or a song title from secondary artists. The `for_artist` option determines whether the regex should be suitable for matching artist fields (the default) or title...
764c5c9295a1d5f6e01fa95059cc079949a12d25
650,334