content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def validate_number(value_if_allowed):
"""
Validation method used by Tkinter. Accepts empty and float-coercable
strings.
Params:
value_if_allowed
Value to validate.
Returns:
True if value_if_allowed is empty, or can be interpreted as a float.
"""
if value_if_all... | a02df07cb8957049058bd4ac7bfc0bf85a6f543f | 578,648 |
from typing import Optional
from pathlib import Path
def get_icon_path(num_sides: Optional[int]) -> str:
"""
Get the path to the icon for a die with num_sides sides.
Args:
num_sides (Optional[int]): Number of sides on the die or None for the overall total.
Returns:
str: The path to t... | 9eb235ef02bfc8a3e4fa05069fda86b507eb4c73 | 578,649 |
import torch
def is_perpendicular(
pt1: torch.Tensor, # N x 2
pt2: torch.Tensor, # N x 2
pt3: torch.Tensor, # N x 2
tol: float = 1e-1,
) -> torch.Tensor:
"""Checks if the two vectors (pt1 - pt2) amd (pt1 - pt3)
are perpendicular to each other.
"""
vec1 = pt1 - pt2 # N x 2
vec1 ... | a409bdd9dfb20cfb2e3975d383c099d95e7b11a9 | 578,651 |
def current(new, old):
"""Return whether a new timestamp is up-to-date with
respect to an old timestamp.
"""
return not old is None and new <= old | 534087cd21b6b22555289547c27590fb464902ee | 578,657 |
import math
def distance_between_points(a, b):
"""
Return the Euclidean distance between two points
:param a: first point
:param b: second point
:return: Euclidean distance between a and b
"""
distance = sum(map(lambda a_b: (a_b[0] - a_b[1]) ** 2, zip(a, b)))
return math.sqrt(distance... | 19e46b3c7a5e91a0c5fdd73bba8bf305d9f08bfc | 578,661 |
import ast
def _scope_helper(node):
"""Get the closure of nodes that could begin a scope at this point.
For instance, when encountering a `(` when parsing a BinOp node, this could
indicate that the BinOp itself is parenthesized OR that the BinOp's left node
could be parenthesized.
E.g.: (a + b * c) or ... | 909efb6dcbedfef97a8c955f97df8e67438cd979 | 578,665 |
def DropWikiSuffix(wiki_filename):
"""Removes the .wiki suffix (if any) from the given filename."""
return (wiki_filename[:-len('.wiki')] if wiki_filename.endswith('.wiki')
else wiki_filename) | 96ec5a3c81ee31c5a6c7f049ec83b5e3c9d4f1b8 | 578,667 |
def split_phylogeny(p, level="s"):
"""
Return either the full or truncated version of a QIIME-formatted taxonomy string.
:type p: str
:param p: A QIIME-formatted taxonomy string: k__Foo; p__Bar; ...
:type level: str
:param level: The different level of identification are kingdom (k), phylum (p... | b61d5cafa1ca7f56c37195c619e8f02f9b925dab | 578,669 |
def record_version(obj):
"""Return record's version."""
field_data = obj.get("metadata", {}).get("version")
if not field_data:
return f"v{obj['versions']['index']}"
return field_data | 5053a6071d3c2a2dbcd749ff30f4be705eebc701 | 578,670 |
def calc_node_idx(point_idx: int, configuration: int) -> int:
"""
Calculates a unique node index.
:param point_idx: Index of the point that the node belongs to within the trajectory.
:param configuration: Robot configuration for the node
:return: Integer value for the node index
"""
if 0 <= ... | 52bb09b2bec97e069d20c3dc3e9cd9d1de30db89 | 578,671 |
def read_file(file_path):
"""Reads a string from a file"""
with open(file_path, "r") as f_handle:
return f_handle.read() | f7bd3de082d0dc26fc84baf78c94fc261cee71b1 | 578,672 |
def combine_values(d, v):
"""Helper function used in call to .aggregateByKey
Args:
d (dict): python dictionary to be aggregated into
v (tuple): tuple of key, value to be inserted into d
Returns:
dict: updated python dictionary from v
"""
key, value = v
d[key] = value
retu... | ad5919889983f96bf77706c86a06baa9cc5412cf | 578,674 |
def valid_url(url):
"""
Validate a URL and make sure that it has the correct URL syntax.
Args:
url (str): URL string to be evaluated.
Returns:
True if the URL is valid. False if it is invalid.
"""
if "http://" not in url and "https://" not in url:
return False
retu... | 0429e10d207af62799a92bf2b16de4ab39a49a20 | 578,679 |
def inc(x):
"""This is a function that takes a number and increments it by 1 """
return x + 1 | 35e02164c619e2c9509692107a2bdaf2bae8220d | 578,684 |
def scale_unit_to_bounds(seq, bounds):
"""
Scales all elements in seq (unit hypercube) to the box constraints in bounds.
:param seq: the sequence in the unit hypercube to scale
:type seq: iterable
:param bounds: bounds to scale to
:type seq: iterable of [lb, ub] pairs
:returns: a list of sc... | 31621e3ec957fbf50c60c6f0ddb0ec59277b7803 | 578,691 |
def readable_size(n):
"""Return a readable size string."""
sizes = ['K', 'M', 'G']
fmt = ''
size = n
for i, s in enumerate(sizes):
nn = n / (1000 ** (i + 1))
if nn >= 1:
size = nn
fmt = sizes[i]
else:
break
return '%.2f%s' % (size, fmt) | 2fa7b2791ef38e2566b2b9e5bc5089e73bd8d7ef | 578,695 |
import typing
def _num_columns(table: typing.Sequence[typing.Sequence[typing.Any]]) -> int:
"""
Returns the number of columns of the table.
Will raise a ValueError if the table is uneven.
"""
num_colums_set = set(len(r) for r in table)
if len(num_colums_set) != 1:
raise ValueError(f'No... | c71a3b1c96262ea15e383eac59986e93c8ea46d7 | 578,697 |
def bold(text: str) -> str:
"""Wrap input string in HTML bold tag."""
return f'<b>{text}</b>' | fc8d62032c1906f0dce8edd00a3a38de42173233 | 578,701 |
def PMH(machine, laborCost, laborU):
"""
machine = machine cost per hourly
laborCost = labor cost
laborU = labor utilization rate
"""
return machine + (laborCost * laborU) | bfa71646dbc429456c14599a346c4f8485411fb8 | 578,703 |
def to_hex(number, width):
"""Convert number to hex value with specified width. Will be padded by zero
to fill the width.
"""
format_string = '{{0:0{0}X}}'.format(width)
return format_string.format(number) | 3c8659051ec5ea9dd162d037aa8eb76cc2501fbc | 578,710 |
import re
def remove_numeric_digits(text: str) -> str:
"""Remove numeric characters using regex
Parameters
----------
text : string
A string containing numeric digits
Returns
-------
string
A string analogous to the input, but without numeric digits,
removed u... | e6dcaf9b5c78c9f395044214ff805af5a1d1a917 | 578,712 |
def _h3_col(h3_lvl):
"""Make it easy and reporducable to create a h3 column"""
return f'h3_{h3_lvl:02d}' | 46463bc3ce0edac3e392dacba0cadfe940577ce3 | 578,714 |
def modify_query(query, modifiers):
"""Modify query according to the modifiers.
:param sqlalchemy.orm.query.Query query: query to be modified
:param dict modifiers: dict of modifiers and their values
:return sqlalchemy.orm.query.Query: modified query
"""
if modifiers is None:
return que... | 56f4024e0402bc5be3cecef16a7eef2ae6f0e98b | 578,717 |
from typing import Iterable
def decimalify_leading(char_set: Iterable[str], text: str) -> str:
"""Replace first character with decimal representation if it's included in
`char_set`."""
if not char_set or not text:
return text
first_char = text[0]
if first_char in char_set:
return f... | 50d9a7bd9f36d7305a63a5fe1bfad9311813abe3 | 578,729 |
def test_tree_inorder_postorder() -> list:
"""Return tree data for building a test tree for inorder & postorder traversals."""
return [
(5, ""),
(6, "4"),
(3, "30"),
(4, "11"),
(2, "7"),
(1, "34"),
] | 559c8361a822d178baeb4bbbb711240cb6ba13cc | 578,730 |
def get_account_idx_for_run_faucet(accounts: int, deploys: int) -> int:
"""Returns run specific faucet account index when dispatching a deploy batch.
:param accounts: Number of accounts within batch.
:param deploys: Number of deploys within batch.
:returns: Ordinal index of account acting as run fa... | f27bf03cd77992146f5b12b652a8430f913fb430 | 578,732 |
import torch
def _compute_translation_matrix(translation):
"""
Computes affine matrix for translation.
"""
matrix = torch.eye(3, device=translation.device, dtype=translation.dtype)
matrix = matrix.repeat(translation.shape[0], 1, 1)
dx, dy = torch.chunk(translation, chunks=2, dim=-1)
... | c95343ee7d4a5cb7c996fea6dc509f21aebdd60f | 578,733 |
import time
def time_it(wrapped):
"""
Decorator to use to get the time it takes to run a function.
"""
def inner(*args, **kwargs):
t = time.time()
ret = wrapped(*args, **kwargs)
func_string = str(wrapped).split()[1]
print('Execution time for function "%s": %s s' % (fun... | 55a932a56135fa3c9785795a988f4ca1d22b1309 | 578,738 |
def _needleman_wunsch_fn(v1, v2):
"""Needleman-Wunsch
Match: +1 -> -1
Mismatch or Indel: −1 -> +1
The values are reversed because our general dynamic programming algorithm
selects the minimal value instead of the maximal value.
"""
d_indel = 1 # gap / indel
if v1 == v2:
d = -1... | 02724f9c371ef24c7a4983d89105415279f6afd3 | 578,740 |
def get_CI_for_t_distribution(xbar, t_critical, s, n):
"""
Get the confidence interval for a t-distribution
Parameters
----------
> xbar: mean of the sample
> t_critical: t-critical value for the distribution
> s: sample standard distribution
> n: size of the sample
Returns
-------
The confidence interval ... | 3536b94e2fe0fbf0c86bdb2137293a2a4a85c0db | 578,742 |
def is_int(val):
"""
Check if value is able to be cast to int.
:param val: String to be tested to int
:return: Boolean, True if success
"""
try:
_ = int(val)
except ValueError:
return False
return True | 19ee61aab7c9320a5cfb44f6fa0845424f5284b3 | 578,745 |
def default_evaluator(model, X_test, y_test):
"""A simple evaluator that takes in a model,
and a test set, and returns the loss.
Args:
model: The model to evaluate.
X_test: The features matrix of the test set.
y_test: The one-hot labels matrix of the test set.
... | 5e30e447b8c4cc0829e0930e21d5895e244ff9a3 | 578,747 |
def eqzip(*args):
"""Zip but raises error if lengths don't match.
Args:
*args: list of lists or tuples
Returns:
list: the result of zip
Raises:
ValueError: when the lengths don't match
"""
sizes = [len(x) for x in args]
if not all([sizes[0] == x for x in sizes]):
raise ValueErr... | a4492487995feced9349874af0c6303fda74ac58 | 578,748 |
import json
def tsv_encode(val, none_string="NULL"):
"""
Encodes a value for inclusion in a TSV. Basically, it converts the value
to a string and escapes TABs and linebreaks.
:Parameters:
val : `mixed`
The value to encode
none_string : str
The string to use wh... | d537a912ede008f07f9344cb3c095f1a272c250a | 578,753 |
import torch
def g_dD(x):
"""Complicated example function defined on interval `[0, 6]`
Parameters
----------
x : torch.Tensor
coordinates for evaluation
Returns
-------
torch.Tensor
function evaluations
"""
result = x[0] * (x[0] - 6) / 9
for x_i in x[1:]:
... | aab61d806545b8b69e5e4cf0240e29c28a438b0a | 578,754 |
import string
def remove_punctuation(input_string):
"""Removes punctuation from the user's input.
Parameters
----------
input_string : string
String that the user inputs into the chatbot
Returns
-------
out_string : string
String with all the punctuation remov... | 89fa7ed25d9a7f539acfed0561a5d2730a47228c | 578,758 |
import random
def generate123(power):
"""
Generates 3 lists that contain a random number of ones, twos and threes
:param power: power of 2
:return: generated lists
"""
lst123 = []
for i in range(3):
experiment = []
for j in range(2 ** power):
experiment.append(r... | c233966a4f925d606f0c915bde69a8b53be7f4c0 | 578,764 |
def bytes_to_utf8(value):
"""
Converts byte literal to utf8 string
:param value: Byte literal
:type value: bytes
:return: UTF-8 encoded string
:rtype: str
"""
return str(value, 'utf8') | 287967b5e44c326501c4c16fa671b781a1c64024 | 578,765 |
def join (lst,sep=" "):
"""Takes a list of objects of arbitrary type, plus an optional separator string. Returns a string in which the 'str'
representations of the objects are joined by the separator, whose default value is just a single space."""
strg = ""
for i,x in enumerate(lst):
if (i > ... | 9d3322de33507a954e68a6aa34f0ea81b00e1bba | 578,766 |
def traverseShortestPath(target):
"""
Traverses backward from target vertex to source vertex, storing all encountered vertex id's
:param target: Vertex() Our target node
:return: A list of all vertexes in the shortest path
"""
vertexes_in_path = []
while target.previous:
vertexes_in... | 10f2e91c1669337c94a6e6812f77c6290e854b33 | 578,768 |
def read_file(filename):
"""
Read input file and save the lines.
:param filename: input file
:return: list of read lines (start and end)
"""
lines = []
with open(filename, 'r', encoding='UTF-8') as file:
for line in file:
start, end = line.strip().split('->')
... | ca45117766014576409580f16adf90e863b5819e | 578,770 |
import base64
def base64_encode(data: bytes) -> bytes:
"""Does a URL-safe base64 encoding without padding."""
return base64.urlsafe_b64encode(data).rstrip(b'=') | 341a6382a655ceb007bdba71e743d6c8656d4f7f | 578,773 |
def seconds_between_datetimes(dt1, dt2):
"""
Return the number of seconds between two datetime objects as an integer, truncating microseconds.
>>> seconds_between_datetimes(datetime(2011, 2, 15, 6, 33, 0), datetime(2011, 2, 15, 6, 33, 30))
30
>>> seconds_between_datetimes(datetime(2011, 2, 15, 6, 3... | b0cbab31500e3f3837161d1e4b553abc931b3c92 | 578,775 |
from typing import Callable
import inspect
def get_required_parameters_number(callable_object: Callable) -> int:
"""
Checks if a callable object has the correct number of required parameters.
.. versionadded:: 0.0.2
A callable object can be a function or a method.
Parameters
----------
... | 23c5ea12751fa105bea662ddaa82104b9a769756 | 578,777 |
import torch
def mesh_grid(h, w, device=torch.device('cpu')):
"""
Creates a mesh grid with normalized pixel values.
"""
assert h == w, "Only support square images for now"
r = torch.arange(0.5, h, 1) / (h / 2) - 1
xx, yy = torch.meshgrid(r, -r)
return xx.to(torch.float32).to(device), yy.to... | 0510102e16cd6c69b1aecb54c88681dfa73be81a | 578,779 |
from typing import Optional
from typing import Union
def prepare_timeout(timeout: Optional[int]) -> Optional[float]:
"""Request timeout is in milliseconds, but `requests` uses seconds"""
output: Optional[Union[int, float]] = timeout
if timeout is not None:
output = timeout / 1000
return output | 64b31825a072fbab8c7112c008d444e1c4abbf41 | 578,783 |
def read_name_file(filename):
"""Read names from a file containing one name per line."""
with open(filename, 'r') as f:
names = f.read()
names = names.split('\n')
names = list(filter(None, names))
return names | 933928dc12a2605e85fca0b10f010f0a575e3692 | 578,784 |
from typing import Any
def items_to_str(*items: Any) -> str:
"""Converts each item to a string and joins them together."""
return "".join(str(item) for item in items) | f187cfc4e4c4a2e1d950a5272d61bd1b6b62938b | 578,785 |
def get_Tanimoto(fp1, fp2):
"""
Calculate Tanimoto score
Parameters
----------------
fp1: bit array
fingerprint 1
fp2: bit array
fingerprint 2
Returns
---------------
return: float
Tanimoto score of fp1 and fp2
"""
one_count = 0
zero_count = 0
... | c3358afb6867a812058eea86c36478d52c5a3178 | 578,787 |
from typing import Union
def color_by_num(num: int, level: bool = False) -> Union[tuple, list]:
"""
@brief Return a color's RGB set of a red by a number.
LEVEL1:(222, 31, 5) > 10000
LEVEL2:(255, 39, 54) 1000 ~ 9999
LEVEL3:(255, 99, 65) 500 ~ 999
LEVEL4:(255, 165, 119... | f52adecf05a0dc8d2c8268f1a3dbee10d8cf2e39 | 578,790 |
import torch
def clamp_scale_function(bounds):
"""
Just clamp to bounds
Args:
bounds (tuple(torch.tensor, torch.tensor)): tuple giving the parameter bounds
"""
return lambda x: torch.clamp(x, bounds[0], bounds[1]) | 0126c27eac611892bb7d548fbc9d688c5eab7445 | 578,796 |
def untokenize(tokens):
"""Return inverse of the Adeft word tokenizer
The inverse is inexact. For simplicity, all white space characters are
replaced with a space. An exact inverse is not necessary for adeft's
purposes.
Parameters
----------
tokens : list of tuple
List of tuples of... | 0abfe331799171d6db35132f35866a878a1c7278 | 578,799 |
def get_chart_error(bands, chart_filter_name):
"""
Helper fn for insert_chart_data().
:param bands: list of band dicts, as extracted from chart json.
:param chart_filter_name: chart-style filter name, as "B" or "Ic" (not "I").
:return: error if found, zero otherwise [float]
"""
chart_error =... | aecff65b1655b445b5d7c69aa71dec2df8686625 | 578,802 |
def lerp(a: float, b: float, t: float) -> float:
"""
Linearly interpolates (unclamped) between a and b with factor t.
Acts such that `lerp(a, b, 0.0)` returns `a`, and `lerp(a, b, 1.0)` returns `b`.
"""
return (1 - t) * a + t * b | 70aadc1e25fd888e41ada5664725755dff74ac87 | 578,807 |
def _standardize_value(value):
"""
Convert value to string to enhance the comparison.
:arg value: Any object type.
:return: str: Converted value.
"""
if isinstance(value, float) and value.is_integer():
# Workaround to avoid erroneous comparison between int and float
# Removes z... | c2c6ec0cbc20ceae2250a8db31106f07a6706336 | 578,809 |
def _start_distance_reg2(dupl1, dupl2):
"""
Returns distance between starts of the regions2.
It is assumed that the duplications are on the same chromosome.
"""
return dupl2.region2.start - dupl1.region2.start if dupl1.strand else dupl1.region2.end - dupl2.region2.end | 6b0377df00dbf764964f147c7f5c3b907000f978 | 578,810 |
import socket
import time
def connect_evaluator(address):
"""
Connects the evaluator to the socket. The garbler will act as
the server, and the evaluator as the client.
:param str address: the address of the socket (IP and the port \
number in the format IP:port)
:return: ... | c5029955a05284c87d85c4db0147ccdc14636d49 | 578,811 |
def _OtherVert(tri, a, b):
"""tri should be a tuple of 3 vertex indices, two of which are a and b.
Return the third index, or None if all vertices are a or b"""
for v in tri:
if v != a and v != b:
return v
return None | dc9514d2e80e3062a6ee58e889ddc4fd4bbc45d6 | 578,813 |
from typing import Optional
import logging
def extract_dataset_config(model_name: str, accuracy_config: dict) -> Optional[dict]:
"""
Find and return a dataset config from a given model config, if exists.
Model config is expected to have "datasets" section,
which is expected to have one entry with... | b60b16adef50ffe63be0b7154247cacfd171ff63 | 578,821 |
import re
def is_itiming_hosted(race_info):
"""
:param race_info: the race metadata to be inspected (RaceInfo)
:return: if the given race is hosted on itiming.com
"""
it_re = re.compile(".*itiming\.com.*")
match = it_re.search(race_info.url)
return match is not None | 624b357bacdcad98a5de64cc80d2e539ab6bfe2c | 578,822 |
def is_numeric(v) -> bool:
"""Returns true if is a numeric type (int or float) or contains numeric elements if this is a tuple
Args:
v ([type]): can be tuple or a primitive type
Returns:
bool: true if v is numeric or in case of a tuple, all of v's members are numeric
"""
if isinsta... | f847a6409288ddcf503f28c44865048a57136793 | 578,823 |
def can_import(module_name):
"""Check if module can be imported.
can_import(module_name) -> module or None.
"""
try:
return __import__(module_name)
except ImportError:
return None | 7a0ce8050a4ef2dec59bbe0a7fda0e4afd9dbafb | 578,827 |
import torch
def ctc_decode(seq: torch.Tensor, blank_idx: int):
"""
Simple ctc decoding without beam search
:param seq: torch tensor with tokens of shape (n_labels, len)
:param blank_idx: index of blank character
:return: torch tensor with ctc decoded tokens
"""
seq = seq.argmax(dim=0)
... | 0139513368870d77c0a3a04b0daa23ef6ac9cabb | 578,828 |
def call_option_function(option, flight):
"""
Call the function associated with the specified option
:param option: Option definiton (dictionary)
:param flight: Current flight object
:raises ValueError: If the callback function requires a flight object and the passed instance is None
:return: E... | e1fc5c1f56a94aefb15ab5051ce849eec511e1ec | 578,832 |
import re
def strip_html(text: str) -> str:
"""Strip HTML tags from the input text.
:param text: HTML to sanitize
:return: sanitized text
"""
return re.sub("<[^>]*>", "", text) | ea41982008bc03672c5739ce9d73a1a9ae830fe0 | 578,840 |
import re
def get_mod_name_from_url(url: str) -> str:
"""Extracts the file name from the url.
Args:
url: url of a downloaded file
Returns:
str: name of the file name
Examples:
>>> FileDownloader._get_mod_name_from_url(("https://files.nexus-cdn.com/110/3863/"
>>> "Sky... | deed275ae3dea14e0d367ae2b0310e8974cfd53a | 578,842 |
def build_response(output):
"""Build JSON Alexa response"""
return {
'version': '1.0',
'sessionAttributes': {},
'response' : {
'outputSpeech': {
'type': 'PlainText',
'text': output
},
'card': {
'type': 'S... | dea37152efa2bf4e3d5b64935d99a8b248048e83 | 578,847 |
import logging
def get_bucket(s3, bucket_name):
"""
Purpose:
Return an S3 Bucket by name
Args:
s3 (S3 Resource Object): S3 Object owning the Bucket
bucket_name (String): Name of bucket to return
Return:
bucket (S3 Bucket Object): Bucket object for the bucket in
... | 0cd2b1136eee929c274ae9689aa023af46d16320 | 578,852 |
from pathlib import Path
def data_path(file_name):
"""Return the full path of a test data file in the test-data directory.
"""
return Path(__file__).parent.parent / "test-data" / file_name | a6f7b4b4510a914df229f5a133e60723fded84c3 | 578,853 |
def __parse_request_range(range_header_text):
""" Return a tuple describing the byte range requested in a GET request
If the range is open ended on the left or right side, then a value of None
will be set.
RFC7233: http://svn.tools.ietf.org/svn/wg/httpbis/specs/rfc7233.html#header.range
Examples:
... | ef44eccb68ed5c929e0600099b0e1f670fd7a6f6 | 578,854 |
import re
def FamilyName(fontname):
"""Attempts to build family name from font name.
For example, HPSimplifiedSans => HP Simplified Sans.
Args:
fontname: The name of a font.
Returns:
The name of the family that should be in this font.
"""
# SomethingUpper => Something Upper
fontname = re.sub('... | 0b1287c976431cfeedbeaa4981e4364764ac911a | 578,858 |
def filter_before(df, date_):
"""Return df excluding rows where index dates are before input date_"""
try:
return df[df.index >= date_]
except (AttributeError, TypeError):
return df | 2c4bfcd95e64e558f977c206e9ebe62d72114783 | 578,861 |
def _get_pkg(pkgs, pkg_name):
"""Returns the package declaration from a list of package declarations.
Args:
pkgs: A `list` of package declarations (`struct`) as created by
`packages.create()`, `packages.pkg_json()` or `spm_pkg()`.
pkg_name: A `string` representing the name of the ... | 5f81bbfd44612342a7548a754cbf95876f3611e0 | 578,862 |
def unstack_and_count(da, dims):
""" Unstacks provided xarray object and returns the total number of elements along dims """
try:
unstacked = da.unstack(da.dims[0])
except ValueError:
unstacked = da
if dims is None:
return ((0 * unstacked) + 1)
else:
return ((0 ... | e60879b140934b67d9684ab3ff71dfe8a9fd31bb | 578,863 |
def dict_filter(posdict, filterset):
"""
Applies a filter on the values of the input dictionary
Values in the dictionary are lists whose elements that aren't present in
the filterset are removed
Parameters
----------
posdict : dictionary of the format returned by search_multiPos_link()
... | c65f77906ffaeb4d4176e8c210445b093908e307 | 578,864 |
def form_dataset_name(code, llx, lly):
"""
Form valid dataset name using OpenTopography bulk raster naming convention
for EarthScope data.
"""
return code + str(llx) + '_' + str(lly) + '.tif' | 809f9c13b0682ce96de412347bfdc3ba72ed7335 | 578,868 |
def format_prio_list(prio_list):
"""Format a list of prios into a string of unique prios with count.
Args:
prio_list (list): a list of PrioEvent objects.
Returns:
The formatted string containing the unique priorities and
their count if they occurred more than once.
"""
prio... | f5605d4a8108f89fc4361fb4d7202b4f92250758 | 578,869 |
def _message_normalizer(exc, no_field_name="_schema"):
"""
Normally `normalize_messages` will exist on `ValidationError` but pre 2.10
versions don't have it
:param exc:
:param no_field_name:
:return:
"""
if isinstance(exc.messages, dict):
if '_schema' in exc.messages:
... | 5800188312e932b7a124f0818f48116ec4042ba5 | 578,871 |
def truncated_discrete_set(value, values):
""" Provides a validator function that returns the value
if it is in the discrete set. Otherwise, it returns the smallest
value that is larger than the value.
:param value: A value to test
:param values: A set of values that are valid
"""
# Force t... | 2ca1026e8bfb008b5b57ea902ac302613748f195 | 578,872 |
def narrow_seat_position(
char: str, lower_char: str, upper_char: str, lower_limit: int, upper_limit: int
) -> tuple[int, int]:
"""Half the range of the seat position ([lower_limit, upper_limit]) given the value of char."""
half_range = (upper_limit - lower_limit + 1) / 2
if char == lower_char:
... | be332a78ac7e6dc2c6d86168723f8098a99e9ec1 | 578,874 |
def pixel_volume_to_cubed_um(pixel_volume, resolution_lateral_um, resolution_axial_um):
"""Convert volume in pixels to volume in cubed microns based on microscope resolution"""
return pixel_volume * (resolution_lateral_um ** 2) * resolution_axial_um | 203a9572729456f86e23e2dc6f400d31cdad288d | 578,878 |
import hashlib
def _sha256sum(input_file):
"""
Return sha256 checksum of file given by path.
"""
hasher = hashlib.sha256()
with open(input_file, "rb") as file:
for chunk in iter(lambda: file.read(65536), b""):
hasher.update(chunk)
return hasher.hexdigest() | 9e7f9655646e82e219798b1648e11039d072bde7 | 578,881 |
import typing
def _get_aws_api_list_endpoints_dict() -> typing.Dict[str, str]:
"""Store AWS API endpoints to list each asset type"""
return {
"users": "list_users",
"groups": "list_groups",
"roles": "list_roles"
} | cd87d856b26ff11353b83cc7c6afa047514b14e9 | 578,883 |
import functools
def cache(fn):
"""Decorator to cache inputs to functions"""
_cache = []
_results = []
@functools.wraps(fn)
def func(*args):
"""
:returns result of function if input was cached,
else it calls fn and returns the result
"""
if len(_cache) > 10... | 4e8f931d7d4e380b5ccd5f52a08556fb538626f8 | 578,888 |
import six
def inclusion_unlimited_args_from_template(one, two='hi', *args):
"""Expected inclusion_unlimited_args_from_template __doc__"""
return {
"result": (
"inclusion_unlimited_args_from_template - Expected result: %s" % (
', '.join(six.text_type(arg) for arg in [one, t... | 838e740fe1fe0f788e2d8e17ad245e97fe1bac3b | 578,889 |
def kelvin2farenheit(K):
"""
Convert Kelvin to Fahrenheit
:param K: Temperature in Kelvin
:return: Temperature in Fahrenheit
"""
return 9.0 / 5.0 * K - 459.67 | 99d82557a05b34db514743c9206c9fb3b6612ffb | 578,891 |
import itertools
def concat(*seqs):
"""
Concatenates zero or more iterables into a single iterable.
Examples:
>>> list(concat([1, 2], [3, 4], [[5], [6]]))
[1, 2, 3, 4, [5], [6]]
Args:
*seqs (Iterable): Iterables to concatenate.
Yields:
Each element from all itera... | b6f1a7d031ebb28b433ae59aaa2fed86ed50ff21 | 578,895 |
import zlib
def flate_encode(stream: bytes) -> bytes:
"""Function that encodes a bytes stream using the zlib.compress method.
Args:
stream (bytes): stream to be encoded.
Returns:
bytes: the encoded stream.
"""
return zlib.compress(stream) | cb13a9fca84119b19366ee3d898b003cc61b156f | 578,902 |
def expand_indent(line):
"""
Return the amount of indentation.
Tabs are expanded to the next multiple of 8.
>>> expand_indent(' ')
4
>>> expand_indent('\\t')
8
>>> expand_indent(' \\t')
8
>>> expand_indent(' \\t')
8
>>> expand_indent(' \\t')
16
... | 79addc10c91b58d1f83e373971ee62b691c56c15 | 578,903 |
def evaluate_precision(tp: int, fp: int) -> float:
"""Precision, aka Positive Predictive Value (PPV).
$PPV=\dfrac{TP}{TP + FP}$
Args:
tp: True Positives
fp: False Positives
"""
try:
return tp / (tp + fp)
except ZeroDivisionError:
return 0.0 | 5c591113833fffbb95cf1f638c76fa1c4e28044f | 578,904 |
def __create_group_list(n):
"""
Helper method for conversion
Takes binary number and converts to a list of
grouped binary values
Process:
1. convert number to a list of chars
2. reverse the list
3. iterate through the list creating groups of 4
removing each value... | b84678abd96446f2777d7a032db43386bc06708f | 578,907 |
def get_start_index_from_alignment_start_string(target_alignment_string) -> int:
"""Get the alignment start index from the given alignment string.
We know that the alignment strings will always start with spaces until
the region that actually aligns to the reference, so we count the number
of spaces in... | fa8992c4b249427b7cc016958f9746bebe658045 | 578,908 |
def _formatter_self(name, value):
"""Format the "self" variable and value on instance methods.
"""
__mname = value.__module__
if __mname != '__main__':
return '%s = <%s.%s object at 0x%x>' % (name, __mname, value.__class__.__name__, id(value))
else:
return '%s = <%s object at 0x%x>' ... | 5ab8794f01ddcfccb38b704150ff6a430618bbaa | 578,910 |
def policy_threshold(threshold, belief, loc):
"""
chooses whether to switch side based on whether the belief
on the current site drops below the threshold
Args:
threshold (float): the threshold of belief on the current site,
when the belief is lower than the threshold, switch si... | 1686b1ff07d75e634b81b8d3a0801f03592f7b79 | 578,915 |
import base64
def hex_to_b64(hex_input: bytes) -> bytes:
"""Encode an hex byte string to base64.
Don't worry, the first version implemented this in C. :)
:param hex_input: The hex byte string to be encoded.
:returns: The base64 encode of the string.
"""
assert hex_input
return base64.b64... | a8f27e89ee9335b12711042d1f53d1083117d4d9 | 578,916 |
def partial_fractions(p, q):
""" Finds the partial fraction representation of the rational
function 'p' / 'q' where 'q' is assumed to not have any repeated
roots. 'p' and 'q' are both assumed to be numpy poly1d objects.
Returns two arrays. One containing the coefficients for
each term in the partial... | 1b57a48b8eb73b983c8c01a8e2f34c5eb269cd25 | 578,917 |
import torch
def _broadcast_if_scalar(x):
"""Return kwargs enabling broadcasting if 'x' is a scalar."""
if isinstance(x, torch._C.Node):
return {}
else:
return {"broadcast_i": 1} | 146c226743a3afea66a4fbd533f6e36a354004a7 | 578,920 |
def _get_filehash(filepath, hasher_factory, chunk_size, cache=None):
"""Compute the hash for given filepath.
# Arguments
filepath (str): Path to the file to hash.
hasher_factory (f: f() -> hashlib._hashlib.HASH): Callable that returns an
instance of the `hashlib._hashlib.HASH` inter... | ecc5cad9246ae92543a76cfc80dbdfef4dd44648 | 578,926 |
def count_records(df, cols, new_count_col_name):
"""
Count the number of unique records in group in a dataframe.
Args:
df (panda.DataFrame) : dataframe you would like to groupby and count.
cols (iterable) : list of columns to group and count by.
new_count_col_name (string) : the nam... | fd7a94d36bf3ca647c475d8b281b7add29c819a0 | 578,932 |
import struct
def get_origsize(fpath):
"""Get original file size of a file."""
with open(fpath, 'rb') as infile:
return struct.unpack('<Q', infile.read(struct.calcsize('Q')))[0] | f9b84c950f88986e16dc656612cbc33ab5c7b090 | 578,936 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.