content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
from typing import List
from typing import Any
def data_is_2D(rows: List[List[Any]]) -> bool:
"""Ensure data is in a 2D format (List of Lists).
:param rows: 2D list containing objects that have a single-line representation (via `str`).
All rows must be of the same length.
:return: Boolean value indic... | 052ad581cbb82e6d8f805594d82b36bdf8e1dba1 | 603,988 |
def std_url(url):
"""
Standardizes urls by removing protocoll and final slash.
"""
if url:
url = url.split("//")[-1]
if url.endswith("/"):
url = url[:len(url)-1]
return url | 4940052d2feebd92f9cb54e7cee57318445f86c2 | 603,993 |
def get_latest_analysis_inputs(files):
"""Get input files for the latest analysis version number of each chip_well_barcode."""
latest_analysis_inputs = []
for chip_name, chip_well_barcode in files.items():
for barcode, versions in chip_well_barcode.items():
latest_version = sorted(versio... | cfd27b643e62a5e2007ad80068da87b289affe18 | 603,996 |
def process_string(instring, year, month, day):
"""
Process a string replacing placeholder occurrences of YYYY with year, MMMM with month and DDDD with day.
:param instring: string to be converted
:param year: year to replace in input string
:param month: month to replace in input string
:param... | da36f1c87c47e30f858f2e4115a5d884736bb656 | 603,997 |
import json
def gps_to_json(positions):
"""
Transform GPS data to web format (time data to seconds since epoch)
:param positions: position data received from bbgps
:return: json data to return on request
"""
data = []
for position in positions:
aux = position.copy()
aux["ti... | 7c8d31493b8fdc40fe33352f78016181308e8558 | 603,998 |
def round_described(described, decimals):
""" For printing purposes the results should be rounded.
This is done with this function and the desired number of
decimals are passed per parameter as an argument.
Parameters
----------
described : DataFrame
The DataFrame you want to print
... | 87db2a4c29514af423686e1f3acf24ab14eb95ef | 603,999 |
def safe_add(x, y):
"""
Adds two values which are either numeric types or None.
- If both values are numeric, the result is the sum of those values.
- If only one numeric value is provided, that value is returned.
- If both values are None, then None is returned.
"""
if x is not None and y ... | 26965be2b64c438f2662b2b06059f660f94bf255 | 604,001 |
def get_attribute_name(attribute):
"""
Return the attribute name from the attribute definition
:param attribute: The attribute definition
:return: The attribute's name
"""
splitted_attribute = attribute.split(' ', 2)
return splitted_attribute[0] | 5850b62783525d5ebb80ef9f5213f9a191749228 | 604,006 |
def get_fully_qualified_fuzzer_name(context):
"""Get the fully qualified fuzzer name."""
if context.fuzz_target:
return context.fuzz_target.fully_qualified_name()
return context.fuzzer_name | d3869b52af4d40115b866c7bc2c89486eb54f06d | 604,009 |
import inspect
import torch
def apply_chunking_to_forward(forward_fn, chunk_size: int, chunk_dim: int, *input_tensors):
""" 将运算分割为多个chunk计算来节省显存 当chunk=0,不分块执行
参数:
forward_fn (:obj:`Callable[..., torch.Tensor]`):
chunk_size : `num_chunks = len(input_tensors[0]) / chunk_size`.
chunk_dim... | 4e59428510f6a3b6072a633a23a0c87d0eadec79 | 604,011 |
def replace_value(line, value):
"""Replaces the parameter `value` in the given `line` of a MESA
inlist. Format is inferred from the type of value: `float`,
`str`, `int` or `bool`.
"""
equals = line.index('=')+1
if type(value) == float:
return '%s %.20e\n' % (line[:equals], value)
e... | 2f91f562c17f8c3c5316df20506bba00261bc5c1 | 604,014 |
def date_format(d):
"""Takes numerical date without formatting (20141225) and formats it (2014.12.25)
"""
if not d:
return ""
t = str(d)
return "{}.{}.{}".format(t[0:4], t[4:6], t[6:8]) | 5604900121de0ee722890b8d09be75e65168e1e3 | 604,016 |
def mult(first: int, second: int) -> int:
"""Multiply arguments."""
return first * second | 86e41efc39eeec5369ea3013d26524a3c9325167 | 604,019 |
from typing import Tuple
def _get_units(b: int) -> Tuple[int, str]:
"""Gets a divided byte size and unit describing the size"""
ret_rate = 0
ret_unit = "B"
iters = 0
while b > 0:
ret_rate = b
b //= 1024
iters += 1
if iters == 2:
ret_unit = "KiB"
elif iters ... | e38d44f15755c78733d939f3f6e779cc945c2476 | 604,029 |
import importlib
def import_modules(modules, path, attribute=None, fetch_attribute=False):
"""Import and return modules from a path if they have a given attribute
:param modules: Collection of modules to import or collection of tuples
containing (module, attribute).
:param path: impor... | 235734bdb293c1f4a8db8ceea47bdd447c38332e | 604,035 |
import random
def run_single_walk(start_node, graph, length):
"""Run a single random walk on a graph from a given start node.
Parameters
----------
graph : networks.MultiGraph
The graph on which the random walk is to be run.
start_node : str
The identifier of the node from which t... | dcd8139ba96ac8e28038590cb3ad28a7e2fc2cdc | 604,038 |
import torch
def mse_loss(data, logits, weight):
"""Mean square error loss."""
weights = torch.ones_like(data)
weights[data > 0] = weight
res = weights * (data - logits) ** 2
return res.sum(1) | 74cd42b99cc65bcb9675d821c80cca84ab3b6645 | 604,040 |
from typing import Any
def _should_coerce_to_bytes(item: Any) -> bool:
"""Whether the item should be converted to bytes."""
# These types are OK in forms, others should be coerced to bytes
return not isinstance(item, (bytes, str, int)) | 561263dc391ffecee5b38f38c2f05a6d35d3120f | 604,042 |
def getBit(n, bit):
"""
Name: getBit(n, bit)
Args: n, the original integer you want the bit of
bit, the index of the bit you want
Desc: Returns the bit at position "bit" of integer "n"
>>> n = 5
>>> bit = 2
>>> getBit(n, bit)
1
>>> bit = 0
>>> getBit(n, bit)
1
... | 37563dd7d210e53c85067b0f8697e4f106e408a2 | 604,044 |
def count_tiles(x, y, s):
"""Returns amount of tiles needed for the specified room size."""
result = float(x) * float(y) / float(s)
return result | c83c295022f364e7c0e801200499c01bb08e5631 | 604,046 |
from typing import Tuple
from typing import List
def analyzeInput(inputString: str) -> Tuple[List[str], List[str], List[str]]:
"""
splits the input string so it can be read
Args:
inputString (str): has to be like "elemA|elemB|... factor*vdw elemC|elemD|..."
Returns:
list: list of lis... | ca74593527fd2ced8bd351fcd7604497c2076a8a | 604,048 |
def viewitems(d):
"""Return either the items or viewitems method for a dictionary.
Args:
d (:obj:`dict`): A dictionary.
Returns:
view method: Either the items or viewitems method.
"""
func = getattr(d, "viewitems", None)
if func is None:
func ... | 770d768f5df8b31988c3642123fba04499c41d7e | 604,051 |
def align(data):
"""
Return the data aligned with its mean values.
Args:
data (pandas.core.frame.DataFrame):
Dataset which should be aligned
Returns:
pandas.core.frame.DataFrame: New DataFrame with aligned data.
"""
mean = data.mean()
return data.sub(mean) | 413329e1a20475bfd1d78277ff6fd1db49637659 | 604,052 |
def generate_ctrlptsw(ctrlpts):
""" Generates weighted control points from unweighted ones in 1-D.
This function
#. Takes in a 1-D control points list whose coordinates are organized in (x, y, z, w) format
#. converts into (x*w, y*w, z*w, w) format
#. Returns the result
:param ctrlpts: 1-D co... | b01f77ed1a6cd6962a8cb1e410ba7edfd84f1ad5 | 604,059 |
def format_size(size):
"""
Formats a filesize to use Kb
"""
kb_int = int(size / 1024)
return "{:d} KB".format(kb_int) | 5e35f044731115026511e7c73a7fafd96d333771 | 604,063 |
def readn(f, n):
"""Read n lines from a file iterator f."""
return "".join(f.readline() for _ in range(n)) | b2a41b6a43b39b1727b68590e887688580ff738f | 604,064 |
import torch
def haschildren(obj):
"""Check if the object has children
Arguments:
obj {object} -- the object to check
Returns:
bool -- True if the object has children
"""
ommit_type = [torch.nn.parameter.Parameter, torch.Tensor]
if type(obj) in ommit_type:
return Fals... | 03ef8ef009565a437a99beed4f1f6076ac6ffa1a | 604,067 |
import re
def c_friendly_string(string):
""" Return a string where most "non-C" characters are replaced
with underscores."""
return re.sub(r'\.|/|\!|\@|\#|\$|\%|\^|\&|\*|\(|\)|\~|\`|\'|^[1234567890]', '_', string) | a5797568b6e55d00416390b165cae8c16e6dec89 | 604,068 |
def clear_bit(number: int, position: int):
"""
Set the bit at position to 0.
Details: perform bitwise and for given number and X.
Where X is a number with all the bits – ones and bit on given
position – zero.
>>> clear_bit(0b10010, 1) # 0b10000
16
>>> clear_bit(0b0, 5) # 0b0
0
""... | ae3433e2991f4f63971f17a79c1c3f142871f57f | 604,069 |
def fzs(*args):
"""
Generate a set of frozensets of args. This is needed, because set cannot be a member of a set.
>>> fzs({'a', 'b'}, 'c') == {frozenset({'a', 'b'}), frozenset({'c'})}
"""
return {frozenset(s) if isinstance(s, set) else frozenset({s}) for s in args} | fa38ca390acebd65be20bfc6e44eba7105d935e3 | 604,070 |
def cpp_escape_name(name):
"""Escape package name to be CPP macro safe."""
return name.replace("-", "_") | 57f8bb59d46c6888f4f6d2bc7f851f18ca666fc3 | 604,076 |
import math
def bretschneider(a,b,c,d,ab,cd):
"""
Calulate the area of a quadrilateral with the length of the four sides a,b,c,d and
the degrees of an opposite pair of angles.
Uses the Bretschneider's formula.
Can be used on any quadriliteral as long as all lengths are known
and as long as to... | 210000f9d61049a1213839d1dd491d7e0d2ad2f4 | 604,078 |
def filter_instances(timings, name):
"""
Filters a single cell instance from the given timing data
"""
cells = {}
for cell_type, cell_data in timings.items():
# Don't have that instance
if name not in cell_data:
continue
# Leave only the one that we are looking... | 2354b178dce734fc9c239b6b953c3e4b4f8b7faa | 604,079 |
def escape_line_delimited_text(text: str) -> str:
"""
Convert a single text possibly containing newlines and other troublesome whitespace
into a string suitable for writing and reading to a file where newlines will
divide up the texts.
Args:
text: The text to convert.
Returns:
The ... | e4e3f4f676a0e6256cd25fbcc3846b4e37634e8a | 604,082 |
def get_table_1(results, number_runs, starting_cost_params):
"""
Create Table 1 in my thesis.
Parameters
----------
results : pd.DataFrame
the results of the Monte Carlo simulation in Iskhakov et al. (2016)
calculated in ``get_iskhakov_results``.
number_runs : float
numb... | 810fd5e749addbb1478bf9909d112e8ed68ed070 | 604,083 |
def del_nz_positions(prof1, prof2):
"""Set positions that are non-zero in both profiles to zero. A new profile is returned."""
prof1_len = len(prof1)
assert prof1_len == len(prof2), "Activity Profiles must have the same length to be compared."
result = []
for idx in range(prof1_len):
if prof... | 6b0c1a886845415872af96d35cf1210609e91856 | 604,085 |
def format_sam_record(record_id, sequence, qualities, tags,
flag='0', reference_name='*', mapping_position='0',
mapping_quality='255', cigar_string='*', reference_name_of_mate='=',
position_of_mate='0', template_length='0' ):
"""This formats arguments into a string for outputting as a SAM ... | a676d68047f271696ca68839fb82224549730704 | 604,089 |
def life_crear(mapa):
"""
Crea el estado inicial de Game of life a partir de una disposición
representada con los caracteres '.' y '#'.
`mapa` debe ser una lista de cadenas, donde cada cadena representa una
fila del tablero, y cada caracter puede ser '.' (vacío) o '#' (célula).
Todas las filas ... | cf71e1ba2d2fc1544e2d86a67cfea8a500481f93 | 604,090 |
import uuid
import hashlib
def providerid_from_name(providername : str) -> uuid.UUID:
"""Generate a provider id UUID from a provider name string.
All TraceLogging providers must have a provider name (string) and a
provider id (UUID). Once selected, the name and id form a pair: the name
should never b... | edcde6a7902f75ca1562c9b7987f1c8db219ba76 | 604,096 |
def log2ceil(arg):
"""Calculates: ceil(ld(arg)) for integers."""
if arg == 1: return 0
tmp, log = 1, 0
while arg > tmp:
tmp = tmp * 2
log = log + 1
return log | 57e81c823e17b30fa83790ab818a12b85de9a476 | 604,098 |
from typing import Deque
def to_path(schema_path: Deque[str]):
"""Flatten a path to a dot delimited string.
:param schema_path: The schema path
:returns: The dot delimited path
"""
return ".".join(str(index) for index in schema_path) | fcc9a3fa4dc88c7a2a4410b629b1ec16fcf689fc | 604,101 |
import re
import base64
import hashlib
def fingerprint_from_ssh_pub_key(data):
"""Calculate the fingerprint of SSH public key data.
>>> data = "ssh-rsa AAAAB3NzaC1y...4IEAA1Z4wIWCuk8F9Tzw== my key comment"
>>> fingerprint_from_ssh_pub_key(data)
'54:c7:4c:93:cf:ff:e3:32:68:bc:89:6e:5e:22:b5:9c'
A... | deae6bda0425563e71eb0ba3e751c3ea6566d795 | 604,104 |
import torch
def to_torch_tensor(np_array):
"""
convert a numpy array to a torch tensor by putting it to the appropriate type
and dimension
"""
return torch.tensor(np_array).unsqueeze(0).to(torch.float32) | 1546eee39b8f906e98489b7f23398e4d0b11b6be | 604,105 |
def createDico(texte):
"""
We need to create a dictionnary that contains the word of the vocab and the index of the word.
We need those index to be able to use the lookup table that will contains all the
embedding vectors.
"""
vocab = set(texte) # ex => set("hello world world for") => {"hell... | 7da6df09d5f6ed5608d4741e2196d104e3eeaa10 | 604,109 |
import json
def get_zattr_info(in_zarr):
"""Parse zattrs of given OME-zarr and return bands, max layer and tilename
Parameters
----------
in_zarr : str
path to OME-zarr
Returns
-------
info: tuple(list, int, str)
tuple of bands, max layer and tilename retrieved from zattr... | 1f58e17dbd443a6f31e810d48d89692f1566bb49 | 604,110 |
def imputed_indices(invalid, length, method='bfill'):
"""Imputation indices assuming the last element is valid.
Args:
invalid: List of negative indices of invalid entries.
length: Length of the list to impute.
method: Imputation methods. Default 'bfill' implements backward-fill
... | c7e2c825d17d4649bdc455dd01ef32f035436c82 | 604,111 |
def peel_digits(num):
"""
Given a positive integer num, peel_digits returns a list filled with the digits
eg. given 1984, peel_digits returns the list [1, 9, 8, 4]
:param num: an integer to peel into a list of digits
:return: A list where each element of the list is a digit from num
"""
str_... | 3f6866393ad6c346d9f06d5bd69b8f9b8aa715d1 | 604,112 |
import re
def replace_mentions(text, filler='@user'):
"""Replaces Twitter @mentions in text with `f' {filler}'`.
Potentially induces duplicate whitespaces.
"""
# Positive lookbehinds: https://stackoverflow.com/a/40617321/4949133
username_regex = re.compile(r'(?:(?<=^)|(?<=[^@\w]))@(\w{1,15})\b')
... | 2133155402ba4c5cc089efe686f0ca2de716d66f | 604,117 |
def urls(string):
"""Parse a comma-separated list of url() strings."""
if not string:
return []
string = string.strip()
if string.startswith("url"):
string = string[3:]
return [
link.strip("() '\"") for link in string.rsplit(")")[0].split(",")
if link.strip("() '\"")... | 7dafa020ca7d118954873e85a490affcb5ceef98 | 604,120 |
import base64
def _make_data_URI(data, output_format):
"""Convert the image with format output_format given as a byte array to a data URI."""
media_type = None
if output_format == 'png':
media_type = 'image/png'
elif output_format == 'svg' or format == 'svgz':
media_type = 'image/svg+x... | f462eeecdeece21281fae8c320d1c303b254aa76 | 604,123 |
def accumulate_rotation(a_in, a_0):
"""
Compares current Axis value with its previous value to determine if there
has been a 360 degree flip in the Axis' evaluation.
e.g.:If a_0 = 94 and a_in = -265; instead of -266, this function would
output a_out = 95
:param a_in: float; current evaluation of... | f8aad055db8d7c92f2c5ed0688c02b63f7ded12c | 604,128 |
import hashlib
def md5_key_mangler(key):
"""
Encodes SELECT queries (key) into md5 hashes
"""
if key.startswith('SELECT '):
key = hashlib.md5(key.encode('ascii')).hexdigest()
return key | 96c179e6a8be76b5f6a3f511b2a5045541738da6 | 604,129 |
import gzip
def open_file_helper(filename, compressed, mode="rt"):
"""
Supports reading of gzip compressed or uncompressed file.
Parameters:
----------
filename : str
Name of the file to open.
compressed : bool
If true, treat filename as gzip compressed.
mode : str
... | a682924f68158f88552b96197c43735bb596afaa | 604,130 |
def register_argument_parser(add_parser, action):
"""Calls add_parser for the given sub-command (create or update) and returns the parser"""
sub_command = str(action)
return add_parser(sub_command,
help=f'{sub_command} token',
description=f'{sub_command.capitalize... | cd8d81b076c3c26aade50910151ada87b57b8375 | 604,131 |
def next_power_of_two(x):
"""Calculates the smallest enclosing power of two for an input.
Args:
x: Positive float or integer number.
Returns:
Next largest power of two integer.
"""
return 1 if x == 0 else 2**(int(x) - 1).bit_length() | a1a48968ff05bb3919245581b4d651ad4b56e453 | 604,136 |
def yes(msg):
"""Prompt the user for a yes/no answer. Returns bool"""
answer = input("{} (Y/N) ".format(msg))
return answer.strip().lower() in ["y", "yes"] | 672e6f12c3bc9571bd608ed7bd2ea96e026e02e2 | 604,139 |
def clip(x, a, b):
"""Return the nearest point of x in the interval [a, b]"""
if a > b:
return None
return min(max(x, a), b) | 86bcb7c0e0f6810a97f3694b6a09f1cb1a0982e4 | 604,141 |
def all_exception_handler(handler_input, exception):
"""Catch all exception handler, log exception and
respond with custom message.
"""
# type: (HandlerInput, Exception) -> None
print("Encountered following exception: {}".format(exception))
speech = "Si è verificato un problema. Riprova!"
h... | deb7378dffce4549f9f3fd297481c0f00dc3d36b | 604,142 |
def GetGenes(transcripts):
"""from a list of transcripts get genes.
"""
genes = {}
for t in transcripts:
if t.mGene not in genes:
genes[t.mGene] = []
genes[t.mGene].append(t)
return genes | e76ba986a7d1bfd1365a6195aeb78ea6c9a02c29 | 604,144 |
def should_skip_build(metadata_tuples):
"""Takes the output of render_recipe as input and evaluates if this
recipe's build should be skipped."""
return all(m[0].skip() for m in metadata_tuples) | 0c4c54349bbea32733e9b0459fdfab9466dfdba8 | 604,147 |
def check_node_usages_out_of_match(match: dict, node_name_in_match_group: str):
"""
Checks if node is consumed by nodes out of match
:param match: dictionary with pattern match
:param node_name_in_match_group: string
:return:
"""
assert node_name_in_match_group in match
graph = match[nod... | 991645e52b93bbafed1f22a018f2349e625de94d | 604,149 |
def get_element_index_by_text(elements, text: str, complete_match=True):
"""
Loops through the list of elements, checks if the text is equal or in
text and returns the index of it if so
"""
for i in range(0, len(elements)):
if complete_match:
if elements[i].text == text:
... | 61f80f23bc06cbe3de3824c9b2e3eb9635ea5d86 | 604,150 |
def add_two_numbers(x_val: int, y_val: int) -> int:
"""Just adds two numbers together."""
return x_val + y_val | c22073efd194ff6b7cdf60b89a1fd1f893936929 | 604,151 |
import hashlib
def addrbin(pubkey):
"""Given a public key, in binary format, return its binary form address (just the bytes, no type or checksum)"""
h = hashlib.new('ripemd160')
h.update(hashlib.sha256(pubkey).digest())
return h.digest() | 8bd815ef54edebf69128223a43c04373ebb57ee6 | 604,152 |
def deep_list(x):
"""Convert tuple recursively to list."""
if isinstance(x, tuple):
return map(deep_list, x)
return x | 24973c9648a3eba2d193258172500b79d3a4f160 | 604,154 |
def _get_dtype_name(tf_type):
"""Converts tf.dtype (eg: tf.float32) to str (eg: "tf.float32")."""
return "tf." + tf_type.name | 6ef729b2e24411c956eaa9905759e0ed3f214921 | 604,157 |
def _get_filter_size(neighborhood_size, feature_size):
"""Returns number of elements in filter with size neighborhood_size."""
return (neighborhood_size + 1)**(feature_size + 1) - neighborhood_size**(
feature_size + 1) | ddf9f0c23767fce62ace4ad6bcd225661a5b407d | 604,158 |
def compute_giou(arg_obj, ref_obj):
"""
Compute the generalized intersection over union code described in the paper available from:
https://giou.stanford.edu/GIoU.pdf Page 4 of the paper has the psuedocode for this algorithm
:param arg_obj: The argument object represented as a bounding box
:param r... | d047c1e66edb252896a4e1e4bd45e1f14fb31fd8 | 604,163 |
def str_head_pop(s, n):
"""
Pop n characters from string s from the beginning.
Returns a tuple consisting of the new s and the popped characters.
"""
if n >= len(s):
return ('', s)
s = list(s)
return (''.join(s[n:]), ''.join(s[:n])) | e0f137600d116e15f6cfa36c637a4b0316df5bad | 604,167 |
import math
def normal_to_altaz(normal):
"""
given a vector, return the corresponding (altitude,azimuth) pointing direction
Parameters
----------
normal: cartesian coordinates of the vector = 3-floats array
Returns
-------
altitude, azimuth = angles of the vector pointing direction
... | c22f4919140397d134c89e577ad53299b73f9d99 | 604,170 |
def compute_energy_from_density(density, x_dimension, y_dimension, chemical_potential):
"""Computes energy from energy density."""
return (x_dimension * y_dimension) * (density - chemical_potential) | d3b43b513ef57aa78f1b483ea598c974313f3fcc | 604,171 |
def write_types(text: str = "") -> str:
"""Write the [Types] portion of the installer script
Args:
text (str): Prototype of the [Types] portion to format
Returns:
str: The formatted [Types] portion of the installer script"""
return text | 59c113aae1be9f4883e969d6a7e736b0addb9a76 | 604,177 |
def where(configurable, attribute=None):
"""
Retrieve the location where the {attribute} of {configurable} got its value; if no
{attribute} is specified, retrieve information about the {configurable} itself
"""
# if no attribute name is given, return the locator of the configurable
if attribute ... | bfb803738c3028ed28cb6570c4ac8f3f73fda720 | 604,181 |
def split_dataset(data_df,
set_col='set',
train_set_name='training',
val_set_name='validation',
test_set_name='test'):
"""
Splits dataset into
(1) `trainval_df`: training + validation set
(2) `train_df`: test set
based o... | 836673d32d4a38e328e287fd5ad4658d80465468 | 604,183 |
def get_offset_and_limit(data, max_limit=None, default_offset=0, default_limit=20):
"""从数据中获取偏移量和每页数量。get offset and limit from data.
Examples::
offset, limit = get_offset_and_limit(request.data, max_limit=100)
:type data: dict
:type max_limit: int
:type default_offset: int
:type defa... | 0f9f42555e01716c376649fd3e6ad792a9534abe | 604,186 |
def getdifflist(inputlist):
"""returns a list of length-1 relative to the input list
list values are the differential of the inputlist [n+1]-[n]"""
difflist=[inputlist[i+1]-inputlist[i]
for i in range(len(inputlist)-1)]
return difflist | 145f11f1f6af87a222f91a2b2cd2ee4c6a039df7 | 604,190 |
from typing import Any
import io
def isio(obj: Any, *, read: bool = False, write: bool = False) -> bool:
"""Determine if object is IO like and is read and/or write.
.. note::
Falls back to :code:`isinstnace(obj, io.IOBase)` if neither `read` nor
`write` is True.
:param obj:
Obje... | 754ebfccc84c8dbbbc0b98f535b77eaee1466b99 | 604,198 |
def velocity_exceeded(Rover, max_vel=2.0):
"""
Check if velocity is under max_vel.
Keyword arguments:
max_vel -- maximum velocity in meters/second
"""
return Rover.vel < max_vel | 944a8c1c19c3c080f8fc79364b40555a8ee792e1 | 604,202 |
import math
def calc_frac_diff(x, y):
"""Calculate the fractional difference between two numbers.
If the reference value is 0 and the value to check is not, returns 1.
:param x: Value to check
:param y: Reference value
:return: Value
"""
if(y != 0):
return math.fabs((x - y) / y)
... | 2b2d5e87feda4628f5ba7c508ebdaf64ccb90f89 | 604,203 |
import io
def clean_lines(f):
"""
Filter out blank lines to avoid prior cross-platform line termination problems.
"""
lines = f.read().splitlines()
lines = [line for line in lines if line.strip()]
content = '\n'.join(lines)
sio = io.StringIO()
sio.write(content)
sio.seek(0)
ret... | bb017a37704fd970452ba51f41668c259ac1459b | 604,205 |
def gt(self, y):
"""Returns self > y"""
return (-self + y)._ltz() | d150a4b8e260e6a124c86fd439fec38be732beeb | 604,207 |
def combat_str_replace(att, vict, att_weapon, vict_weapon, string,
vict_body = None):
"""
Replaces the tokens in our combat output string with the appropriate
string.
$o - p_two's sdesc
$go - p_two's gender
$s - p_one's sdesc
$gs - p_one's gender
$ws - p_one's we... | bb0b57f0754ac4c334a2234058d3f4fc8ccf2b90 | 604,208 |
def quote_pad(string):
"""
Returns a string padded with quotes.
str -> str
"""
quote = "'"
return quote + string + quote | c880af085334fc9446ed461eecd72c5a7f171a8a | 604,209 |
def isascii(string):
"""Checks whether a unicode string is non-empty and contains only ASCII
characters.
"""
if not string:
return False
try:
string.encode('ascii')
except UnicodeEncodeError:
return False
return True | 0b8bcd9ac30967231de4fcbde5df58ce60a2835d | 604,210 |
import random
def swap_permutation(permutation, numswaps):
"""
Swap numswaps pairs of integers in the permutation
Input permutation should be an index vector (e.g. a permutation of
the integers from 0 to dimension-1 of the vector).
"""
newperm = permutation.copy()
for x in range(numswaps):... | 0f7434ce31c28e99cb88c945fea59bfefa0f05d7 | 604,212 |
def get_ewma_derivative(data, ewma_window):
"""Compute the ewma and the derivative
Parameters
----------
data: pandas DataFrame
ewma_window: width of the window
in the rolling average
Return
------
ewma_derivative: pandas DataFrame
derivative of the ewma of data
"""
e... | 343c9384c0338808b4e85fd8688a03838518bbdd | 604,216 |
def get_quartile_data(number_of_simulations):
""" Take in the number of simulations and output the quartile line numbers. """
std_increment = round(number_of_simulations/100)
lower_quartile = round(std_increment*25)
middle_quartile = round(std_increment*50)
upper_quartile = round((std_increment*75))... | 29824ef904ec18f659afb6115ff77a7222d42215 | 604,217 |
def daily_feature_data_split(df, start, end):
"""
split the dataset into training or testing using date
:param data: (df) pandas dataframe, start, end
:return: (df) pandas dataframe
"""
data = df[(df.date >= start) & (df.date < end)]
data = data.sort_values(["date"], ignore_index=True)
d... | ef7a403a5c1fea5e37d7794c00d6958b0dfcc3b7 | 604,221 |
from typing import Dict
from typing import Any
def practically_equal(a: Dict[Any, Any], b: Dict[Any, Any]) -> bool:
""" Compare two defaultdict. It is used because a simple access have
side effects in defaultdict.
>>> from collections import defaultdict
>>> a = defaultdict(list)
>>> b = defaultdi... | d51ef53089c606ae5c54a89122ed5e63ac09e071 | 604,222 |
def reformat_large_tick_values(tick_val, pos):
"""
Turns large tick values (in the billions, millions and thousands) such as
4500 into 4.5K and also appropriately turns 4000 into 4K
(no zero after the decimal).
"""
if tick_val >= 1000000000:
val = round(tick_val/1000000000, 1)
ne... | 5d39e9406afc1c33aa364ff3cd353585ec609e61 | 604,223 |
import math
def summarize(v):
"""
Returns basic summary statistics (mean, variance, stddev) for the supplied vector v in a tuple.
"""
assert v is not None
n = len(v)
assert n > 1, 'summarize function requires a vector of at least two values'
sum = 0.0
sumsq = 0.0
for x in v:
... | b5c311f1498d01ed378d951344e0eb5f3cc6a5ba | 604,224 |
def never_decrease(num: str) -> bool:
"""Check if digits are never decrease."""
return all(int(num[i]) >= int(num[i - 1]) for i in range(1, len(num))) | 929176f629cf57ca4cd83fd4565f1707107f9573 | 604,228 |
def calc_AIC(k, maxlogL):
"""
| Calculate Akaike Information Criterion.
| k = number of parameters
| maxlogL = maximum log likelihood
"""
aic = 2 * (k - maxlogL)
return aic | bc5fcbddce154d452910fee13f8d509f9d8346e6 | 604,234 |
def is_horizontal_rule(line):
""" Check if a line looks like a horizontal rule."""
line = line.strip()
return all(ch == '#' for ch in line) and len(line) > 10 | 2c23438265242f81692d2d986be33e3818c9eb50 | 604,236 |
def flash_class(category):
"""Convert flash message category to CSS class
for Twitter Bootstrap alert
:param category: Category of flash message
:type category: str
:return: CSS class for category
:rtype: str
"""
if category == 'error':
return 'danger'
return category | ea03fe4ba14a32a32498b96016bf9a0f479c9662 | 604,240 |
def flattened_dimensions(space):
"""
Computes the number of dimensions a flattened equivalent of the given space would have.
"""
space_dim = 0
for prop in space.properties:
prop_dim = 0
if prop.WhichOneof("definition") == "discrete":
prop_dim = max(len(prop.discrete.labe... | 212eafb00b538d927d71f7b0207326b5d6550bc1 | 604,242 |
import struct
def p16(x):
"""Packs an integer into a 2-byte string (little endian)"""
return struct.pack('<H', x & 0xffff) | 589bf8baa11e5a9ec92a4012efaf20b4f0822efd | 604,243 |
import torch
def encode(localization_match, localizations_default):
"""localization_match are converted relatively to their default location
localization_match has size [batch, number_of_localizations, 2] containing the ground truth
matched localization (representation x y)
localization_defaults has ... | e01250a0c188af45615b748e01c932395e7b6381 | 604,244 |
def split(seq, length):
"""
Split a list in chunks of specific length
"""
return [seq[i : i + length] for i in range(0, len(seq), length)] | 06c29b4021ea0f7460368db627c489632704cf64 | 604,246 |
import zlib
def hash(polygon):
"""
Get a hash of a polygon
Parameters
-----------
polygon : shapely.geometry.Polygon
Polygon to hash
Returns
------------
crc : int
Hash of polygon
"""
crc = zlib.adler32(polygon.wkb)
return crc | 10d58f376d752d955e21a8a4c35ce287b99fe4c0 | 604,249 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.