content
stringlengths
39
14.9k
sha1
stringlengths
40
40
id
int64
0
710k
def lastFrameFromSegmentLength(dist, first_frame, length): """Retrieves the index of the last frame for our current analysis. last_frame should be 'dist' meters away from first_frame in terms of distance traveled along the trajectory. Args: dist (List[float]): distance along the trajectory, incr...
3e85a8814da1f17dd8e3f9136e5e1682cc09bcd5
627,710
def lyrics_to_frequencies(wordlist): """ wordlist (list): list of words (strings) of song lyrics Returns a dictionary mapping different lyrics words to their frequencies or number of occurences """ myDict = {} for word in wordlist: if word in myDict: myDict[word] += 1 ...
c4b2ee8216281eb0675b2146fe87f077f3f130be
627,711
import time def get_timestamp(date_time): """ Create a `timestamp` from a `datetime` object. A `timestamp` is defined as the number of milliseconds since January 1, 1970 00:00. This is like Javascript or the Unix timestamp times 1000. """ return time.mktime(date_time.timetuple()) * 1000
482cfce4f6314a40ac0e51c8763aa4d4fb533541
627,712
def getattr_deep(obj, attrs): """ Like getattr(), but checks in children objects Example: X = object() X.Y = childobject() X.Y.variable = 5 getattr(X, 'Y.variable') -> AttributeError getattr_deep(X, 'Y.variable') -> 5 :param obj: object :param attrs: attribu...
1d9165ee550ce0fb442533982dcc1c5cbfad8fc3
627,718
def chunk_file(fname, *, limit=5000, start_num=0): """ This function is inexorably tied to extras.fetch_eddb.jq_post_process. Importantly jq doesn't wrap in list brackets or end in ',' Take any file with fname. Chunk that file out with limit lines per file. Each chunk will be written to a file with...
dd39a73660c3eadcb7d928bfd675e22def0ada5c
627,719
def get_base_url(parsed): """Convert a parsed URL back to string but only include scheme, netloc, and path, omitting query.""" return parsed.scheme + "://" + parsed.netloc + parsed.path
21df200efbd72eab7ea844e3d8b5466170eac5c9
627,723
import re def css_colour(s): """Is string a valid CSS colour.""" m = re.match(r'^(?:[0-9a-fA-Z]{3}){1,2}$', s) return m is not None
82066d04b2504179e40a70f84c8939af335285ac
627,729
def to_str(text, session=None): """ Try to decode a bytestream to a python str, using encoding schemas from settings or from Session. Will always return a str(), also if not given a str/bytes. Args: text (any): The text to encode to bytes. If a str, return it. If also not bytes, convert ...
74bcec023a7a8afea69c24a3dc2d7ae41247f461
627,731
def get_regression_predictions(input_feature, intercept, slope): """ Purpose: Compute predictions Input : input_feature (x), intercept (w0), slope (w1) Output : Predicted output based on estimated intercept, slope and input feature """ predicted_output = intercept + slope * input_feature re...
be03ccb21abab4bac099ded636be07e67d4db2ae
627,732
import random import string def rand_string(numOfChars): """ Generates a string of lowercase letters and numbers. That makes 36^10 = 3 x 10^15 possibilities. If we generate filenames randomly, it's harder for people to guess filenames and type in their URLs directly to bypass permissions. """...
5b8bcd85b516e54686c479fe46236853c6bd2aa5
627,733
def always_str_list(list_or_str): """Makes sure list_or_str is always a tuple or list Parameters ---------- list_or_str: str or str iterable (tuple, list, ...) Parameter to set as iterable if single str. Returns ------- Iterable Iterable equivalent to list_or_str.""" if...
5c3d6c6a0ca1667d92722740941bf17366175d06
627,734
def find_faces_at_edges(faces): """ For each edge on the mesh, find the two faces that share the edge. Parameters ---------- faces : list of lists of three integers the integers for each face are indices to vertices, starting from zero Returns ------- faces_at_edges : dictionar...
d8e05105a85e6c724e258ebbe949029047bd1a3f
627,736
def get_id_from_urn(urn): """ Return the ID of a given Linkedin URN. Example: urn:li:fs_miniProfile:<id> """ return urn.split(":")[3]
8fecec105617364cf3ed9e61764041d8960060f2
627,738
def datetime_encode(obj): """Encode a datetime.""" return obj.isoformat()
53385cb9b50db652f71953a13856f83951f36826
627,741
def derivative_sigmoid(y: int) -> float: """Calculate the derivative of the sigmoid function Args: y (int): the output of the sigmoid function of x Returns: float: the output of the derivative sigmoid function """ return y * (1 - y)
067bbce65924eee234a9e3635a649af6f39bb922
627,744
def get_header(context, header_name): """Return all response header values that've been set for header_name.""" return [header[1] for header in context.headers if header[0] == header_name]
cc2fba51f028aa76b8864376d8010099de56cc50
627,748
def calculate_ngram_freqs_solution(ngrams): """Calculate the frequency of a subsequent word given a sequence of ngrams :param ngrams: [['i', 'will', 'be'], ['will', 'be', 'leaving'], ['be', 'leaving', 'florida']] """ freqs = {} for ngram in ngrams: # Differentiate successor (= lastWord) ...
66867cd4e269d23e1dc22803cde2baf2b5d9f6a4
627,750
import math import torch def simpleLambda(x, scale, sigma=1.0): """ De-noising by Soft-thresholding. Author: David L. Donoho :param x: one block of wavelet coefficients, shape [num_nodes, num_hid_features] torch dense tensor :param scale: the scale of the specific input block of wavelet coefficients,...
1d03884b4b0067cd401145047d5269fe78e33dcb
627,753
def sort(data): """ Sort list of reminders by time (oldest first). """ return sorted(data, key=lambda k: (k['time']))
2c9ec32f6e5c3435596a34cc3f98ce1ad1d12ccc
627,754
def find_gvfs(lineages, gvf_list): """This function searches for gvf files in a directory which have filenames that contain specified lineage names. :param lineages: Pangolin lineages to include in the report :type lineages: list of strings :param gvf_list: directory to search for gvf files :typ...
f2779d57a30600a48862beb30550d84cb6491495
627,755
def __int_to_bool(records: dict) -> dict: """Convert integer values to Boolean values.""" for k, v in records.items(): if isinstance(v, int): records[k] = bool(v) return records
9637290b2ff1ce6cc25a02919807861a6bf63128
627,756
def CalculateForecastStats(matched, available, possible=None): """Calculate forecast percentage stats. Args: matched: The number of matched impressions. available: The number of available impressions. possible: The optional number of possible impressions. Returns: The percentage of impressions t...
cc942e16a104b1b04ccf8964f5c9a1502b121d8e
627,761
from pathlib import Path def is_existent_file(potential_file: Path) -> bool: """Assess if a Path points to a file that exists.""" return potential_file.exists() and potential_file.is_file()
ef7fedf193a6d147b5e86f11d2f9064203f4a701
627,765
def int_to_str_add_zeros(number): """ Turn an int to a sting and make sure it has 6 digit (add zeros before if needed) """ if type(number) != int: print("File number should be an integer.\n") if number < 0: print("File number can't be negative.\n") elif number > 999999: ...
120c0cab693c12613f5381bbf25bdec8a442b59a
627,769
import torch def get_norm(torch_tensor, dim=0, order=2): """Get the norm of a 2D tensor of the specified dim Parameters ---------- torch_tensor : torch.tensor 2-dimensional torch tensor dim : int, optional order : float, optional Returns ------- torch_tensor : a 1-dimensi...
dc27780cf8b5a5a7a6c612be0891b36b9b3a2690
627,776
def potencia(base, exponente): """ (num, num) -> num Calclula la potencia dada una base y un exponente >>> potencia(2,3) 8 >>> potencia(2,8) 256 >>> potencia(5,3) 125 :param base: la base de la operacion :param exponente: la cantidad de veces que se debe multiplicar por si...
b270ce885c1b37eef1fa994793ae35e840e61380
627,780
def get_variables(models): """get variables of all models Args: models: dict containing all the models available Returns: variables: variables of all models """ variables = [] for model in models.keys(): variables += models[model].variables return variables
b2671c4bd2877be8fa4d241fa87dd789ceda8b7e
627,782
def params_to_lists(params): """Dictionaries are more convenient for storing and working with the parameters of the gaussians and lorentzians, but leastsq wants the initial parameters as a list (as far as I can tell...). This will take a list of dictionaries and convert it to a single list according to the ...
602ec229fa7159665179ca85a1b286e869366ac0
627,783
import logging import traceback import time def retry(tries, delay=1, backoff=2): """A retry decorator with exponential backoff. Functions are retried when Exceptions occur. Args: tries: int Number of times to retry, set to 0 to disable retry. delay: float Initial sleep time in seconds. backoff: f...
716f687ec8716dd94feb3a6dc849838397e79525
627,787
import torch def gather_word_outputs(outputs): """ 'outputs' is a list of 'output' of each GPU. As a reminder, each 'output' is a 3-tuple where: - output[0] is the last_hidden_state, i.e a tensor of shape (batch_size, sequence_length, hidden_size). - output[1] is the pooler_output, i.e. a tens...
1ce90c3ccaef5024daa4f77e2f76b2bfe76cce78
627,789
from datetime import datetime def decypher_date(datestr): """ Turn 12/17/2016 style dates that Goodgle sheets gives us and convert into a datetime object """ split = datestr.split('/') return datetime(int(split[2]), int(split[0]), int(split[1]))
3d44ae9fee955ba8064cdda5b1ab4839622f1ec1
627,795
def merge(a: list, b: list) -> list: """Merges two sorted lists into one sorted list""" i = 0 j = 0 result = [] while i < len(a) and j < len(b): if a[i] < b[j]: result.append(a[i]) i += 1 else: result.append(b[j]) j += 1 while i < ...
2309e21de2a73e1c9201ea7b5dcb168510841337
627,796
def find_closest_index(L,t): """ Find the index of the closest value in a list. Input: L -- the list t -- value to be found Output: index of the closest element """ beginning = 0 difference = abs(L[0] - t) best = 0 end = len(L) while beginning < end: ...
97e3177aaefaa5ffaf7da588ee780b7373f1bf27
627,797
def get_attrib(xml_obj, attrib): """Get an arbitrary XML attribute""" return xml_obj.attrib[attrib]
0c90595dfc6731f7fe2f14141d6ae003cab71905
627,799
import ast def make_arg(key, annotation=None): """Make an ast function argument.""" arg = ast.arg(key, annotation) arg.lineno, arg.col_offset = 0, 0 return arg
4a41c8335326f336a338c0c036cadca555cb7124
627,800
def get_max_len(files_list): """Get the length of the file with the longest filename""" ret = 0 if len(files_list) > 0: filename_lengths = [len(x) for x in files_list] max_len = max(filename_lengths) ret = max_len return ret
b74d5b5685b0e6abe8bf1093911f3a9723806f69
627,802
def _artifact_display_versions(versions): """Return a list of artifact versions for display purposes. This is slightly different than the 'versions' property of the artifact, as it is reverse-sorted (newest at the top) and also enumerated so that while it's reversed, the numbers still indicate chronolo...
a012fe700c987104175fea4b59bc178cf15f81d9
627,804
def replace_with_median(col, value_to_replace): """Replaces a dummy number with the median of the other numbers in the column. Parameters ---------- col : Pandas DataFrame column with numeric values value_to_replace : Dummy value that needs to be replaced Returns ---...
7962351333782164f0be023e5e6d242bda43e3e9
627,806
from datetime import datetime def to_datetime(dict_date): """ Convert json date entry to datetime. :param dict_date: Date as retrieved from kanka in the format "YYYY-mm-dd HH:MM:SS.000000" :type dict_date: string :return: Date converted to python datetime object :rtype: datetime.datetime """ ...
7275562a5ec7657853b5d664e858c88de71014d5
627,808
import re def clear_path_string(s): """ Simple function that removes chars that are not allowed in file names :param s: path_string :return: cleaned_path_string """ return (re.sub('[^a-zA-Z]+', '#', s)).lower()
2722af065988f02cba40a4899abd92f7c9a51063
627,809
from typing import Dict from typing import List def format_validation_errors(validation_errors: Dict[str, List[str]]) -> str: """Return marshmallow validation errors formatted as a single string.""" return ', '.join( '{}: {}'.format(key, value[0]) for key, value in validation_errors.items() ...
e43ab4c1d2886062a40db4c36b03783bb171c0ca
627,811
import csv def load_data(path_to_csv, num_samples=None): """ Read the csv file given and return the path to images and steering angles """ image_path = [] steering_angle = [] with open(path_to_csv, "r", newline='') as f: recorded_data = csv.reader(f, delimiter=',', quotechar='|') ...
be02b6f02a01293b59de8a8acf63f676a64ac558
627,815
def get_c(layer_configs): """Find input channels of the yolo model from layer configs.""" net_config = layer_configs['000_net'] return net_config.get('channels', 3)
3846c4f961f3a887073b9da25c7333a65a2547be
627,817
def get_format(s): """ Returns the Open Babel format of the given string. Note: It is primitive, distinguishes only xyz, smiles, inchi formats. >>> print(get_format('C')) smi >>> print(get_format('InChI=1S/H2O/h1H2')) inchi >>> print(get_format(get_xyz('C'))) xyz """ frm = 'u...
e3ec8c253b4cf14dd2401d4be710a6a596f6116b
627,820
def get_first_word(tabbed_info): """ Get the first word in a sentence, this is useful when we want to get file type, for instance, >> get_first_word('bigBed 6 +') will return 'bigBed' :param tabbed_info: the string (e.g. 'bigBed 6 +') :returns: the first word in the string """ return tab...
b3447800fbc9aea2bd685359cff30600c6f59dd5
627,821
def iscircular(linked_list): """ Determine whether the Linked List is circular or not Args: linked_list(obj): Linked List to be checked Returns: bool: Return True if the linked list is circular, return False otherwise """ if linked_list.head == None: return False ...
40a0ca17bc4534cfd68a46706a3445313b4ab09e
627,828
from typing import List def get_network_mask(raw_address) -> List[int]: """ Return a network mask from the given raw address. >>> get_network_mask('0.0.0.0/8') [255, 0, 0, 0] >>> get_network_mask('0.0.0.0/9') [255, 128, 0, 0] >>> get_network_mask('0.0.0.0/32') [255, 255, 255, 255] ...
9c0a5090b9407ee7d69985455f648ea4328ec783
627,830
def find_subscript_name(subscript_dict, element): """ Given a subscript dictionary, and a member of a subscript family, return the first key of which the member is within the value list. If element is already a subscript name, return that Parameters ---------- subscript_dict: dictionary ...
6d6b088e079cd05c9ccd2637d946e921306e7b5b
627,831
import csv def csv_dict_reader(file_obj): """ Read a CSV file using csv.DictReader """ return csv.DictReader(file_obj, delimiter=',')
587e9cd8ccedfa2b80f0cd48a6b01360f5fc3b8a
627,832
import torch def pdist(vectors): """ vectors shape: (batch_size, k-dimensions) compute the Euclidean distance between any two pairs. using formula distance = ||A - B||^2 = A'A + B'B - 2A'B note: A, B represent vector, respectively. A' denotes transpose of A :param vectors: embeddings of batch_...
cad8e6f4dac8a0c3ab4333d7a9b7c064ec029ac9
627,834
from datetime import datetime from typing import Callable def is_before(time: datetime, now: Callable[[], datetime]=datetime.now) -> Callable[[], bool]: """ :param time: A time :param now: A function to use to get the current time (defaults to datetime.now) :return: A predicate that checks if the curr...
0da53787e9cdb4246172ab86354fb09a61b1c82b
627,838
from datetime import datetime def get_index_time(index_timestamp, separator='.'): """ Gets the time of the index. :param index_timestamp: A string on the format YYYY.MM.DD[.HH] :return The creation time (datetime) of the index. """ try: return datetime.strptime(index_timestamp, separator....
3c89fdd1e816bcfeb58f8792bd14c56974ef579f
627,839
def solution(array): """ Computes number of distinct values in an array. """ # Sets only have distinct values # and creating a set from a list has a good time complexity, as it uses hash tables return len(set(array))
aa4d9b8bb9daa7f3935d2301c330077cd79d9988
627,842
def tokenize(s, keep_punctuation=(), drop_punctuation=(), delimiter=' ', add_start=True, add_end=True): """Tokenizes a sentence Args: s (str): the sentence keep_punctuation (tuple): contains the punctuation to keep drop_punctuation (tuple): contains the punctuation to drop ...
839404d08e2aa8fe7ee4a25a7ab474295e6834b2
627,843
def create_extra_dimensions_stats(customer_records_by_extra_dim): """Groups entry records by customer_id and extra_dimension. Args: customer_records_by_extra_dim: Tuple containing a tuple of customer_id and extra_dimension and a list of transaction records related to that combin...
a616d084496c980ed7dc2a465b84b18be853e701
627,848
def db2lin(value): """Convert logarithimic units to linear >>> round(db2lin(10.0), 2) 10.0 >>> round(db2lin(20.0), 2) 100.0 >>> round(db2lin(1.0), 2) 1.26 >>> round(db2lin(0.0), 2) 1.0 >>> round(db2lin(-10.0), 2) 0.1 """ return 10**(value / 10)
8840989dc365eee46e7836749d3fc8fff14dc048
627,850
import re def isValidModelname(name): """Returns if a name contains characters other than alphanumeric, '_' and '-'. Also, empyt strings are not valid model names. Args: name (str): potential name for a model Returns: bool -- True if the name is a valid model name according to conven...
1d061d3b29d393dd093f5b5f862ecfb503b65d6e
627,852
def Line2Float(line): """Convert a string into a list of Float""" return map(float,line.split())
2f2fa2f1f8bc905a8a3a52f4bbab558dcfe8f2d7
627,853
import socket def get_current_hostname() -> str: """Returns the hostname of current machine Returns: str: current hostname """ return socket.gethostname()
b231dd9acf507b76f64890b7843f6165fcb9b630
627,857
from typing import Iterable from pathlib import Path from typing import Optional def searchcandidates(candidates: Iterable[Path]) -> Optional[Path]: """ Searches for the first filename in `candidates` which exists. Returns `None` if none of the paths are valid. Parameters ---------- candidates: List[Path] T...
d5efeafda07e7b5ef8e3e111ce16df15b3b33f5d
627,859
def determine_color(number): """ In number ranges from 1 to 10 and 19 to 28, odd numbers are red and even are black. In ranges from 11 to 18 and 29 to 36, odd numbers are black and even are red. """ if number >= 1 and number <= 10: return "black" if number % 2 == 0 else "red" elif number...
ab27cc7f40c497d5710645d393f909f176bbde28
627,860
def extract(query_dict, prefix=""): """ Extract the *order_by*, *per_page*, and *page* parameters from `query_dict` (a Django QueryDict), and return a dict suitable for instantiating a preconfigured Table object. """ strs = ['order_by'] ints = ['per_page', 'page'] extracted = { } ...
4deb8f09e3b6185a389736b3eb7fdadb4b82ecfe
627,863
def filterOdometry(solutions, odometry): """Filter the solutions by odometry. Removes solutions from the list if there are not within range of the odometry. Args: solutions: A set of points candidates to the final solution. odometry: Odometry instance. Returns: A list of c...
707c6716f9baf6b5ee6be6adb91ec264aad4e67f
627,865
def mod_Goodman_Fos(sa, sm, Se, Sut): """ Computes the mod Goodman relation factor of safety :param sa: alternating stress :param sm: midrange stress :param Se: Endurance strength :param Sut: Ultimate tensile strength :return: factor of safety """ n_inv = sa/Se + sm / Sut retur...
b98e8335929a8ef40569f25fd46dc7035090a20a
627,871
def flip_left_right(image): """Flips an image left and right. # Arguments image: Numpy array. """ return image[:, ::-1]
aaca0201572ab9fa2df857d82919db0b3f5a102c
627,873
def get_average_solution_length(population): """ Calculate the average distance of the instances within a population Args: population: list of indices with format {"feasible":[], "infeasible":[]} Returns: avg distance of instances in the population """ sum_length = 0 nr_instances ...
347fe771302b75765f71a1ba7c96e3bf3e6f5058
627,875
def updateAlias(old_alias: str, new_alias: str) -> str: """Return a query to update a character's alias.""" return (f"UPDATE alias " f"SET aname='{new_alias}' " f"WHERE aname='{old_alias}';" )
6db124254e42b88017cd4b6b8d82a84c08eb4101
627,877
import json def matdesc_to_unicode(matdesc): """Convert Material Descriptor to Unicode String.""" return str( json.dumps( { "queryId": matdesc.query_id, "smkId": str(matdesc.smk_id), "keySize": str(matdesc.key_size), }, ...
a8ff0cdc4cb625adcea39154af60d4c1b239cf7a
627,881
def bilinear_interp(x1, x2, y1, y2, x, y, q11, q12, q21, q22): """ Perform a bilinear interpolation at the point x,y from the rectangular grid defined by x1,y1 and x2,y2 with values at the four corners equal to Q11, Q12, Q21 and Q22. """ assert x1 <= x <= x2 assert y1 <= y <= y2 asser...
b692c7c48e3c93b491e5ff56ab9c08159bc08f23
627,883
def is_same_module_or_submodule(orig, incoming): """ Returns true if the incoming module is the same module as the original, or is a submodule of the original module """ if incoming is None: return False if orig == incoming: return True if incoming.__name__.startswith(orig._...
a3ecf3f1d9d1546a9f8a30f9ef6609ae9e94cc6e
627,884
import re def strip_internal_comments(text): """Removes internal comments from a string and normalizes whitespace around them. Comments are in the format [[comment]]. For example, the string 'Lorem ispum [[dolor sit]] amet.' will be transformed to 'Lorem ipsum amet.' Further examples: https://www...
3cf00fc44f0aa2614f275f54f4c1d22f190fba3a
627,886
def count_in_layer(layer, number): """Count occurrences of number in layer.""" return sum(row.count(number) for row in layer)
1d70ef128a4688343911b01cd4022493dcd2f19e
627,887
def shift_position(pos, x_shift, y_shift) -> dict: """ Moves nodes' position by (x_shift, y_shift) """ return {n: (x + x_shift, y + y_shift) for n, (x, y) in pos.items()}
c354c713a6a620b0691aeea940f1f14314580c95
627,888
import re def normalize(s): """ Normalizes a string: - replaces any sequence of whitespace characters (including non-breaking space) with a single space character """ if s == None: return None else: return re.sub(r'\s+', ' ', s)
6bb8267a0bc465ce4c0eba22b7311058562c39d5
627,898
def remove_whitespace(string): """Remove whitespace from string""" return "".join(string.split())
60e5396a53f66b94e5b162fec1c90511c268f6e6
627,899
def reversed_enumerate(seq): """Like reversed(list(enumerate(seq))) without copying the whole seq.""" return zip(reversed(range(len(seq))), reversed(seq))
d9623d6557b94b70ee5f73b241e8fd985e5e85a6
627,904
import re def strip_prefix(line): """Remove the [filename:lineno] prefix in a Log line, if present.""" m = re.match(r"^(\[.+:\d+\]\s*)(.*)", line) if m: return m.group(2) else: return line
57bb10f8c1b405087c69ecc2f6538e1728a39307
627,905
def proper(s): """Strips then capitalizes each word in a string.""" s = s.replace("-", " ").title() s = s.replace("_", " ").title() return s
78fa0f28bfdb77fdc572eb851f4021daabdc1a2b
627,906
def clip(input, conf): """ Clip the generating instance with each feature to make sure it is valid :param input: generating instance :param conf: the configuration of dataset :return: a valid generating instance """ for i in range(len(input)): input[i] = max(input[i], conf.input_boun...
a18fb851d76df3b80fe5ac88d6d07291955ce499
627,907
def check_models_have(models, key): """Check models have deserialized the provided key.""" n_err_models = 0 for m in models: if not m.is_deserialized(key): n_err_models += 1 if n_err_models: return "errors: {}/{} models {} don't have key {}".format( n_err_models, ...
b20cb64f386dba6d3a7100e14c76040af2d700f6
627,910
def _val2col(val): """ Helper function to convert input value into a red hue RGBA """ nonred = abs(0.5-val)*2.0 return (1.0,nonred,nonred,1.)
68adb104a7812f0992ec79864a1b8d5d3103e023
627,911
import re def is_snake_case(id_name): """Check if id_name is written in snake case. Actually, it is restricted to a certain subset of snake case, so that we can guarantee camel->snake->camel roundtrip. >>> is_snake_case('') False >>> is_snake_case('_') False >>> is_snake_case('h') ...
2558d1bebdf8405a86b213f7892932616558f3c6
627,913
from __main__ import gearsConfigGet as redisGearsConfigGet def gearsConfigGet(key: str, default=None) -> str: """Fetches the current value of a RedisGears configuration option and returns a default value if that key does not exist. Args: key (str): The configuration option key. ...
a6532b528b033160a21c8eeb7ce8952b3c3481fc
627,915
import random def choose_from_string(string: str, n: int): """ Choose a card from a string. Returns the choice and what remains after choosing. """ assert len(string) >= n choices = [] for _ in range(n): char = random.choice(string) string = string.replace(char, '', 1) choice...
e8605428d046456311333f73c66465319803dc13
627,918
import requests def get_image() -> bytes: """Get a person that does not exist.""" data = requests.get( "https://thispersondoesnotexist.com/image", headers={"User-Agent": "My User Agent 1.0"}, ).content return data
88861bb689ddf17e378fb196cfc8fe4d47fd7dec
627,923
def potential(r, r_c, r_e, r_a): """Potential (Eq. 4) Args: r: distance between agent i and j r_c: hard-core repulsion distance r_e: equilibrium (preferred) distance r_a: maximum interaction range Returns: potential: attractive/repulsive potential """ if r < r...
0cf253ec694c27b43728af5bac77e3dd7e1f7969
627,927
def get_sender(tx: dict) -> str: """ Returns the tx sender's address :param tx: transaction dictionary :return: str """ return tx["events"][0]["sub"][0]["sender"][0]["account"]["id"]
d4bc293a9b92c335ff09fa82f9f7f4f82862a491
627,930
def next_power_of_two(x): # type: (int) -> int """ Compute the next power of two that is greater than `x`: >>> next_power_of_two(0) 1 >>> next_power_of_two(1) 2 >>> next_power_of_two(2) 4 >>> next_power_of_two(3) 4 >>> next_power_of_two...
bc9275767fc863951b91fcc83f8e811aeb77d581
627,933
def harmonic_mean(series: list) -> float: """ return the harmonic mean of series >>> harmonic_mean([1, 4, 4]) 2.0 >>> harmonic_mean([3, 6, 9, 12]) 5.759999999999999 >>> harmonic_mean(4) Traceback (most recent call last): ... ValueError: Input series is not valid, valid serie...
5e88f193f887b064fe190d8d45d9db84a88a3801
627,937
def _weight(role): """Return an integer weight for the given role for sorting purposes.""" if role == "CEO": return 0 return 100
505d761bdcc820c425ff8d85374556cbbad93b48
627,938
def schedule_composition(row): """Takes in a series with $id and \*_ScheduleDay_Name values and return an array of dict of the form {'$ref': ref} Args: row (pandas.Series): a row Returns: list: list of dicts """ # Assumes 7 days day_schedules = [] days = [ "Mond...
6c92c3d1c0a82e20bab01202880dc8fa80d7f826
627,939
def faxen_factor(height, radius, lateral=True): """ Return the relative change of the stokes drag according to Faxen's law. References ---------- Schäffer, E., et al. Surface forces and drag coefficients of microspheres near a plane surface measured with optical tweezers. La...
41bff2f39cf11bdda5453397986841b1c717d974
627,940
from typing import Iterable from typing import Callable from typing import Any def delegate_factory(cls: type, delegate_attrs: Iterable[str]) -> Callable[[Any], Any]: """ Create factory function that searches object `o` for `delegate_attrs` and check is any of these attributes have `cls` type. If no such ...
227fd327fd86edfe577fbbf787869a8bab2a2564
627,942
from typing import Optional def column_name_to_metric_target(col_name: str) -> tuple[str, Optional[str]]: """ Return (metric_name, column_name) from column name that build by this class. """ parts = col_name.split("__") if parts[0] == "table_metric": return parts[1], None if parts[0] =...
a93359ee09dfe4e01c52cb981d2106aae9d8962b
627,944
def lookup_dict_from_url_params(url_params): """Convert a url_params dict in a mapping suitable for ORM querying.""" lookup_dict = {} for k, v in url_params.items(): values = v.split(",") if len(values) > 1: lookup_dict[k] = values else: lookup_dict[k] = v ...
f8cb93a924d01aa45fb0ae926b688a1b640a5e61
627,952
import functools def classdecorator(func): """Class decorator that can be used with or without parameters.""" @functools.wraps(func) def wrapper(cls=None, **kwargs): def wrap(klass): return func(klass, **kwargs) # Check if called as @decorator or @decorator(...). if cl...
48ba5076962746cce374e610c01b7e491cf793af
627,953
from typing import List def cast_trailing_nulls(series: List) -> List: """ Cast trailing None's in a list series to 0's """ for i, x in reversed(list(enumerate(series))): if x is None: series[i] = 0 else: return series return series
3a7f7d53dcb7ed9b892b9b423c3650a339af26e2
627,957
def _is_multiple_records(mem_addr, num_recs): """Return true if we are searching for multiple records.""" return (mem_addr == 0x00 and num_recs == 0) or num_recs > 1
4422ae8563fff77d24026fe431bdedb7f60f44b0
627,959
def _encode_structure_parts(local_target): """ Encodes the design task, to distinguish between struture and wequence domains. Args: A sequence that may contain structure or sequence parts. Returns: A list representation of the sequence with all structure sites and None else. """ ...
deb185b439f7b75b6081ca61e57547bdb87aa981
627,960
import hmac def is_valid_digest(hash_a: str, hash_b: str) -> bool: """Compares two hashes using `hmac.compare_digest`.""" return hmac.compare_digest(hash_a, hash_b)
e2901c596761c6a221d60aaee1d32e8abd0fad42
627,962