content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def get_payday_leap_years(
payday,
frequency='biweekly',
count=5,
starting_year=date.today().year
):
"""Get the next n payday leap years.
Return a list of the next n payday leap years, where n is specified
by `count`.
Args:
payday (date): A payday from the specified pay calenda... | 87808c0ee596005c2dd90db30b2cd168cf7ebf63 | 51,590 |
import json
def output_message(message):
"""This function will output an error message formatted in JSON to display on the StatusBoard app"""
output = json.dumps({"error": message}, indent=4)
return output | 06f9ed6350cfc9e721cfb1e24b9a695bff6d9ffe | 51,591 |
def _time_distributed_dense(x, w, b=None, dropout=None,
input_dim=None, output_dim=None,
timesteps=None, training=None):
"""Apply `y . w + b` for every temporal slice y of x.
# Arguments
x: input tensor.
w: weight matrix.
b: optiona... | 8d81621ef720c9eed044f7d58c55030bdd9eea30 | 51,593 |
from typing import Callable
import collections
def build_scheduled_client_work(
model_fn: Callable[[], model_lib.Model],
learning_rate_fn: Callable[[int], float],
optimizer_fn: Callable[[float], TFFOrKerasOptimizer],
metrics_aggregator: Callable[[
model_lib.MetricFinalizersType, computation_ty... | a4e2c0b635ffab3cd781a8584aff0811b1d2bd4d | 51,594 |
from typing import Set
from typing import Iterator
def filter_by_letterset(letters: Set[str], words_set: Iterator[str]) \
-> Iterator[str]:
"""
Filters the words in the dictionary by the letter-set. So, the set
{'h', 'o', 'w'} will match 'how' and 'who' but not 'whom'
Args:
letters: Th... | a072c80c3bddf0f7ff06437c635f46f4b2e43c97 | 51,595 |
import copy
def evaluate_confusion_matrix(y_true, y_pred, labels):
"""
Calculates a Confusion for each each of for y_true / y_pred and returns a formatted dictionary with the results.
:param ndarray y_true: The (potentially multiple) observed targets
:param ndarray y_pred: The (potentially multiple) ... | fa83931c085b147dd6c432bb45ba0a1eb773f0e7 | 51,596 |
from typing import Callable
from typing import Optional
from pydantic import BaseModel # noqa: E0611
def get_redirects(func_name: str, attr: str,
redirect_from: Callable) -> Optional[BaseModel]:
"""Get an attribute :code:`attr` from function :code:`func_name` from context of
:code:`redirect... | 25a4bfc1e6872bcff45cb6b67b3cfde3e8e075bb | 51,597 |
import msgpack
def send_msgpack(socket, obj, flags=0, protocol=-1):
"""pickle an object, and zip the pickle before sending it"""
p = msgpack.packb(obj, use_bin_type=True)
return socket.send(p, flags=flags) | e80dee26986c4975b46e4527f8425e25cecf0621 | 51,598 |
def CreateFromSurface(surface, multiple=False):
"""
Constructs a mesh from a surface
Args:
surface (Surface): Surface to approximate
Returns:
Mesh: New mesh representing the surface
"""
url = "rhino/geometry/mesh/createfromsurface-surface"
if multiple: url += "?multiple=tru... | 2abe38c4ba2ec4a60ef69f54dac51d194c1a48a5 | 51,600 |
def multiscatterplot(
data=None,
columns=None,
group_by=None,
color=None,
opacity=1,
tooltip=None,
height=600,
width=800,
):
"""Generate many scatterplots.
Based on several columns, pairwise.
"""
opt_args = choose_kwargs(locals(), ["color", "tooltip"])
assert group_... | b6cab0591d8291095fed056de5e1e15e46a07e5f | 51,601 |
def register_tf_serializable(name=None, predicate=None):
"""See the docstring for `register_serializable`."""
return register_serializable(package="tf", name=name, predicate=predicate) | c3299a8624b5a189dd2805cefcc0ed54bbe56e59 | 51,602 |
def compute_inertia_ellipsoid(points):
"""Compute inertia ellipsoid for `points`.
Please note, that order of Ellipsoid.axes might not correspond to the order of image axes!
Arguments:
points {numpy.array} -- an array of points (x, y, z)
Returns:
[analysis.Ellipsoid] -- inertia ellipso... | 3d5d1d893f45533cdfb201381ec59f4008224670 | 51,603 |
def get_back_to_settings_button(poll):
"""Get the back to options menu button for option sub menus."""
locale = poll.user.locale
payload = f'{CallbackType.menu_back.value}:{poll.id}:{CallbackResult.settings.value}'
return InlineKeyboardButton(text=i18n.t('keyboard.back', locale=locale),
... | 3dc05773693bc0a53564f238ba1fcb2836c75d09 | 51,604 |
from typing import cast
def downsample_average(trace: Trace, factor: int = 2) -> Trace:
"""
Downsample samples of `trace` by `factor` by averaging `factor` consecutive samples in
non-intersecting windows.
:param trace:
:param factor:
:return:
"""
resized = np.resize(trace.samples, len... | e3c6fab242efc4e723ebb30e38e372fb12b0d9c6 | 51,606 |
def generate_acrostic(tokenizer, model, head):
"""
随机生成一首藏头诗
:param tokenizer: 分词器
:param model: 用于生成古诗的模型
:param head: 藏头诗的头
:return: 一个字符串,表示一首古诗
"""
# 使用空串初始化token_ids,加入[CLS]
token_ids = tokenizer.encode('')
token_ids = token_ids[:-1]
# 标点符号,这里简单的只把逗号和句号作为标点
punctuati... | d17d441499eb856ef246e0928267947dcd89b6eb | 51,607 |
import asyncio
def run_cmd(cmd, ignore_return_code=False, no_shell=False):
"""
Run a command using the async function that logs the output.
:param cmd: command to run
:param ignore_return_code: whether a non-zero return code should be ignored
:param noshell: don't run the command in a sub-shell
... | 0ea21d3925f1cd2fef56aa18962bf9fd3ef0a8c8 | 51,608 |
def distance0(cell1, cell2):
"""Return 0 distance for A* to behave like Dijkstra's algorithm."""
return 0 | 7850364b245afd304e3aa3ad443d7af74b36df79 | 51,609 |
def get_allowed_post_types_from_link_type(link_type):
"""
Determine allowed_post_types based on a value for reddit's link_type setting
Args:
link_type (str): the link type or None
Returns:
list of str: list of allowed post types
"""
if link_type in [LINK_TYPE_LINK, LINK_TYPE_SE... | a663dca858cb4aa61f3c9ad03f660a5edab55799 | 51,610 |
def get_dev_config():
"""Get dev config object."""
config_class = get_config_class()
return config_class(config_yaml=DEV_CONFIG_YAML) | 69d9369e66842b0e39f225dff2c3b5d9b1274af4 | 51,611 |
def get_adjmatrix_from_image(image):
"""Get the adjacenty matrix from image
Args:
searchmap(np.ndarray): our structure of searchmap
Returns:
set of tuples: set of the crossing positions
"""
searchmap = parse_image(image)
return get_full_adjmatrix_from_npy(searchmap) | 8b4f3530b5eaf2c1e5225c0fb063b5e7e0755e33 | 51,612 |
def adjacent(g,node, n):
"""
find all adjacent nodes of input node in g
g: 2D array of numbers, the adjacency matrix
node: int, the node whose neighber you wanna find
return: a list of ints
"""
result = []
for i in range(n):
if g[node][i] != 0:
result.append(i)
... | 630160dbee314ed85980ac8bd825e96cd33765f4 | 51,613 |
def create_dgl_object(graph_name, num_parts, \
schema, part_id, node_data, \
edge_data, nodeid_offset, edgeid_offset):
"""
This function creates dgl objects for a given graph partition, as in function
arguments.
Parameters:
-----------
graph_name... | dc8c707d9f17891881bfcc8748f3d911b8aa4ca2 | 51,614 |
def get_version() -> str:
"""
Retrieves version from the flask app.
"""
if 'version' not in g:
g.version = read_version('development')
return g.version | bd85e17e6814a0717e948d6e8a66495a68d21981 | 51,615 |
def create_counter():
"""Returns a prefab which can contain one of any item."""
base_prefab = create_base_prefab("counter")
base_prefab["components"] += [{
"component": "Container",
"kwargs": {
"reward": 0.0
}
}]
return base_prefab | 5314121059f4172fe7b9a75105509e428052cc74 | 51,616 |
def GetCyclicThioamide(mol):
"""
Return:
count: int
"""
thioamide = Chem.MolFromSmarts("[CX3](=[SX1])@[NH]")
matches = mol.GetSubstructMatches(thioamide)
return matches | c391b17138b0a02b07889ea7fb4558d479d89440 | 51,617 |
from typing import Iterator
def cleanBottom(line):
"""Rewrites bottom patterns."""
it = Iterator(line)
while line.find(["CofreeT ", "Identity ", " :< BottomF "], it):
it.element().replaceWith(Structure("⊥", []))
return line | 41346bc815f3b4103530bf9ecb13498f7a95f7e4 | 51,618 |
from tvtk.api import tvtk
from mayavi import mlab
from mayavi.sources.vtk_data_source import VTKDataSource
def createVtkUnstructuredGrid(G):
"""
Creates a tvtk.UnstructuredGrid object from a PRST grid.
Synopsis:
vtkGrid = createVtkUnstructuredGrid(G)
This is currently only used for plotting... | ae81db14c8d00879b1398d4643c9d08a240d87dd | 51,619 |
def _read_potentials(rotors, spc_dct_i, run_path, cnf_save_path,
ref_ene, mod_tors_ene_info,
tors_model):
""" read out the potentials
"""
_ = run_path
# Convert the rotor objects indexing to be in geoms
increment = spc_dct_i.get('hind_inc', 30.0*phycon.DEG... | bcccfe70b35dcb10718f94ee82586647481ba096 | 51,621 |
def ldns_resolver_defnames(*args):
"""LDNS buffer."""
return _ldns.ldns_resolver_defnames(*args) | 07db6e6097a2afc23d0cf50c168b1eeac0def678 | 51,622 |
from datetime import datetime
def is_expired(message):
"""Determines if a raid is expired, given its announcement message.
Message accepts the result returned by get_announcement_message (a valid obj or None).
:param message discord.Message: The announcement message associated with the raid.
:return... | 3d0715edfef6de7d3608c8a2b673859ac5ac96e1 | 51,623 |
def gaussbeam(w0 = 1,P = 5,z0 = 5, z = 10):
"""
Generate a gaussbeam
========================================
input
----------------------------------------
w0 Beam Waist
P total power
z0 Rayleigh Range
z Axial Distance
output
----------------------------------------
gaussbeam matrix
""... | 337a85497a933b80737603c14e6b96ebae0ef3e6 | 51,624 |
import re
def error_064_link_equal_linktext(text):
"""
Fix the error and return (new_text, replacements_count) tuple.
Also correct links with spaces.
"""
count = 0
def _process_link(match_obj):
"""Deals with founded wiki-link."""
link = match_obj.group(1)
name = match_... | 12494a2b0377c559a3294bae67a84486a91abbe7 | 51,625 |
def calc_unit_kinetic_energy(acc_signal):
"""
Calculates the cumulative absolute change in kinetic energy for a unit volume of soil with unit mass
Parameters
----------
acc_signal: eqsig.AccSignal
Returns
-------
"""
kin_energy = 0.5 * acc_signal.velocity * np.abs(acc_signal.veloc... | be676753894a39102d1793e1ed9b75662e7f1eff | 51,626 |
def flatten(expression):
"""
A AND (B AND C) -> A AND B AND C
A OR (B OR C) -> A OR B OR C
"""
if isinstance(expression, exp.Connector):
for node in expression.args.values():
child = node.unnest()
if isinstance(child, expression.__class__):
node.replac... | 4a59d672c04ec9c7171939979b2a82722859e9a7 | 51,627 |
def split_integer(num, parts):
"""
Split number into given number of pars that are as equal as possible
https://stackoverflow.com/questions/55465884/how-to-divide-an-unknown-integer-into-a-given-number-of-even-parts-using-python
"""
quotient, remainder = divmod(num, parts)
lower_elements = [quo... | bd6a74dc409cef3f6e397579eeb15e6c9cde69a6 | 51,628 |
import json
def lambda_handler(event, context):
"""Lambda function that stores the current step function state token into dynamo.
Parameters
----------
event: dict, required
context: object, required Lambda Context runtime methods and attributes
Context doc: https://docs.aws.amazon.com/lambda... | fc2aa85b0ded0e1831edd437d61bc913cf80749f | 51,629 |
def read_module(f) -> ir.Module:
"""Read an ir-module from file.
Args:
f: A file like object ready to be read in text modus.
Returns:
The loaded ir-module.
"""
return Reader().read(f) | c5f31c0c725292fb03fd0e84ea9a194a52a7de94 | 51,630 |
def chat_guard(func):
"""
Разрешено ли боту работать в этом чате?
"""
@wraps(func)
def decorator(bot: telegram.Bot, update):
chat_id_str = str(update.message.chat_id)
if chat_id_str not in CONFIG["chats"]:
send_chat_access_denied(bot, update)
return
r... | 257c402e3a85f130a39e220fe04422f1c31716a2 | 51,631 |
def get_1st_ck_line_from_line( line ):
"""
A check line may contain more than 1 check.
Here we get only the info(line aka string) from the 1st one.
"""
# return line # if there is only 1 check per line
splited = line.split()
ck1 = splited[:4] # in this case, 1st check info is in 1... | 5979e2231b01385da20fb2a50430989d91af9ba1 | 51,632 |
def convert_to_real_ops(ops):
"""
Converts a batch of TensorFlow operators to something that a neural network
can take as input.
Args:
ops (`tf.Tensor`): a 4D tensor (batch_size, N, hilbert_size,
hilbert_size)
of ... | 78b4c9c5c82a3459a3509bf3f5d1491fc807b8de | 51,633 |
from typing import Optional
import re
def validate_twitter_handle(twitter_handle: str) -> Optional[re.Match]:
"""Validate a twitter handle. Optional @, length up to 15 characters"""
return re.match(__match_twitter_handle, twitter_handle) | 6e6da1a3876be50470361d2bb5408f194df0ebf2 | 51,634 |
def run_popen_with_timeout(command_string, timeout, cwd):
"""
Run a sub-program in subprocess.Popen, pass it the input_data,
kill it if the specified timeout has passed.
returns a tuple of success, stdout, stderr
"""
kill_check = threading.Event()
def _kill_process_after_a_timeout(pid):
... | 43ef05ccadb1678e36763631fd432f42627356ce | 51,636 |
def average_bg_with_rc(bgs):
"""
Average the background frequencies with the reverse complement
----
Parameters:
bgs (dict) : dictionary of the background probabilities
----
Returns:
bgs_avg (dict) : averaged background probabilities
"""
bgs_a... | 9bbf7f7c8648341fac79b27d71d981fb4af449ad | 51,637 |
def splice_alg(pd_edges):
""" Implementation of the SPLICE algorithm
"""
pickups = pd_edges.keys()
deliveries = pd_edges.values()
# Compute Hungarian matching indices
c_mat = dist.cdist(deliveries, pickups)
# Connect dp_edges according to bipartite matching
dp_edges = {deliveries[d_ind]... | c1f5d88382e7b5c34b317d1527d019d07b7fa66e | 51,638 |
def for_get(uri: str) -> dict:
"""
Extract resource names from a URI for supported AWS services.
Currently, only S3 and SSM are supported.
>>> for_get('s3://abc:xyz@bucket/object.data')
{'Bucket': 'bucket', 'Key': 'object.data'}
>>> for_get('ssm://ABC:XYZ@/path/to/parameter?region_name=us-east-... | a4defa6f6e6a0e5a9974b3ec911c041d4a1dc14e | 51,639 |
from typing import Union
from typing import Iterable
from typing import MutableMapping
def as_nested_dict(
obj: Union[DictLike, Iterable[DictLike]],
dct_class: type = dict, **kwargs) -> Union[DictLike, Iterable[DictLike]]:
"""
Given a obj formatted as a dictionary, transforms it (and any neste... | 518337d5e59be662adfead202e217c1b4cd55d85 | 51,640 |
def complete_sulci_name(sulci_list, side):
"""Function gathering sulci and side to obtain full name of sulci
It reads suli prefixes from a list and adds a suffix depending on a given
side.
Args:
sulci_list: a list of sulci
side: a string corresponding to the hemisphere, whether 'L' or ... | 5a0e969976458b81bac01ee33cfa24bbc92659c4 | 51,641 |
from typing import Union
from typing import Callable
from typing import Any
from typing import List
def _gwr(fn: Union[Callable[[float], Any], Callable[[float, int], Any]],
time: float, M: int, precin: int) -> float:
"""
GWR alorithm with memoization.
"""
tau = mp.log(2.0) / mp.mpf(time)
... | 08cf61f6ebd9f6bb175342c5aa68cf10834ecc93 | 51,642 |
def libsvm_convert_sparse_tensor(array_ids, array_values):
"""Transform the contents into TF understandable formats, which is similar to
sparse_tensor_to_train_batch().
Args:
array_ids: Sparse indices.
array_values: Sparse values.
Returns:
List of the transformed (ids, values).
"""
... | 321625a2ecc6424b600d312dc968c67667098131 | 51,643 |
def initialize_deep_flow_model(h, w, weight):
"""Initialize optical flow network
Args:
h (int): image height
w (int): image width
Returns:
flow_net (nn.Module): optical flow network
"""
flow_net = LiteFlow(h, w)
flow_net.initialize_network_model(
weight_... | d4354190805125ad4f64b0882920f3189be2ea82 | 51,644 |
def register_blueprints(app):
"""Register Flask blueprints."""
app.register_blueprint(public.views.blueprint)
app.register_blueprint(user.views.blueprint)
return None | 51d52c1ac93514fea191b74c0da76b019756b79c | 51,645 |
from allennlp.modules.token_embedders.embedding import EmbeddingsTextFile
from typing import List
def _read_pretrained_tokens(embeddings_file_uri: str) -> List[str]:
"""
Helper method for loading pretrained tokens from a given file. This is usually
the case for e.g. GloVe files, containing the token and t... | c59323b27ce19be81c67ef62447e01e3bf8e0e2a | 51,646 |
from typing import Callable
import inspect
def has_param(func: Callable, param: str) -> bool:
"""Check if func has a parameter named param.
Parameters
----------
func : Callable
Function to inspect.
param : str
Parameter name.
Returns
-------
bool
True if the ... | d04603f27a24f6bdfa6c8ae7b720d1d1e8ceb4c2 | 51,647 |
def solve_msd_analytically(t):
"""Returns the analytical solution to the differential equation
at the timepoints t.
"""
mass = 100
springk = 50
damping = 1
x0 = 1
#Calculate help variables
zeta = damping/(2*sqrt(mass*springk))
omega0 = sqrt(springk/mass)
#Solve the differen... | d6c77e6eaa4ce462f842bc57f1ca1c26f7c62e2e | 51,648 |
import torch
def run_on_patches(
image,
model,
conf_threshold,
nms_threshold,
batch_size=128,
z_unit="micro",
toggle_eval=False,
device="cuda",
plot_result=False,
):
"""
Runs input image as 448x448 patches through model and returns resulting particle predictions
:param ... | 07404f8a4d6d8898ae91e7fb0a9a0835e7919385 | 51,649 |
def mbar_hessian(u_kn, N_k, f_k):
"""Hessian of MBAR objective function.
Parameters
----------
u_kn : np.ndarray, shape=(n_states, n_samples), dtype='float'
The reduced potential energies, i.e. -log unnormalized probabilities
N_k : np.ndarray, shape=(n_states), dtype='int'
The numbe... | ac3373ee9032293c940e32b666212fb533fb288a | 51,650 |
def shape_dim_for_plot(iter_avg, n_runs, data, run):
"""Go from shape: (:, data) → (-1, iter_avg) → (-1) (average over data) → (n_runs, 250)
Example: (5000,) → (250, 20) → (250, ) → (1, 250)"""
data = np.asarray(data)
shape_other_dims = data.shape[:-1]
data = data.reshape(shape_other_dims + (-1, ite... | db3f89381e0c96bb46918ba47155058f9f6d3ce5 | 51,652 |
def getW(D, K, Mu = 0.5):
"""
Return affinity matrix
:param D: Self-similarity matrix
:param K: Number of nearest neighbors
:param Mu: Nearest neighbor hyperparameter (default 0.5)
"""
#W(i, j) = exp(-Dij^2/(mu*epsij))
DSym = 0.5*(D + D.T)
np.fill_diagonal(DSym, 0)
Neighbs = np.... | 755cc96b69ba220f237cc98f68efa28aa0fcc7c8 | 51,654 |
def handle(f):
"""Handles exception in wrapped function and writes to LOG."""
@func.wraps(f)
def f_handle(*args, **kwargs):
try:
return f(*args, **kwargs)
except Exception as e:
LOG.exception(e)
return f_handle | 8c374c12502580ad54962ca425ac4970f6eb4678 | 51,655 |
def tess_flux_to_mag(flux):
"""Convert flux from TESS observation to magnitude."""
# Based on https://heasarc.gsfc.nasa.gov/docs/tess/observing-technical.html#saturation
# TESS CCDs produce 15000 e/s for magnitude 10 light source
if isinstance(flux, u.Quantity):
flux_raw = flux.to(u.electron / ... | 7c36a5d05c862db8d9b2a9378e68b4c876a3bbb3 | 51,657 |
from typing import Callable
from typing import Any
from typing import Tuple
import re
def to_tuple(
value: str,
split_re: str = r"[\s,]+",
converter: Callable[[str], Any] = str,
max_split: int = 0,
) -> Tuple[Any, ...]:
"""Convert value to a tuple"""
return tuple(
converter(s) for s in... | 43edb406c551d46534602e8a7179f7af95b68e5c | 51,658 |
from typing import Tuple
def geodetic2ecef(
lat: ndarray,
lon: ndarray,
alt: ndarray,
ell: Ellipsoid = None,
deg: bool = True,
) -> Tuple[ndarray, ndarray, ndarray]:
"""
point transformation from Geodetic of specified ellipsoid (default WGS-84) to ECEF
Parameters
----------
lat... | 15047a08cd8e1756b697337fccc93df22dd3a621 | 51,659 |
def calc_bv(mag_pars):
"""Calculate a B-V colour from stellar parameters.
Calculate B-V colour from stellar parameters [EEP, log10(age, yrs), feh,
distance (in parsecs) and extinction] using MIST isochrones.
Args:
mag_pars (list): A list containing EEP, log10(age) in years,
metalli... | 4cc82dd1cb63b1a34046217152530f5ff2acec58 | 51,660 |
from typing import Union
from typing import Any
import json
def jsonext_loads(data: Union[str, bytes]) -> Any:
"""Deserializes a json representation of known objects into those objects.
Parameters
----------
data : str or bytes
The byte-serialized JSON blob.
Returns
-------
Any
... | 3ec6cb411ad27802b5a485fd144123f5ca1c6b59 | 51,662 |
def _add_tests_command(subparsers):
"""
:param subparser:
:return:
"""
parser_tests = subparsers.add_parser('tests',
help='Run unit tests',
description='This command executes all unit tests, among them is an '
... | 80a16652eceab64b7b061c49e094e4686a56182c | 51,663 |
def lu(variables, t):
"""Lu, Jinhu, and Guanrong Chen.
"A NEW CHAOTIC ATTRACTOR COINED."
International Journal of Bifurcation and Chaos 12.3 (2002): 659-661.
DOI: 10.1142/S0218127402004620
"""
x, y, z = variables
a = 36
b = 3
c = 20
dx = -a*x+a*y
dy = c*y-x*z
dz = x*y-b... | b178bcdc596fedc42de2ba0a9a3a9aba2be1216c | 51,664 |
def get_server(url=None, port=None, keyfile=None, certfile=None,verbose=False):
"""
returns an xmlrpc connection to the service a the specified
address
"""
if url:
url_parts = url.split(":")
if len(url_parts) >1:
pass
else:
url = "http://%(url)s:%(por... | 68bd548f2e5df3335b6f91c6cca657822af1c22e | 51,665 |
def vector_info(map, layer=1):
"""Return information about a vector map (interface to
`v.info`). Example:
>>> vector_info('geology') # doctest: +ELLIPSIS, +NORMALIZE_WHITESPACE
{'comment': '', 'projection': 'Lambert Conformal Conic' ... 'south': 10875.8272320917}
:param str map: map name
:para... | b73e5971bb2d2c54c2d5cb5a869a19616518bc36 | 51,666 |
def distance_xy(p1, p2):
"""Calculates 2D distance between p1 and p2. p1 and p2 are vectors of
length >= 2."""
return ((p1[0]-p2[0])**2 + (p1[1]-p2[1])**2)**0.5 | 39fcebfc448f68c61c5b41882d998001cff4bcbb | 51,667 |
def set_image_spec(spec):
"""
Writes new specification for images manipulated or created when needed
:param spec:
:return:
"""
output_spec = ImageSpec()
output_spec.set_format(OpenImageIO.UINT8)
output_spec.width = spec['resolution'][0]
output_spec.height = spec['resolution'][0]
... | 89aca8c1d5abc73c3579134648e75071c41f705c | 51,668 |
from scipy.sparse import coo_array, csr_array
def from_numpy(m):
"""
If m.ndim == 1, returns a Vector
if m.ndim == 2, returns a Matrix
if m.ndim > 2, raises an error
dtype is inferred from m.dtype
"""
if m.ndim > 2:
raise GraphblasException("m.ndim must be <= 2")
try:
exce... | a5376cad97c0fa42b7a77c74993a8106a1ecb80c | 51,669 |
import torch
def percentile_normalize_torch(img: torch.Tensor) -> torch.Tensor:
"""
1-99 percentile normalization per image channel. Numpy version
Args:
-----------
img (torch.Tensor):
Input image to be normalized. Shape (C, H, W)
Returns:
-----------
torch.T... | 0d3851a799e4313689e60d2c0541de5cfcd23511 | 51,670 |
def make_layer(basic_block, num_basic_block, **kwarg):
"""Make layers by stacking the same blocks.
Args:
basic_block (nn.module): nn.module class for basic block.
num_basic_block (int): number of blocks.
Returns:
nn.Sequential: Stacked blocks in nn.Sequential.
"""
layers = []... | 5bb2396c5349b9854b6c0602eb6b8303626562ae | 51,672 |
def get_unique_candidate_list(csv_data):
"""
Returns the unique list of candidates in a dictionary, where key is the candidate name and value is the number of votes.
The votes will all be 0 to begin.
:param csv_data:
:return:
"""
candidate_dict = {}
for row in csv_data:
candidate... | 41dd1a0780609e0e7185e9787e0534d62d88b0af | 51,674 |
def _to_slugs(d):
"""Return structured slugs spec.
"""
f = _slugs_str
return (
_format_slugs_vars(d['env_vars'], 'INPUT') +
_format_slugs_vars(d['sys_vars'], 'OUTPUT') +
f(d['env_safety'], 'ENV_TRANS') +
f(d['env_prog'], 'ENV_LIVENESS') +
f(d['env_init'], 'ENV_IN... | 35355a8c5e0cc925a1aba3a6f3fa88ef1146bbad | 51,675 |
def has_extension_md(filename):
"""Check whether a filename has a valid Markdown extension.
:Example:
>>> has_extension_md('filename.md')
True
>>> has_extension_md('filename.mDown')
True
>>> has_extension_md('filename.rst')
False
"""
return has_extensions(filename, ['.md', '... | 1c7a032d2b7776500356d0b072c57fd085440c71 | 51,676 |
def test_docs():
"""Test that the documentation examples work as expected"""
grader = FormulaGrader(
answers='1+x^2+y',
variables=['x', 'y']
)
assert grader(None, '1+x^2+y')['ok']
grader = FormulaGrader(
answers='1+x^2+y+z/2',
variables=['x', 'y', 'z'],
sampl... | 7588bebc2d73c3fea9db1b8ee196e677e0405837 | 51,677 |
from RubrikPolaris import MyClient
def client(requests_mock, capfd):
"""Client fixture."""
data = {
"access_token": "dummy_token",
"mfa_token": "dummy_token"
}
requests_mock.post(BASE_URL_SESSION, json=data)
capfd.close()
client_obj = MyClient(
domain="rubrik-se-beta",
... | c6eb7591a2c4ed9a5a696b1c35b14270b6c05a7e | 51,679 |
def main(input_file):
"""Solve puzzle and connect part 1 with part 2 if needed."""
# part 1
inp = read_input(input_file)
p1 = part_1_and_2(inp, 3)
print(f"Solution to part 1: {p1}")
# part 2
inp = read_input(input_file)
p2 = part_1_and_2(inp, 4)
print(f"Solution to part 2: {p2}")
... | db7d053f46b8a427e69525caa2d31f5129f0d203 | 51,680 |
def pooling_overlap(mat, ksize, stride=None, method='max', pad=False):
"""Overlaping pooling"""
m, n = mat.shape[:2]
ky, kx = ksize
if stride is None:
stride = (ky, kx)
sx, sy = stride
_ceil = lambda x, y : int(np.ceil(x/float(y)))
if pad:
ny = _ceil(m, sy)
nx = _ce... | 5493c79914ec4bf707e508f4856bd3d08cbff35c | 51,681 |
import urllib
def img_query(iurl):
"""
Download an image file from a URL.
Returns the bytes object with the raw image data if successful and
None if image couldn't be downloaded. This function does NOT perform
retries. It only performs one attempt, without any delays. Use
isbndb_query() for the full q... | 0c9f67154bcd8cb794712251303677c034215506 | 51,682 |
def login():
"""
Login User
----------
first if user is already logged in, we redirect them to main page
after extract email and password from login form;
we check if the email is in db or not, otherwise app flashes a message
also we compare the given password with decoded hash that is in da... | bad65adb959160c4a40298233cf741a9f929f79c | 51,683 |
def test_read_XML_04():
"""Test XML file import: Includes duplicate reaction."""
rc = chemkin.ReactionRate()
try:
f = rc.read_XML('./data/rxns_test/rxns_test_04.xml')
return f
except NotImplementedError as err:
assert(type(err) == NotImplementedError) | 24c9d3b2f1367b5577fe5beaedd8ca5cdd849176 | 51,684 |
import math
def vectorMagnitude(vector = None):
"""Calculates the length of the vector"""
return math.sqrt(pow(vector[0],2) + pow(vector[1],2) + pow(vector[2], 2)) | b9bcb247abd5b273e492a4578bceaabddbbf5529 | 51,685 |
def find_vx_vy_new(m):
"""
Given three points (origin, v1, v2), finds out which of v1, v2 is vx and vy.
Input: A 2x3 matrix (origin, v1, v2)
Output: A 2x3 matrix (origin, vx, vy)
"""
# The standard coordinate system
positive_x = np.array([1,0])
positive_y = np.array([0,1])
... | 371a8c5507beae76c90f9b5497d947a5f8d5d793 | 51,686 |
def get_stops():
"""Return stops suggestion by name."""
query = request.args.get("query", "")
limit = request.args.get("limit", type=int, default=10)
stops = Stops.get_stops_by_text(query, limit)
if isinstance(stops, list) and len(stops) == 0:
stops = Stops.get_stops_by_text_regex(query, li... | 7ce820a0388b95298fd6b15b6ec9f85c3b2d43ae | 51,687 |
import math
def Vabrms_calc(va,vb):
"""Inverter terminal voltage - line to line RMS"""
return abs(va-vb)/math.sqrt(2) | aeb9b30990513f88d4a671c7de035d0a5cd64296 | 51,689 |
from typing import List
from typing import Union
def get_common_movies(your_list: List) -> Union[str, List]:
"""
Checks if two characters were detected on the SWAPI database;
if the result is positive, then it returns the common movies
where both characters appeared.
"""
if len(your_list) in... | 04969de96e1d31e5490d184e2977ba74761f2b0c | 51,690 |
import json
import hashlib
def get_settings_md5(settings):
"""Produces an md5 hash of the settings dict"""
flat_settings = flatten_settings(settings)
settings_str = json.dumps(flat_settings, allow_nan=False, sort_keys=True)
h = hashlib.md5()
h.update(settings_str.encode())
return h.hexdigest() | f465dda20c48fb72b9278ff3d1c381850cb30c13 | 51,691 |
import re
def get_value(text, regex, value_type=float):
"""Dump a value from a file based on a regex passed in."""
pattern = re.compile(regex, re.MULTILINE)
results = pattern.search(text)
if results:
return value_type(results.group(1))
else:
print("Could not find the value {}, in t... | 6c4b9990dab2d8fe9f55c7a8f8c97011d3857b01 | 51,693 |
def concat(*arrays):
""" Concatenate a sequence of (up to 2D) array-like objects along a given axis.
"""
array_list = []
for ia, array in enumerate(arrays):
arrdim = np.ndim(array)
if arrdim == 1:
array = np.asarray(array)[None,...]
array_list.append(array)
re... | 720841576ea1f7dd2cdb202e44484e3618f895d9 | 51,694 |
from typing import cast
def ca_migration_continue_session_negotiation(
target_session, input_step, input_data, input_session_ouid=None
):
"""
Runs CA_MigrationContinueSessionNegotiation
:param int target_session: Session handle
:param int input_step: TBD
:param bytes input_data: TBD
:para... | a8f9986a957c7f1a1a919c41ffef0e676ad32b47 | 51,695 |
def numberofdupes(string, idx):
"""return the number of times in a row the letter at index idx is duplicated"""
# "abccdefgh", 2 returns 1
initial_idx = idx
last = string[idx]
while idx+1 < len(string) and string[idx+1] == last:
idx += 1
return idx-initial_idx | e5b9aa310c821683632dbec1ce3ab9a8bf8a08b7 | 51,696 |
def check_timestamp(value):
"""
Checks that the value is a valid HL7 timestamp
:param value: the value to check
:return: `True` if the value is correct, `False` otherwise
"""
try:
get_timestamp_info(value)
except ValueError:
return False
return True | f2bfdde9129d449a9c37d9cb3f92035a03b43e8a | 51,698 |
import functools
def ensure_cls(cls, *containers, key_converter=None):
"""If the attribute is an instance of cls, pass, else try constructing."""
def converter(val):
val = val if isinstance(val, cls) else cls(**val)
return val
def converter_list(converter, val):
return [converter(... | e243b19ff0d673c4792d6d234313da9373cad065 | 51,699 |
def loadCompareDirs(directories, runparamname='runparams.json'):
"""
Loads final results and run parameters of two comparison directories
"""
runPars = loadRunPars(directories, runparamname)
paramnames = [p.get('paramname', None) for p in runPars]
fs = loadResults(directories, paramnames... | 60b5a3969eb56b8888fafae668a8b2710517cbf6 | 51,701 |
import requests
def get_info(mid):
"""
获取粉丝数量
:param mid: 用户ID
:return: 返回关注数量和粉丝数量
"""
headers = {
'Connection': 'keep-alive',
'Cookie': COOKIE,
'Host': 'api.bilibili.com',
'Referer': 'https://space.bilibili.com/' + str(mid),
'User-Agent': 'Mozilla/5.0 ... | 147ed6362676af1caa3ac5e0fa587ec5b965348f | 51,703 |
def _advapi32_encrypt(cipher, key, data, iv, padding):
"""
Encrypts plaintext via CryptoAPI
:param cipher:
A unicode string of "aes", "des", "tripledes_2key", "tripledes_3key",
"rc2", "rc4"
:param key:
The encryption key - a byte string 5-16 bytes long
:param data:
... | 2399ffa6da771552a96538e646a1320d4eb5eedf | 51,704 |
def process(request):
"""processes the input url and sends the date
to web page for rendering
"""
try:
url = request.POST['url'].strip()
title, data = process_utility.get_data(url)
return render(request,constants.FEEDS_TEMPLATE, {"title":title,"data":data})
except Exception... | bbeccd2d666b14f6c53da6de4ad6f8e44bdaadba | 51,705 |
def rotscan(proj, N_steps, slice_mode = False):
"""
The function combines rotaxis_rough() and rotaxis_precise()
It does three iterations to find the best match for the rotation axis
It also finds the inclination of the rotation axis
Parameters
__________
projections: 3D array
0 d... | ed4aa524fbff1d9c86258eb5f1e062c4ab49fe81 | 51,706 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.