content
stringlengths
39
14.9k
sha1
stringlengths
40
40
id
int64
0
710k
def contact_sequence(data, pIDs): """ Given a pd.DataFrame with variables ['gID', 'pID', 'begin', 'end'], generate a contact sequence of events (j, i, t) where j is the group member being interrupted, i is the group member doing the interrupting, and t is the start time of the interruptive speech. Ignores non-i...
bb36b4bddefc094f036a32319a5cdf47b146005d
645,057
import time import copy import torch def train_model(nb_epoch, dataloaders, model, opt, criterion, device, scheduler=None): """ Function to train a model. Args: nb_epoch: number of epoch to train train_dsld: dataset loader for training model: model to optimize ...
f9cbbbf63c779d075bf4caaa56cae45a867b91c4
645,059
def split_param_filter_index1(s): """ Split a parameter name into the <string><number> components where <string> is the parameter name and <number> is the filter index (1-based). If there is no number at the end for a filter index, then return None for the second argument. Returns ---------...
b5c3356184c9bee35cbbeaf81c3de2915c67435b
645,060
def get_diffs(pulse_times, pulses): """ Returns a list of time differences between the pulse times given, corresponding 1 - for - 1 *** PARAMS *** pulse_time (list of strings): list of strings containing the exact time of the pulse. pulses (list of floats): list of floats of the exact time (...
5611be3d0a54e86beff2d115e49703f84be6a3c9
645,061
def get_maxdepth(input_table_A,input_table_B): """Get maximum depth between tables""" #gaps and overlaps maxlist=[] a= input_table_A['todepth'].unique().tolist() maxlist.append(a[-1]) b= input_table_B['todepth'].unique().tolist() maxlist.append(b[-1]) maxl=float(max(maxlist)) return ...
da62d281c611c08663ee3e9a05b3b0afba6d891a
645,062
import torch def concat_without_padding(text_idx, cand_idx, use_cuda, null_idx=0): """ Concatenate two right padded tensors and move padding to the right. For example, if text_idx = [[1, 2, 3, 4, 0, 0 ]] and cand_idx = [[5, 6, 7, 8, 0, 0 ]]: Then result = (tokens, segments) where ...
59ae9ba64c9bee926b0d530043709f74f8ec2db7
645,068
def get_hps(data): """ Get the name of all columns corresponding to hyperparameters """ return [c for c in data.columns if c.startswith("hp.")]
b600c2b5d79af3ae24c791c8723255d80baa1093
645,071
def compareDicts(dict1, dict2): """ Compare two dictionaries, returning sets containing keys from dict1 difference dict2, dict2 difference dict1, and shared keys with non-equivalent values, respectively. Parameters ---------- dict1 : dict dict2 : dict Returns ------- set, set, ...
3f1897193118d8ff16022b55570396dec2c289e9
645,072
def API_fatal(description): """Create an API fatal error message.""" return {"status": "fatal", "error": description}
92b258f30c18c3cea6c8a462c729eca9c2e9da2d
645,076
def power(a, n: int): """Return `a` to the n-th power, uses exponentiation by squaring i.e square and multiply """ # Shortcuts are evaluated here to avoid code duplication if a == 0: if n > 0: return 0 # 0^n = 0 for n > 0 if n == 0: return 1 # a^0 = 1 (0^0 = 1 is a co...
9343404bf8c3a438e953f1fdedcf213318249e86
645,077
import unicodedata async def _get_all_intents(skills): """Get all skill intents and concatenate into a single markdown string.""" intents = [skill["intents"] for skill in skills if skill["intents"] is not None] if not intents: return None intents = "\n\n".join(intents) return unicodedata.n...
f498d90e5dca49350579ab882dfc3ed069cb31dd
645,078
def total_gross_income(responses, derived): """ Return the total gross income of both claimants """ try: claimant_1 = float(responses.get('annual_gross_income', 0)) except ValueError: claimant_1 = 0 try: claimant_2 = float(responses.get('spouse_annual_gross_income', 0)) exc...
8ca58266794d6b6ce1166ac50ad318ceafa8d30c
645,080
def gross_count(spec, c1, c2): """Returns total number of counts in a spectrum between two channels""" if c1 > c2: raise ValueError("c1 must be less than c2") if c1 < 0: raise ValueError("c1 must be positive number above 0") if c2 > max(spec.channels): raise ValueError("c2 must ...
154f0e45463d38bd8dfb6ab1f678ef2d1980410c
645,081
def asbool(value, true=(b'true', u'true'), false=(b'false', u'false')): """Return string as bool if possible, else raise TypeError. >>> asbool(b' False ') False """ value = value.strip().lower() if value in true: # might raise UnicodeWarning/BytesWarning return True if value in fa...
3b043be4e6c479a16c9bc22f068ff47bc36ec11b
645,086
import re import copy def _getZoneData(line): """ Extract TecPlot formatted zone data from a line, return as two lists of keys and matching values. Attributes ---------- * ``line`` (`string`): string representation of a line in a TecPlot file Returns ---------- * `list` with all the names of zone properti...
3e69178dbaef3ffb9997462cbe97f6dd48be4d56
645,088
import hashlib def get_hash_string_of_numpy_array(array): """ Returns a 32 character long string that is a deterministic hash of a numpy array's data. """ return hashlib.md5(array.data.tobytes()).hexdigest()
62dd603c246f7351ddecf2f76c49a4f55becc285
645,090
def maskAngLT452(image): """ mask out angles >= 45.23993 Parameters ---------- image : ee.Image image to apply the border noise masking Returns ------- ee.Image Masked image """ ang = image.select(['angle']) return image.updateMask(ang.lt(45.23993)).set('sy...
2b310c0542b770858595c5fa027bddbb1c43da33
645,092
def prettyPrintResults(evaluationResults): """prettyPrintResults returns a string formatting the results of a simulation evaluation result""" output = "" for er in evaluationResults: message = ( f"Evaluated Action Name: {er['EvalActionName']}\n" f"\tEvaluated Resource name: {...
637846fb2e54922d20d912170cadd1b9552d43a9
645,094
def plot_wrapper(self, func, *args, cmap=None, values=None, **kwargs): """ Calls `~proplot.axes.Axes.parametric` if the `cmap` argument was supplied, otherwise calls `~matplotlib.axes.Axes.plot`. Wraps %(methods)s. Parameters ---------- *args : (y,), (x, y), or (x, y, fmt) Passed to `~m...
fcec48a978da8b653f71a1980032af88170cb551
645,095
from typing import List def max_profit(prices: List[int]) -> int: """ Find the maximum profit that can be made from buying and selling a stock once """ if prices is None or len(prices) < 2: return 0 min_price = prices[0] current_max_profit = 0 for price in prices: if pric...
a411fde1659aa187484e6fbea7633d41ffae8868
645,096
def element_to_apparent(element): """Create an apparent element from an element. Parameters ---------- element The element. Returns ------- A tuple (ElementType, Direction). """ return (element.element_type, element.direction)
9f9e3a6ce870e6aeef33dbe4fd1b6c8502a7458f
645,097
def _fmt_string(array, float_format="{}"): """ makes a formatting string for a rec-array; given a desired float_format. Parameters ---------- array : np.recarray float_format : str formatter for floating point variable Returns ------- fmt_string : str formatting...
05f687ef5cd0121198e7e7fce74480fe9867e05a
645,099
def merge(left, right): """Merges two sorted sublists into a single sorted list.""" ret = [] li = ri =0 while li < len(left) and ri < len(right): if left[li] <= right[ri]: ret.append(left[li]) li += 1 else: ret.append(right[ri]) ri += 1 ...
88f8550ad67941d1956e67b28d9ed29017975dfb
645,103
def matrix_max(matrix): # SYFPEITHI NORMALIZATION """Returns the maximum attainable score for a pssm""" return sum([ max(value.values()) for _, value in matrix.items() ])
60f166ce15b844d3bf958d66ec6452e318a49561
645,104
def padding(corpus, logger=None): """ Performs padding on the already tokenized documents Args: corpus (list): A list of strings where elements are the tokens from your document. logger (Logger): Returns: A list of strings where elements are all at equal length """ ne...
bb160b021c5f8d92afe758cc2bf605837e060974
645,105
import pickle def top_n_bigrams(pkl_file_name, N, shift=0): """ Returns a dictionary of form {bigram:rank} of top N bigrams from a pickle file which has a Counter object generated by stats.py Args: pkl_file_name (str): Name of pickle file N (int): The number of bigrams to get ...
8bcffa98c3c585e4da11650890d1f936fca040d9
645,109
def list_is_nested(input_list: list) -> bool: """This function checks whether the input_list is nested (i.e. it is a list of lists). Args: input_list (list): the input list Returns: is_nested (bool): True if list is nested, False if it isn’t """ is_nested = any(isinstance(i, list) fo...
ed3eccd77ae8a53d75f040ee6ba44c932dbf1cf3
645,114
def recursive_fold(left, right): """ Recursively folds (reduces) two records. Parameters ---------- left : dict The "left-hand", or current, record. right : dict The "right-hand", or next, record. Returns ------- left : dict The folded (reduced) record. "...
f93f836a1351806f9691cfd5fbe1ca7ee6058bae
645,116
def load_labels_file(file_path): """ Reads the 'classes.txt' file and returns a class dictionary. Args: file_path: Full path to the 'classes.txt' file. Returns: classes: Dict in the format: 'classes[class_name] = class_id'. """ classes = {} with open(file_path, 'r') as file: ...
f26484546cec1c41a86614def5f969f10c57e5d3
645,117
def epsilon_schedule(eps: float, n_frames: int) -> float: """ Epsilon is annealed linearly from 1 to 0.1 over the n_frames """ change = (1 - 0.05) / n_frames eps -= change eps = max(eps, 0.05) return eps
556424fa4e6277ed397b09710078f5353fdaa073
645,119
def gcdr(a, b): """Recursive Greatest Common Divisor algorithm.""" if b == 0: return a if a<b: a,b = b,a print(a,b) return gcdr(b, a%b)
7edd0742f2f57dbed839b345067df734ec5e4544
645,120
def get_empty_marker_error(marker_type): """ Generate error message for empty marker. """ msg = ( "no configuration file is specified in " "``@pytest.mark.gdeploy_config_{0}`` decorator " "of this test case, please add at least one " "configuration file file name as a par...
92bb8c554d1d84ec64395ff6d7d749bde5a8d5b6
645,122
def find_value(keys, d, create=False): """Return a possibly deeply buried {key, value} with all parent keys. Given: keys = ['a', 'b'] d = {'a': {'b': 1, 'c': 3}, 'b': 4} returns: 1 """ default = {} if create else None value = d.get(keys[0], default) if len(keys) > 1 and ty...
c4b4e039bf6a2f159deee510b79ca8aaa7d179a7
645,123
def convertir(hora: str) -> str: """Convierte una hora en notación de 24 horas a 12 horas. :param hora: Hora a convertir :hora type: str :return: Hora en notación de 12 horas :rtype: str """ hora_24 = int(hora[:2]) hora_12 = 12 if hora_24 % 12 == 0 else hora_24 % 12 return f"{hora_1...
d274761c151908b3013b5973047d25781136f053
645,125
def path_concordance_jspecies(path_fixtures_base): """Path to JSpecies analysis output.""" return path_fixtures_base / "concordance/jspecies_output.tab"
8dbeb6296a050555eaf520a3d2e563ecadcc12a4
645,126
def normal_from_ineq(s_ineq): """ Get the normal stored in the phase surface inequalitie vector :param s_ineq: A phase data surface vector (see SL1M output doc) :return: The surface normal, as an array of size 3 """ return s_ineq[2]
2e5c5e839407cff51880bc9b30b6107fd7f372c3
645,130
def _get_from_onclick(node, index): """Private function to grab a value in the "`onclick`" attribute. Grabs the value in the specified index of the "`onclick`" attribute of a selectolax `Node`. Args: node (:class:`Node`): A `Node` containing the "`onclick`" attribute. index (:obj:`int`...
aa41f9a3234c3d53f92f22feed6af4f853efb7bf
645,131
import typing def is_basic_iterable(obj: typing.Any) -> bool: """Checks if an object is a basic iterable. By basic iterable we want to mean objects that are iterable and from a basic type. :param obj: Object to be analysed. :return: True if obj is a basic iterable (see list below). False otherwi...
48a87ea430021fe7086ba9c17d973da1ef5f7fdd
645,138
def set_data_types(data_types=["userAcceleration"]): """ Select the sensors and the mode to shape the final dataset. Args: data_types: A list of sensor data type from this list: [attitude, gravity, rotationRate, userAcceleration] Returns: It returns a list of columns to use for cr...
4a08ba2d33ce77a4fa8a33b8d4c2f02174c6cefb
645,142
def false_to_none(ctx, param, value): """Convert a false value to a None""" if value: retval = True else: retval = None return retval
3c25c725473ff7c271c1819170e0332db3810dd8
645,146
import random def face(x, y): """ Calculates points to fill in order to plot a smiley-face on a graph of x and y dimensions Parameters ---------- x: x-axis resolution (how many points desired in x-axis) y: y-axis resolution (how many points desired in y-axis) ...
504bcb68a511a2cfad57a12d2dc480757891e8ad
645,149
def convert_big_str_numbers(big_num): """Convert big number written with numbers and words to int. Args: big_num (str): number, written with numbers and words. Returns: int: same number as an int. Examples: >>>print(convert_big_str_numbers('101.11 billions')) 101110000...
44699108d1ebac79d55df620ce851a6ecf96376d
645,150
import re def read_header(ds): """Read a RAMSES output header file.""" folder = './' iout = int(str(ds)[-5:]) hname = '{0}/output_{1:05d}/header_{1:05d}.txt'.format(folder, iout) with open(hname, 'r') as hfile: htxt = hfile.read() header_re = re.compile("Total number of particles\s+(...
3d19aa144e25ab2bfccf0ec422ba3a4db4542b20
645,153
def collect_vertices(geometry): """Returns all vertices within the given geometry as a list.""" vertices = [] vertices_iter = geometry.vertices() while vertices_iter.hasNext(): vertices.append(vertices_iter.next()) return vertices
19381cb28a475e62f47240a1cadef481a5f34a44
645,154
def convert_keys_to_variable_names(dict_): """ Change keys in dict to comply with PEP8 for variable names. Keys are converted to all lower case and spaces replaced with underscores. Parameters ---------- dict_ : :class:`dict` Dictionary the keys should be renamed in Returns --...
de6e9d69fce1ec1b7672159e096793ba0687459d
645,158
import binascii def pem_to_der(pem_str): """Convert a PEM string to DER format""" lines = pem_str.strip().splitlines() der = binascii.a2b_base64(''.join(lines[1:-1])) return der
6b551c1852aa587152a6ce9c29c68c0044239dd7
645,159
def parse_requirements(filename): """Given a filename, strip empty lines and those beginning with #.""" with open(filename) as rfd: output = [] for line in rfd: line = line.strip() if line != '' and not line.startswith('#'): output.append(line) ret...
f4989867b217e694f9c05be25c9b213ec1dd4b7b
645,169
def get_gene_class(gene): """ Return the class of a gene. Available options are Core or Non-core. """ core_genes = ['pif-0', 'pif-1', 'pif-2', 'pif-3', 'pif-4', 'pif-5', 'pif-6', 'pif-7', 'pif-8', 'dnapol', 'desmoplakin', 'dnahe...
1dfb95d0e97565c3f0e2000d315d0d635a8ed73a
645,174
def _create_database_sql(database_name): """Return a tuple of statements to create the database with the given name. :param database_name: Database name :type: str :rtype: tuple """ tmpl = "create database {} with owner = dcc_owner template = template0 " \ "encoding = 'UTF8' lc_collat...
48fc179d282750d162eb7544cf4b594d0e2f0729
645,176
def drop_columns(cols): """Drop columns in a DataFrame.""" def dropper(data): return data.drop(columns=cols) return dropper
e93b1e45b9eda800aa812a41a02c78f459d65172
645,179
def GetModulePath(obj): """Returns the module path string for obj, None if its builtin. The module path is relative and importable by ImportModule() from any installation of the current release. Args: obj: The object to get the module path from. Returns: The module path name for obj if not builtin ...
2d98b63d49c177353edf92bd722e19dadb5b7d82
645,180
import torch def uniform_sample_shape(batch_size, mean_shape, delta_betas_range): """ Uniform sampling of shape parameter deviations from the mean. """ l, h = delta_betas_range delta_betas = (h-l)*torch.rand(batch_size, mean_shape.shape[0], device= mean_shape.device) + l shape = delta_betas + ...
8d8d5880e5963231661f49b1f0fd91d6fffe0f7e
645,181
def depth(expr): """ depth(expr) finds the depth of the mathematical expr formatted as a list. depth is defined as the deepest level of nested operations within the expression. """ if not isinstance(expr, list): raise TypeError("depth() : expr must be of type list") else: exprlen...
15da365f83432093ea42b60dc3b2f49da206d9fd
645,184
from typing import Dict import pkg_resources def get_current_environment_requirements() -> Dict[str, str]: """Return package requirements for current python process. Returns: A dict of package requirements for current environment """ return { distribution.key: distribution.version ...
e9916b718d9ded2da2105306b7e2cc426ccc208e
645,185
def squareroot(n: int) -> str: """Return string vertion of int prepended with a unicode radical symbol. Useful for pretty printing elements of, for example, a quadratic field. Example: >>> print(squareroot(5)) √5 """ return u"\u221A"+str(n)
b154d04698c291ace2457dab005169306614f0eb
645,191
def get_maximum_telemetry_message_size(client): """ Returns the maximum message size (in bytes) the client can support """ if client.settings.language == "java" and client.settings.transport == "amqpws": # java amqpws limitation. Actual number is unknown. This just blocks 63K+ tests. #...
5aa4b7e17526b22ff0ac1cbc567ce130aa15cf91
645,198
import torch def gershgorin_bounds(H): """ Given a square matrix ``H`` compute upper and lower bounds for its eigenvalues (Gregoshgorin Bounds). """ H_diag = torch.diag(H) H_diag_abs = H_diag.abs() H_row_sums = H.abs().sum(dim=1) lb = torch.min(H_diag + H_diag_abs - H_row_sums) ub ...
c26cd15a781d4317558fa844ccf3bde61f36d3dd
645,199
def to_bytes(s): """ Turns the string with suffix of KiB/MiB/GiB into bytes. :param s: the string (NUM SUFFIX) :type s: str :return: the number of bytes :rtype: int """ factor = 1 if s.endswith(" KiB"): factor = 1024 s = s[:-4].strip() elif s.endswith(" MiB"): ...
f44c9eef5715a7ed68161045d1bc4c018a9d862c
645,202
import socket def find_unused_port(base=1025, maxtries=10000): """Helper function. Finds an unused server port""" if base > 65535: base = 1025 for _ in range(maxtries): serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) try: serversocket.bind(("localhost",...
1af439ac6882b760ce5a6b0abded895c8b0d1d12
645,203
def capitalize(line): """Capitalize the first char in a string string.capitalize messes up deliberate upper cases in the strings so here's a dedicated function. Args: line (str): The string to capitalize Returns: str: The capitalized string """ return line[0].upper() + l...
4737d6db527866229673be381ebd3a27e6970874
645,204
import csv def parse_csv_data(csv_filename: str) -> list: """A function thats takes in the name of a csv file and returns a list of strings for the rows in the file""" rows = [] # a list containing the strings for the rows with open("{}".format(csv_filename)) as csv_file: csv_reader = csv.reade...
b3f5c951b1296090b5aba6b81725670baf68fe1f
645,205
from typing import List def to_factorial_base(n: int) -> List[int]: """ Convert a nonnegative integer to its representation in the `factorial number system <https://en.wikipedia.org/wiki/Factorial_number_system>`_ (represented as a list of digits in descending order of place value, not including t...
bcee7f9165267bfb9370f0b1256cae4ed7f04237
645,206
def normalize (bbox): """ Normalizes EPSG:4326 bbox order. Returns normalized bbox, and whether it was flipped on horizontal axis. """ flip_h = False bbox = list(bbox) while bbox[0] < -180.: bbox[0] += 360. bbox[2] += 360. if bbox[0] > bbox[2]: bbox = (bbox[0],bbox[1],bbox[2]...
3713b1c4c9d12a9c6d0de5308382bf9464ec672c
645,207
def bandwidth_converter( number, *, from_unit, to_unit, from_time="seconds", to_time="seconds" ): """ Bandwidth Calculator. Convert data rate from one unit to another. Arguments: number (int): number to be converted Keyword arguments: from_unit (str): convert from this da...
93068fb52bc3cd04615749e61a6ecea54b2eda0f
645,208
def checkNull(dummy_dictionary): """Given a dictionary, checks if any of the values is null""" return None in list(dummy_dictionary.values())
cb19c755a39df123e944ea1ae2b4c1d721161071
645,209
import re def camel_case_to_snake_case(s): """Convert string in CamelCase to snake_case. Args: s (str): String in CamelCase. Returns: str: String in snake_case. """ _underscorer1 = re.compile(r"(.)([A-Z][a-z]+)") _underscorer2 = re.compile("([a-z0-9])([A-Z])") subbed = _und...
7ad89d0f7ff5d4c5669ccdab13cda98bdfa4e502
645,211
def get_yesno_input(text): """ Gets a yes/no input from the user. The user can type "y" for yes or "n" for no. :param text: Text to ask user (the yes-no question) :return: True for yes and False for no """ while True: user_input = input(text + " [y/n] ") if user_input[0] == 'y': ...
0af3456fca58596af12e0db0ada080a8cadf1035
645,212
def get_accel_y(fore_veh, back_veh, ego_vy, idm_model): """ A wrapper around IDM, given a front and a back vehicle (and the absolute speed), and a longitudinal driver model, this function returns the desired acceleration of the back vehicle. Arguments fore_vehicle: A vehicle object, f...
847cc4c7ed02bb27dcfb0bfed966ad2699cd90b6
645,215
def append_df_columns(dataframe1, dataframe2, dataframe2_col_name, new_appended_col_name): """Appends a column of data from one dataframe to another dataframe Args: dataframe1 (df): Dataframe to append new column on dataframe2 (df): Dataframe to pull column of data from dataframe2_col_na...
ff1af8848cbc0c4767d91299895dbc0631c6cb54
645,217
def is_valid_key(key): """ Return false if key is not alphnumeric or start with letter """ if key == "": return False # check if no invalid charaters if key.isalnum(): # check if first char is letter return key[:1].isalpha() return False
6a0337167f3ef960ab39f3527da84349830a2291
645,218
import timeit def depthwise_conv_timer_mxnet(c, n, k, ctx): """Benchmark convolution in MXNet c : input, output channels n : input width and height k : kernel width and height """ timer = timeit.Timer( setup='import d2ltvm\n' 'import mxnet as mx\n' 'c, n, k, p, s = %d,...
c927503c399c0005010a0165679a5cfd2dec20b3
645,224
def get_file_content(file_path): """Return content of a file.""" return open(file_path).read().strip()
f5047e4ca47f5cc36b5d13e7823f4db3a363d45f
645,225
def get_unique_instruments_in_channel(notes_in_channel): """ Utility function to get an ordered set of unique instruments in the channel """ all_instruments = [] for notes in notes_in_channel: all_instruments.append(notes.program) return sorted(set(all_instruments))
6e69f143886456a3667ac997222227cdbfdccdd1
645,231
def attr(elem, attr): """An html attribute from an html element. E.g. <a href="">, then attr(elem, "href") will get the href or an empty string.""" try: return elem[attr] except: return ""
42f34cf67bb5b59ed9f9ace0005ed37aebf079b0
645,236
import math def vd(inc, sd): """ Calculate vertical distance. :param inc: (float) inclination angle in degrees :param sd: (float) slope distance in any units """ return abs(sd * math.sin(math.radians(inc)))
730a1d7ae82c79b327af7e6452a498ff8a04868a
645,240
def module_import(app_path): """ Imports a module in a given path. :param str app_path: A string that contains the path of the module and it's name. :returns: A reference to the module in the given path. """ module = __import__(app_path) for part in app_path.split('.')[1:]: ...
8da8c0a6bd35fc5edf174d8751b28122394312b9
645,242
def canonize_dtypes_and_names(a=None, t=None, y=None, w=None, X=None): """ Housekeeping method that assign names for unnamed series and canonizes their data types. Args: a (pd.Series|None): Treatment assignment of size (num_subjects,). t (pd.Series|None): Followup duration, size (num_subjec...
84f7392a215392715a1c43de18585a748f3c4147
645,243
def intervalComparison(x, lowerBound, upperBound): """ classify a value relative to the interval between two bounds: returns -1 when below the lower bound returns 0 when between the bounds (inside the interval) returns +1 when above the upper bound """ if (x < lowerBound): return -1 if (x > upperBound): return...
8725473f029540ee67c48f9cea3f342d7ea28182
645,247
import itertools def make_range(start, end): """Return a generator of the time steps to iterate over""" if end is None: return itertools.count(start=start, step=1) else: return range(start, end)
8e8f5e4561c2b1781ad2c0ec96c20c9e0a91e374
645,248
import inspect def deduce_protobuf_types(fn): """ Try to extract the class names that are attached as the typing annotation. :param fn: the function with the annotated parameters. :return: a list of classes or None. """ spec = inspect.getfullargspec(fn) if not spec: return None ...
b11b3bdfa5acdcfbfd9958017f583e6bc3b3386f
645,249
import math def inverse_mercator(xy): """ Given coordinates in spherical mercator, return a lon,lat tuple. """ lon = (xy[0] / 20037508.34) * 180 lat = (xy[1] / 20037508.34) * 180 lat = 180 / math.pi * \ (2 * math.atan(math.exp(lat * math.pi / 180)) - math.pi / 2) return (lon, lat)
39c33ca87c475efa5f21366f176429800c478f87
645,252
import collections def filter_words(line, count): """ Filter words in documents less than count. """ cnt = collections.Counter() for sentence in line: cnt.update(sentence) s = set(word for word in cnt if cnt[word] < count) l_temp = [[word for word in sentence if word not in s] for sentenc...
6a91cbbe9ec3e50efef992406217a888ad386d4b
645,254
def _user_info(user): """Format a user.""" return { "id": user.id, "name": user.name, "is_owner": user.is_owner, "is_active": user.is_active, "system_generated": user.system_generated, "group_ids": [group.id for group in user.groups], "credentials": [{"typ...
99505e0d721ff3c289a25a9903bc21d304cbd3de
645,263
import re def clean_name(name): """cleans a name by removing all non-alphabets""" regex = re.compile('[^a-zA-Z]') return regex.sub('', name)
1104adb1eb863fdd8466ce335aa11a683de0f3e4
645,270
def model(k, alpha, beta, gamma): """Returns values of alpha-beta-gamma model at given k values Parameters ---------- k : array alpha, beta, gamma : float Parameters of model """ T = (1 + (alpha * k) ** beta) ** gamma return T
9e5986f92be2efba9fcc91fc5f08e6ae16605d2d
645,271
def rgb2gray(rgb_img): """ Parameters ---------- rgb_img : numpy array with shape as (3, X, Y) image to convert in gray Returns ------- gray_img , the grayscale image """ gray_coef = [0.2989, 0.5870, 0.1140] r = rgb_img[0] / 255 g = rgb_img[1] / 255 b = rgb_img[...
d6b582253eed18c1810f584bda815a7b98f74ec4
645,274
def _map_theme(theme: str) -> str: """Maps a survey schema theme to a design system theme :param theme: A schema defined theme :returns: A design system theme """ if theme and theme not in ["census", "census-nisra"]: return "main" return "census"
10233327015d5a9f94fea05b4d477cab8b572e3a
645,277
def getFileExtension(f) : """Gets the file extension, and returns it (in all lowercase). Returns None if file has no extension. Keyword arguments: f - file name possibly with path """ i = f.rfind(".") return f[i+1:].lower() if i >= 0 and f.rfind("/") < i else None
9b0362ed720f77e71a64fca5b7311d92ce37183a
645,278
def set_cat_default(available_options): """Callback to set category dropdown default value. Args: available_options: list of categories from dropdown Returns: first value from category dropdown to set as default dropdown value """ return available_op...
51407d945a85bc9ba0873e1c378a4c2da12493b0
645,279
def multi_cdf(m, bound, capacity, f): """ This function computes the value of the cdf of the multivariate random variable (X1+X2+...Xn). For a given distribution it gives back the probability, if the sum of the random variables is lower or equal to a specific bound. Therefore it uses the feasible_me...
abaceee5b2ad93b77bcd569ee0a00d2ade4688ec
645,280
def update_log_level(logger, level): """Update the logging level. Args: logger (:class:`logging.Logger`): Logger to update. level (Union[str, int]): Level given either as a string corresponding to ``Logger`` levels, or their corresponding integers, ranging from 0 (``...
dede5ee698f4831853df7c98bd9927ebc86acfe1
645,285
import io def tobytes(image): """Convert an image object to a PNG byte array""" data = io.BytesIO() image.save(data, format='PNG') return data.getvalue()
03bee05b214aefad0cb6e265f8078065ff2f5f6e
645,287
def spherocylinder_aspect_ratio(l, R): """Return the aspect ratio of a spherocylinder, Parameters ---------- l: float Length of the cylinder section. R: float Radius of the hemispheres and cylinder sections. Returns ------- ar: float Aspect ratio. This i...
5900b4dd098e57db67065e64c41c37d4cb31733e
645,288
from typing import Dict def create_result_dict() -> Dict: """ Create the results dictionary """ return {"Vulnerable Library": None, "Version": None, "Language": None, "Vulnerability": None, "CVE": None, "CVSS": None, "Upgrade to Version": None}
1405954b51308ce08324574d01a43c712f8552bb
645,290
def hex_color_to_tuple(hex): """ convent hex color to tuple "#ffffff" -> (255, 255, 255) "#ffff00ff" -> (255, 255, 0, 255) """ hex = hex[1:] length = len(hex) // 2 return tuple(int(hex[i*2:i*2+2], 16) for i in range(length))
0432f3335e13b9b2b91de1a6799d42ed4b45d40b
645,291
def reverse(pattern): """Reverse a string sequence. For example, if we reverse the string 'ACGT', we would get 'TGCA'.. Args: pattern (str): a DNA string (i.e. pattern). Returns: String, a reversed string of the given pattern. Examples: Reverse a pattern string. ...
55b3b16369e1a075b49291071085d07546368d96
645,293
def python_3000_has_key(logical_line): """ The {}.has_key() method will be removed in the future version of Python. Use the 'in' operation instead, like: d = {"a": 1, "b": 2} if "b" in d: print d["b"] """ pos = logical_line.find('.has_key(') if pos > -1: return pos, "W601...
1be1f91c6f52960b138ae05297b0b7f9b5123dc0
645,301
def _sanitize_url(url): """ Makes sure that the URL ends with a trailing ``/`` for Pooch. Parameters ---------- url : str The URL for downloading the data, with or without a trailing ``/``. Returns ------- url : str Sanitized download URL. """ if not url.endswit...
0df8002e2e57bea5254f0a9b67eb35abdc872d70
645,302
def db_name() -> str: """Database name""" return 'olist_ecommerce'
cca63e5b1f6130b5dbd6786d0b31b4e7fc4ae6f2
645,306
def _fullname(o): """Return the fully-qualified name of a function.""" return o.__module__ + "." + o.__name__ if o.__module__ else o.__name__
e4a93a30f9e18ede4c3f1da641b51cf42724ee92
645,308