content
stringlengths
39
14.9k
sha1
stringlengths
40
40
id
int64
0
710k
def mode(prediction, pad='[PAD]'): """Returns most common predicted item or pad if no items were predicted""" if prediction: return prediction.most_common(1)[0][0] return pad
6d4ba9446f465b3663020205ee271aca076aceb0
86,276
import random def sample_lines(lines, proportion): """Sample a proportion of the lines to use for modification later. Arguments: lines: list of strings of documents proportion: float between 0 and 1 of proportion of documents to use in the sample Returns: a tuple ...
5b6ff861f34ce270842b3bd2cbc4d10b3540bcc0
86,281
def remove_new_stat_vars(stat_vars, client): """ Removes Statistical Variables that do not already exist. Pulls the existing StatVar list from production and makes sure that no new statistical variables are added. This function is used in the event that you need to refresh a file dependent on this generatio...
67512c423634f5e7c4bcbe5cdb25cb9d39ff2ce4
86,285
def get_sweep(hyper): """Returns hyperparameter sweep.""" domain = [ hyper.sweep('config.word_weights_file_weight', hyper.discrete([0.25 * i for i in range(5)])), hyper.sweep('config.psl_constraint_learning_weight', hyper.discrete([0., 0.001, 0.005, 0.01, 0.05, 0.1]))...
79e07e11d31321fef9869637b510cd493a904382
86,286
def uniquefy(seq): """ duplicated members only keep one copy. [1,2,2,3,3,4] => [1,2,3,4]. """ seen = set() return [x for x in seq if x not in seen and not seen.add(x)]
b2020058856d89746555daec3c5cc0b68752e5f8
86,298
import csv def get_tsv_header(input): """Get a header of a tsv file. Column counts of the first (header) and second (content) line are compared. If the header has one column less than the content, then a new column is added to the beginning of the returned list (convention in Chipster to handle ...
dc66e14da5158e691d02a8085ff1ae6ef8a9d3eb
86,300
import shutil def command_is_available(command_name: str) -> bool: """Return whether given bash command is available in PATH. Parameters ------------------ command_name: str, The command to check availability for. Returns ------------------ Boolean representing if the command is ...
541200b2414edd43f8631be745abb84e3ad2b9b7
86,301
import threading def inthread(f, *args, **kwargs): """A convenience function for starting a Python thread. This function launches a Python thread in Daemon mode, and returns a reference to the running thread object. Arguments: f: A reference to the target function to be executed in ...
2255a04bfc8a1d9343ad3844ab9b982a1811a136
86,302
import yaml def make_rushfile(make_tmpdir): """Creating dummy rushfile.yml.""" # dummy rushfile path tmp_dir, tmp_path = make_tmpdir # dummy rushfile contents content = """task_1: | echo "task1 is running" task_2: | # Task chaining [task_1 is a dependency of task_2] task...
4ab258bd61e4abc873addfe6cd8ae02bcc9bac17
86,306
def get_mse(df): """calculate MSE of df, assuming column1 is actual column2 is predicted""" true = df.columns[0] predicted = df.columns[1] return ((df[true]-df[predicted])**2).mean()
083e12686bc7a81736b2a159e4b5f0d4241168c0
86,311
def mandatory_arguments(parameters, parent=None): """Get a list of parameter names that are mandatory. The optional parent parameter allows to request mandatory parameter for nested components. Parameters ---------- parameters: dict(benchtmpl.workflow.parameter.base.TemplateParameter) Dicti...
cebda64776f0500e51ea400db1db9de2d28ec653
86,315
def calc_received_power(eirp, path_loss, receiver_gain, losses): """ Calculates the power received at the User Equipment (UE). Parameters ---------- eirp : float The Equivalent Isotropically Radiated Power in dB. path_loss : float The free space path loss over the given distance...
bc3fe5e76b66f8956297b583f7337da954901387
86,326
from typing import Tuple import timeit def bench(fn_name: str) -> Tuple[float, float]: """Benchmark the supplied function.""" result = timeit.timeit( fn_name, globals=globals(), number=100_000 ) return (result, result / 100_000)
d627ba3667ef8d08ffe8e48b141c5484365b0e94
86,328
def get_totals(path_sha_loc): """Returns: total numbers of files, commits, LoC for files in `path_sha_loc` """ all_commits = set() total_loc = 0 for sha_loc in path_sha_loc.values(): all_commits.update(sha_loc.keys()) total_loc += sum(sha_loc.values()) return len(path_sha_loc), ...
944b6d2b002b5d3eb324d091ae58281bbadf9863
86,329
def split_date(date): """ Splits date from format %y%m%d to %y-%m-%d """ date = str(date) y = date[:4] m = date[4:6] d = date[6:] return '-'.join([y, m, d])
0bfea4072e7a45e77ed54f37890e3a0eb2da4d1f
86,331
def _entity_skill_id(skill_id): """Helper converting a skill id to the format used in entities. Arguments: skill_id (str): skill identifier Returns: (str) skill id on the format used by skill entities """ skill_id = skill_id[:-1] skill_id = skill_id.replace('.', '_') skill_...
090607ed7b59f03784698072f3644624cc35d129
86,335
def center_cloud(cloud, plot_center): """Center cloud data along x and y dimensions.""" x_center, y_center = plot_center cloud[0] = cloud[0] - x_center cloud[1] = cloud[1] - y_center return cloud
7ef7484f78d74bc58338828643d638dec3c70f94
86,338
def tcl_str(string=''): """ :param string: Python string. :returns: Tcl string surrounded by {}. """ return ' {' + string + '} '
7552ff9a44d374f6fbfffbb0c9da9e2e2ea2e071
86,342
def overlap(start1, end1, start2, end2, tolerance=0): """Check that range (start1, end1) overlaps with (start2, end2).""" # Taken from https://nedbatchelder.com/blog/201310/range_overlap_in_two_compares.html return end1 + tolerance >= start2 and end2 + tolerance >= start1
3b70a6fb7be67cc07d45eeb61a3f70899ae3455a
86,345
import torch def outer(v1, v2): """Compute the outer product between two vectors. Simple wrapper to deal with several torch versions. Args: v1: The first vector. v2: The second vector. Returns: (torch.Tensor): The outer product. """ try: return torch.oute...
80be663dfff6a7bb34f62800fb2f18160b1753c6
86,346
def close(f1, f2, epsilon=0.0001): """Checks if f1~f2 with epsilon accuracy.""" return abs(f1-f2) <= epsilon
1d28b42a804e796b528903eb36b8d4cebe3e746f
86,350
def is_blocked(viewer, user): """is this viewer blocked by the user?""" if viewer.is_authenticated and viewer in user.blocks.all(): return True return False
b92c7b8d2b1348b38620c772ddfecf8c38c1b0b2
86,352
def correct_gravity(sg, temp, cal_temp): """Correct a specific gravity reading to the specified calibration temperature Args: sg (float): Measured specific gravity temp (float): Measurement temperature in degrees Fahrenheit cal_temp (float): Hydrometer calibration temperature in degrees...
c9f70212441af665ba0d2c889285e3a75c3e5423
86,356
import re def _IsGitHash(revision): """Checks whether the input looks like a SHA1 hash.""" return re.match(r'[a-fA-F0-9]{40}$', str(revision))
0fb496f5ab796cb06e30e1e35bf33bc9e38ce1bd
86,357
def get_default_indicator_name(predictor): """Get default name for indicator variable.""" return 'i_{}'.format(predictor)
6b27597a58ba65f3a60a64275b8520a68972c111
86,359
from typing import Mapping def get_attribute(obj, attr_name): """ Return object attribute. Can work with dictionaries. :param object obj: Object for search attribute. :param str attr_name: Attribute name. :return: Found attribute or exception. :rtype: object :raise AttributeError: If at...
db6eed214f0d08b3bb2d7dd9cb5a01b6af1c3cfe
86,360
def _return_stderr(cfg, data): """Check if standard error should be returned.""" return (data.get('var_type') == 'prediction_input' and cfg['return_trend_stderr'])
c4066c2bca051a469f1ff9afaa0c0e16220b3e22
86,364
def get_extended_attention_mask(attention_mask): """ Makes broadcastable attention and causal masks so that future and masked tokens are ignored. Arguments: attention_mask (`torch.Tensor`): Mask with ones indicating tokens to attend to, zeros for tokens to ignore. Returns: `t...
a7ded6363ab5f28377c7cd54f86a9b6bb6101b07
86,366
import torch def _second_deriv(arr, dt): """Calculate the second derivative.""" d2dt2 = torch.zeros_like(arr) d2dt2[1:-1] = (arr[2:] - 2 * arr[1:-1] + arr[:-2]) / dt**2 d2dt2[0] = d2dt2[1] d2dt2[-1] = d2dt2[-2] return d2dt2
bcdbf2246dca973154a3134efc4b92d666f368a6
86,367
def convert_key_val_tpl(line): """Convert response line from string to key, value tuple :param line: string line from response 'hash_suffix:n_matches' :return: key value tuple ('hash_suffix', int) """ hash, count = line.split(":") return hash, int(count)
48712aea8d395f04827a8c28dd3f073fa36127fa
86,368
def _is_void(name): """Private function for determining if a material name specifies void. """ lname = name.lower() return 'vacuum' in lname or 'void' in lname or 'graveyard' in lname
2431c775003c94ef1f5cc4681ccd704ca03b9d4f
86,369
def disectTheResults(output): """Disect given output line by line. :param output: Text to be disected :type output: string :return: Return of the Python script :rtype: A list of strings where each element represents a line of the total return """ outputs = [item if output ...
75fbbc8d5f06f70c8d695800c1f289df6c2444aa
86,380
def extgcd(a, b): """ 拡張ユークリッド互除法 ax + by = gcd(a,b) の最小整数解 (gcd(a,b), x, y) を返す Args: a (int): b (int): Returns: Tuple[int, int, int] """ u = y = 1 v = x = 0 while a: q = b // a x, u = u, x-q*u y, v = v, y-q*v b, a = a, b-q*a r...
4f6d91fda3e9a8b4b8cdf7e3eaa97dc5bea7b237
86,384
def _to_string(s): """Convert a value into a CSV-safe string.""" if isinstance(s, list): return '[' + ' '.join([str(x) for x in s]) + "]" return str(s)
e3743683e4dc63cc610ca77284981459162b238d
86,386
def scale_time_inverse(time_array, tscale): """ Apply inverse scaling to a given scaled time array from [0,1] to [0,T] Input:: time_array: numpy time array tscale: Scaling factor to use Output:: unscaled numpy time array """ return time_array*tscale
c10098d3dee70f693d58d798108bf8b6198a3239
86,388
def unparse_cpe23(parsed): """ Join back the components into a CPE 2.3 name. :param parsed: Components parsed by parse_cpe(). :type parsed: list(str) :returns: CPE 2.3 name. :rtype: str """ return "cpe:2.3:" + ":".join(x.replace(":", r"\:") for x in parsed)
11fa6007cfa0b7576f83733c16726929ec7fd8bd
86,390
def p_word_given_topic(topic_word_counts, topic_counts, word, topic, W, beta=0.1): """the fraction of words assigned to topic that equal word (plus some smoothing)""" return ((topic_word_counts...
f675ebe996d4775a0e80eda072c28dc5cabce095
86,394
def get_drama_day_url(drama_name): """Return a “Drama Day” URL (`http`-converted from `https` for `cfscrape` compatiblity), given an english K-Drama name (space-delimited e.g.: “A Piece of Your Mind”). Sample return value: 'http://dramaday.net/a-piece-of-your-mind' """ base_url = 'http://dramad...
247829b05bd5b73502e1e6e505fb9744a315fd78
86,396
def build_parameters(request_args, origin_latitude=None, origin_longitude=None, radius=None, start_latitude=None, start_longitude=None, end_latitude=None, end_longitude=None, start_year=None, end_year=None, threshold=None, cq=True): ...
875c4e1020a597826d787fc93779a9afbb2f5cff
86,407
def plot_scatter(ax, photon_events, pointsize=1, **kwargs): """Make a scatterplot This is effcient when there are a low RIXS intensity Parameters ---------- ax : matplotlib axes object axes for plotting on photon_events : array two column x, y, Iph photon locations and intensiti...
f47e28c2515ee4294210f98036c9ae21a8e3e091
86,409
def process_wine_data(data): """Returns features and target of wine data.""" features = data.loc[:, "fixed acidity":"alcohol"].as_matrix() target = data.loc[:, "quality"].as_matrix() return features, target
bd51ace20c89ff8827255facadd993dfa470c64c
86,410
def mass_gas_engine(max_power): """ Estimates the mass of a small piston-driven motor. Source: https://docs.google.com/spreadsheets/d/103VPDwbQ5PfIE3oQl4CXxM5AP6Ueha-zbw7urElkQBM/edit#gid=0 :param max_power: Maximum power output [W] :return: Estimated motor mass [kg] """ max_power_hp = max_p...
4b4cc22ea73061da74519fe8ca137d5598d84ade
86,412
def _get_keywords_with_score(extracted_lemmas, lemma_to_word): """ :param extracted_lemmas:list of tuples :param lemma_to_word: dict of {lemma:list of words} :return: dict of {keyword:score} """ keywords = {} for score, lemma in extracted_lemmas: keyword_list = lemma_to_word[lemma] ...
1713eb85c92b20b0498d299e8c928b16dd79dccd
86,413
def find_shape(dic): """ Find the shape (tuple) of data in a NMRPipe file from parameters. 1-tuple is returned for 1D data, 2-tuple for 2D and non-stream 3D/4D data, 3-tuple or 4-tuple for stream 3D/4D data. The last dimension of the tuple is length of the data in the file, the actual length o...
7a43e9a2caa2cf989e6d09ec978562c9740301f0
86,416
def auth_domain(request): """Return the value of the h.auth_domain config settings. Falls back on returning request.domain if h.auth_domain isn't set. """ return request.registry.settings.get('h.auth_domain', request.domain)
41db967e91100a9dfb473fabdc4aa5ea40b06bd5
86,425
def sortedDictValues(inputDict, reverse=False): """ Returns the given dictionary as a list of keys sorted deterministically by value then key:: {"spam": 0, "eggs": 1, "ham": 1} => ["spam", "eggs", "ham"] :param dict inputDict: :param bool reverse: Reversed sorting :rtype: list """ ...
50581e6e66094795ed1a8842e2492fe8c06f19a2
86,432
def _ConvertPercentToAbsolute(total_value, percent): """Given total value and a 100-based percentage, returns the actual value.""" return percent / 100 * total_value
0ce031053e047d8aaa8afd8033e80ceb7eecdc85
86,436
import typing import glob def find_requirement_files() -> typing.List[str]: """Find all requirements.txt files.""" return glob.glob('**/*requirements.txt', recursive=True)
b9a4729617049ad8ba53152fffd9368024f71203
86,438
def vowel_indices(word): """ Find the index of the vowels in a given word, Vowels in this context refers to: a e i o u y (including upper case) This is indexed from [1..n] (not zero indexed!) Some examples: Mmmm => [] Super => [2,4] Apple => [1,5] YoMama -> [1,2,4,6] """ new...
dbdcb324e7ef5f3191bb81684f0a382ef27d8dbb
86,450
def normalize_query(query): """ Perform query normalization. At the moment, this is simply downcasing and stripping whitespace from the ends. Extend this as needed. Args: query (str): A query string Returns: A normalized query string """ return query.lower().strip()
87b18dcbbcf0be293a6b8c2de9f9c161c2197bd1
86,456
from typing import Any import logging def validate_field(field: str, value: Any) -> Any: """Type checks a given config field. Compare a field value's type with the expected type for that field. Return the value if the type matches, otherwise return the default value for that field. Args: ...
ca0ccd73fa162861d2035c37a68f80f0c5ab901f
86,464
def yatch(dice): """ Score the dice based on rules for YACHT. """ points = 0 if dice.count(dice[0]) == len(dice): points = 50 return points
2606336c162f97d5c0a6a53ae905cf410395de03
86,466
def logistic_equation(_, x, k, g): """ ode for the logistic equation :param _: place holder for time, not used :param x: x value :param k: slope of logistic equation :param g: upper bound of logistic equation :return: slope dx/dt """ dx = k * x * (g - x) return dx
d6b1e5994e51a5e26b07420328458d91fdf2de20
86,467
def populate_usr_pref_dict(user_pref_lst : list, shows : list): """ Pass in list of user preferences [show, rating] and list of shows. Return dictionary with show as key and rating as value and list of shows not found. """ dictionary = {} not_found = [] for row in user_pref_lst: if row[0] i...
b82f8dee097ab817dff14b5f5cd665ccb0033449
86,474
def filter_no_leads(df): """ Objective: Filter out sitegeos where there are no leads :param df: Dataframe with all sitegeos :return: Dataframe with sitegeos having at least one lead """ # Group by sitegeo, count brands __df_grouped = df.groupby(by='sitegeo', as_index=False).leads.sum() ...
b6a0cfe2fd414dd341ba8e14e660c3728ccdba34
86,475
def get_corr_mask(corr, corr_thresh=0.8): """ Mask the numbers below threshold in the corrlation matrix as 0. Parameters ---------- corr: pandas dataframe of shape = [n_features, n_features] corr_thresh: float, default=0.8 The correlation threshold above which a feature will be deemed c...
1c7abc6ae6294e63aefc5bc0073be3bc603ebe21
86,482
def isnamedtuple(x): """ Utility to check whether something is a named tuple Since a namedtuple is basically a tuple with some additional metadata, we can't just do an `isinstance` check Based on https://stackoverflow.com/questions/2166818/how-to-check-if-an-object-is-an-instance-of-a-namedtuple/2166841...
7ca9bdcd264cf1d4fdae01f9a8cc0f2ff4d9dd32
86,483
def _parse_tool_line(line: str) -> str: """ Return ``True`` if this line contains a tool preamble of the format we add in the converter scripts. >>> _parse_tool_line("# ALIGNMENT TOOL cross_match") 'cross_match' >>> _parse_tool_line("# Something else") '' """ if line.strip().upper()...
dd169f3e88d2621e358197363d787890f2c4c038
86,485
def get_symbol_name(result): """Returns the name used by this symbol based on availability""" if 'longName' in result: return result['longName'] elif 'shortName' in result: return result['shortName'] else: return result['symbol']
a45ef6c8feac4cef73470f3b7576e6fc97428cb3
86,487
import math def Lattice_Theory_Algebraic(N,Kappa,d) : """ Approximate expression for the algebraic connectivity of a periodic random geometric graph. This formula is presented in chapter 4 of: Nyberg, Amy. The Laplacian Spectra of Random Geometric Graphs. Diss. 2014. (Also see Van Mieghem, Piet. Graph sp...
26e53f24b4fc45d05b601fd070ab47891c4f64d2
86,488
def num(s): """ Return input string as int or float if possible, otherwise return string. """ try: return int(s) except ValueError: try: return float(s) except ValueError: return s
c3367e8f109f31cfac90842366ac200f724ab0c5
86,489
import random def _generate_random_float_scalar() -> float: """Generate a random float scalar. Returns: float: a random value within the range [0, 1) """ return random.random()
20d5f332dd91f66cec881e440e71603596cdeaeb
86,490
def check_ambiguity(grammar, root, n_max=6): """ Check if the grammar produces ambiguous (repeated) objects Args: grammar (dict): Grammar to check root: Grammar root object n_max (int): Max object size to check Returns: bool: Check result """ for n in range(n_ma...
4d5beedb618b7e34af024c83e7c95136ab65fc87
86,502
def _stride_arr(stride): """Map a stride scalar to the stride array for tf.nn.conv2d.""" return [1, stride, stride, 1]
2cfc75f58dddd1ce7234d97ef7a8707d8bf1b17e
86,504
import math def next_pow2(i): """ Find the next power of two >>> int(next_pow2(5)) 8 >>> int(next_pow2(250)) 256 """ # do not use NumPy here, math is much faster for single values exponent = math.ceil(math.log(i) / math.log(2)) # the value: int(math.pow(2, exponent)) retur...
fd1eb2d4dd75c89ef39af3ea9cecf095d667a32f
86,506
def dominates(one, other): """Return true if each objective of *one* is not strictly worse than the corresponding objective of *other* and at least one objective is strictly better. """ not_equal = False for self_wvalue, other_wvalue in zip(one, other): if self_wvalue > other_wvalue: ...
6ea320c8bfd929adab58093241213c9a3cfc78ef
86,510
def polygonArrayToOSMstructure(polygon): """ polygonArrayToOSMstructure(polygon) With a polygon array gets structure of poly for OSM sql. Parameters ---------- polygon : Array Array that contains the poligon separated [[lat,long], [lat', long'], [lat'', long''], ...] same as [...
61c3debcf4b8ff47eca574fd1bb94a0cde52dbf5
86,512
def nested_to_flat(nested_output): """ Convenience function for comparing two results dictionary. Used in many built-in tests (before passing both dicts to check_common_outputs). Arguments: nested_output: dict, API response """ base = { 'run_uuid': nested_output['Scenario']['run...
44e4d03488657be34fdbf6c027b0d34b6322d79b
86,514
def chan_default(_printer, _ast): """Prints the default channel.""" return f'default'
b0950e765815af232a5a762229248e02e3da9f0e
86,518
def gram_matrices(features, normalize=True): """Calculate gram matrices (approximation of covariance matrix) for image features Args: features (tensor): shape NxCxHxW -- represents a batch of image features normalize (bool, optional): Whether or not to normalize the gram matrix. Defaults to Tru...
d157be848c63f4976524301537065e3e8f32e170
86,519
def poreVolume(G, rock): """ Compute pore volumes of individual cells in grid. Synopsis: pv = poreVolume(G, rock) Arguments: G (Grid): Grid data structure. Must have attribute `G.cells.volumes`. rock (Rock): Rock data structure. Must contain valid fie...
7d0f3b906039776bc08913d89e3290cf004d20ef
86,523
import time def now_timestamp() -> int: """Now timestamp (Second)""" return int(time.time())
da25ab632de774876ace42980c9209e198b9d1dc
86,524
def osminor(dev): """Return the device minor number from a raw device number. This is a replacement for os.minor working around the issue that Python's os.minor still has the old definition. See Ganeti issue 1058 for more details. """ return (dev & 0xff) | ((dev >> 12) & ~0xff)
3d67d3dd61e5f5207555e0c4ef522479d00df3f3
86,525
import re def parse_elapsed_times(qstat_output): """ Read the "%H:%M:%S" strings from the last column of a `qstat` table. Return a list of parsed times, as 3-element lists. @returns Listof(List(Hour, Min, Sec)) Hour = Min = Sec = Natural number """ elaps = [] for ln in qstat_output: ...
4474fb5b0ce7f1df9ec9c273918dad7722925c77
86,526
def _rename(name: str) -> str: """Rename attributes following the specification for the JSON file. Basically pascal case with known acronyms such as BIDS fully capitalized. """ return "".join( word.upper() if word == "bids" else word.capitalize() for word in name.split("_") )
417297d9b19a3e6416f9c791bbffb873e760107d
86,528
def str2tuple(idx_str): """ Convert a miller index string to a tuple. Arguments --------- idx_str: str String for miller index such as "1,1,1" Returns ------- tuple Returns integer tuple such as (1,1,1) """ idx = [] temp_idx = "" for ch...
970a2495676f2e22bd669573a4c4683abae97884
86,536
from typing import Optional def get_growth_rate(doubling_time: Optional[float]) -> float: """Calculates average daily growth rate from doubling time.""" if doubling_time is None or doubling_time == 0.0: return 0.0 return (2.0 ** (1.0 / doubling_time) - 1.0)
8917f05fc59c2e17c26390dbe2abd9bf6f999c94
86,539
def get_superlocus_bounds(superloci): """Get the most 5' and 3' boundaries of a superlocus.""" start = min(locus.min_start for super in superloci for locus in super) stop = max(locus.max_stop for super in superloci for locus in super) return start, stop
6ce604e363ea404c977e1ffd8249d5543f3a6d2e
86,540
from typing import Iterable def seq2str(sequence: Iterable) -> str: """ Converts an Iterable to string of its comma separated elements. """ return ", ".join(str(item) for item in sequence)
08b7251c68f6c068759b614ba104dfa43fb02c51
86,548
def percentage(numerator: float, denominator: float) -> float: """Calculate a percentage Args: numerator (float): The top of the fraction denominator (float): The bottom of the fraction Returns: float: The numerator as a percentage of the denominator """ return (numerator ...
4ca5030f6bff18ae82fd4b73dbeae6345744c2fb
86,551
def get_bookinfo_from_xpath(htmltree, xpath, special_characters = ["\n", "\t", ",", "'", "-", ":", ";", "(", ")", ".", "?", '\r']): """ Returns information about the book's webpage using an htmltree, and an xpath to select the approriate web elemen. Removes any weird character from the obtained data. ...
5abe30b5a079684bdb4fc5019f9d943890a1541c
86,554
def get_cylinder_radius(cell_geometry): """Return the radius the cylinder should have The cylinder have the same radius as the half-sphere that make the dots (the hidden and the shown part of the dots). The radius is such that the spherical cap with diameter cell_geometry.dot_diameter has a height ...
9d52f5c50e1e0690eab48313cf441e5e01fe2b7a
86,559
def _get_added_comment_id(src): """Returns comment ID from given request.""" if not src: return None actions = src.get('actions') or {} related = actions.get('add_related') or [] if not related: return None related_obj = related[0] if related_obj.get('type') != 'Comment': return None re...
65fcccaf63c64add42de7c26053d7b537f7d661a
86,564
def _escape_dn_value(val): """Escape special characters in RFC4514 Distinguished Name value.""" if not val: return "" # See https://tools.ietf.org/html/rfc4514#section-2.4 val = val.replace("\\", "\\\\") val = val.replace('"', '\\"') val = val.replace("+", "\\+") val = val.replace("...
a41bffd855b02c05168c140811290a70c905edbd
86,573
def compute_roc_auc(xs, ys, positiveYValue): """ Compute area under the receiver operating curve... INPUTS: xs : predicted floating point values for each sample ys : truth for each sample positiveYValue : y value to treat as positive OUTPUT: computed AUC """ def trapezoid...
d6bb90538a36ad2455d577f7d4af5285efadfb90
86,579
def bool_to_string(b): """Convert a boolean type to string. Args: b (bool): A Boolean. Raises: TypeError Returns: str: String representation of a bool type. """ s = str(b).lower() if s in ["true", "false"]: return s raise TypeError("Value must be True o...
586cd8312ba071982bf7db407d568181796e8e8e
86,586
import csv def get_depts_mapping(csv_filename): """ Parameters: csv_filename (string): filepath of the campus csv, the csv lists a table of three columns: ID, Dept_code and Department. 1,ACT,"Actuarial Science" 2,ANT,"Anthropology" Returns: A dictionary with Department code as ...
d987a75e76b8ee97359d62c3f6bb2e5ab951bee9
86,587
def get_worksheet_data(sheet, headers): """Get the data of a worksheet. Args: sheet (Worksheet): An openpyx; Excel file object. headres (list): A list of headers to map the values. Returns: list(dict): A list of dictionaries. """ data = [] for row in sheet.iter_rows(min_r...
c7fc6e75d2a948947d45e650339a32c3abc0707c
86,589
import torch def _normalize_prediction(prediction): """ Normalize the predicted SOD probability map. :param prediction: Model prediction. :return: Prediction normalized. """ maximum = torch.max(prediction) minimum = torch.min(prediction) prediction_normalized = (prediction - minimum) /...
ae258cf6aab98f74111d2011db94b929c9f4037b
86,595
def _get_resource_tag( resource_type, tag, runtime, chip, resource_id=None, ): """ Get resource tag by resource type. IMPORTANT: resource_id is optional to enable calling this method before the training resource has been created resource_tag will be incomplete (missing r...
1e0d787fe5b185ccbb624ae6989689ddc3bb58a5
86,599
def is_numeric(text): """Validate whether the string represents a number (including unicode)""" try: float(text) return True except ValueError: return False
d98c76902bb364be0e982a37b5dccf6f091cebe0
86,604
def farenheit2rankine(F): """ Convert Farenheit to Rankine :param F: Temperature in Fahrenheit :return: Temperature in Rankine """ return F + 459.67
cc2e0eb74b4a3ef50222893efc0e5dc9c8f01e71
86,607
def find_used_entities_in_string(query, columns, tables): """Heuristically finds schema entities included in a SQL query.""" used_columns = set() used_tables = set() nopunct_query = query.replace('.', ' ').replace('(', ' ').replace(')', ' ') for token in nopunct_query.split(' '): if token.lower() in col...
a50a9f756bc269782a4bf8969ff4401b4f77899f
86,609
def _TransformCluster(resource): """Get Cluster ID from backup name.""" # backup name is in the format of: # projects/{}/instances/{}/clusters/{}/backups/{} backup_name = resource.get('name') results = backup_name.split('/') cluster_name = results[-3] return cluster_name
a6b7a8250da036c4252823da2fd2d5d25fae96df
86,610
import importlib import inspect def import_class(module_name, cls_name): """ Imports a class dynamically :param str module_name: Module, e.g. 'images', 'metadata' :param str cls_name: Class name :return loaded class cls :raises ImportError: If class can't be loaded """ full_module_na...
696f1dc480b1381ebad67e335abd1620d7bb1dc5
86,611
def adjust(text, run_in_function=False): """Adjust a code sample to remove leading whitespace.""" lines = text.split('\n') if len(lines) == 1: return text if lines[0].strip() == '': lines = lines[1:] first_line = lines[0].lstrip() n_spaces = len(lines[0]) - len(first_line) ...
410100b8027a41591057030e2a2765915662fd14
86,613
def get_rule_short_description(tool_name, rule_id, test_name, issue_dict): """ Constructs a short description for the rule :param tool_name: :param rule_id: :param test_name: :param issue_dict: :return: """ if issue_dict.get("short_description"): return issue_dict.get("short...
d6521ee928a193a0002625522f5e8d279c4d39a8
86,615
def link_repo_name_url(name, url, target="_blank"): """ concat repo name and url in hyperlink """ return f"<a target='{target}' href='{url}'>{name}</a>"
a49bbe753f5143641b42e853f5ad27a467eb3f96
86,616
def concat(k, N): """Concat N multiples of k.""" arr = [str(k*n) for n in range(1, N+1)] s = "".join(arr) return int(s)
1092a04806f548c3cef0ee97033ae5e50415a485
86,619
def _serialize_custom_object(obj): """Serialize a user-defined object to JSON. This function gets called when `json.dumps` cannot serialize an object and returns a serializable dictionary containing enough metadata to recontrust the original object. Parameters ---------- obj: Object ...
6ce62f1636129c5198073f80668e3224fb500885
86,624