content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def success_checks(successf):
"""Return an action collection with a successing check"""
au = ActionUnit("SuccessUnit", "this unit should always succeed", successf)
return ActionCollection([au]) | 277a392c6d577965511b0c1da4230358ee418431 | 3,606,700 |
def _handle_split_region(split_roi, until_eof=False):
""" Checks format against `until_eof` and creates the Roi object
Args:
split_roi (:py:obj:`list` or :py::obj:`tuple`): the contig, start, and stop information.
until_eof (bool): whether or not to allow access to end of reference or file (whi... | 61f516aebe7d92f55a3474756e644c0db29fc00b | 3,606,701 |
def register(disp,host,info):
""" Perform registration on remote server with provided info.
disp must be connected dispatcher instance.
Returns true or false depending on registration result.
If registration fails you can get additional info from the dispatcher's owner
attributes lastErrNode, lastErr and lastE... | fe7f157a61faf89e3519568b73c4f7ffd0decca5 | 3,606,702 |
from typing import Sequence
import torch
def reference_reduction_numpy(f, supports_keepdims=True):
"""Wraps a NumPy reduction operator.
The wrapper function will forward dim, keepdim, mask, and identity
kwargs to the wrapped function as the NumPy equivalent axis,
keepdims, where, and initiak kwargs, ... | 5e982f6763a72ee12885cd8c5f7a5c3cec5438ab | 3,606,703 |
def get_tree_ctrl_image(file_path, file_type=wx.BITMAP_TYPE_PNG, width=16, height=16):
"""
Create an image top be used in the TreeCtrl from the provided file_path
:param file_path: absolute file_path of image
:type file_path: str
:param file_type: specify the image format (PNG by default)
:param... | a1c9b6146535e45cbfc61dc39bcbb242c485014d | 3,606,704 |
def copy_seat_allocations(flight_id, allocations):
"""
Re-apply a set of seat allocations
:param flight_id: ID for the flight to apply the allocations to
:param allocations: A list of (seat number, passenger ID) tuples for the seat allocations to apply
:return: A list of passenger IDs for passenge... | cc3a0dee1338dfc7ce91d8386e5cc31fbc18c034 | 3,606,705 |
from typing import Iterable
def delete_states_rows(state_ids: Iterable[int]) -> StatementLambdaElement:
"""Delete states rows."""
return lambda_stmt(
lambda: delete(States)
.where(States.state_id.in_(state_ids))
.execution_options(synchronize_session=False)
) | 0538a67f78da9b624b9c0dc96b17b1c01431fcfa | 3,606,706 |
def add_navnode(request, tree):
"""Add a new node"""
response = {}
# get the type of object
object_type = request.POST['object_type']
if object_type:
app_label, model_name = object_type.split('.')
content_type = ContentType.objects.get(app_label=app_label, model=model_name)
... | c6da07c7762bd679d910e4002b8d782103ee45fe | 3,606,707 |
def get_control_colors():
"""
Returns control colors available in DCC
:return: list(tuple(float, float, float))
"""
return list() | 3629fdd069353e4916ba23e172299e96e389b824 | 3,606,708 |
def parse_arg_type(arg, type):
"""Parses argument to corresponding type, if not already.
Parameters
----------
arg:
Argument
type:
Required type of the argument
"""
if arg is not None:
if not isinstance(arg, type):
if type == bool:
arg = bool(strtobool(arg))
else:
... | ec604d47f5581fbd8a9407c349f5007bceb1eef3 | 3,606,709 |
import torch
def _pre_conv(input, weight, bias=None, stride=1, padding=0, dilation=1, groups=1):
"""
This is a block of local computation done at the beginning of the convolution. It
basically does the matrix unrolling to be able to do the convolution as a simple
matrix multiplication.
Because al... | be27cb73d5dd7480da477b46c3fa64a32feee744 | 3,606,710 |
import fsspec
import os
def download(source_url: str, cache_location: str) -> str:
"""
Download a remote file to a cache.
Parameters
----------
source_url : str
Path or url to the source file.
cache_location : str
Path or url to the target location for the source file.
Retu... | b0d068e26140b284067f072dddfb327e6e89cfba | 3,606,711 |
def regionvit_small_224(pretrained=False, progress=True, **kwargs):
"""
Constructs the RegionViT-Small-224 model.
.. note::
RegionViT-Small-224 model from `"RegionViT: Regional-to-Local Attention for Vision Transformers" <https://arxiv.org/pdf/2106.02689.pdf>`_.
The required input size of t... | 88e67bf0696ed9f93c8fb8acdea4539150ed86ae | 3,606,712 |
def smallestPrimeFactorv2(num):
"""assumes num is an integer
returns an int, representing the smallest prime factor of num"""
for divisor in range(num):
if checkPrime(divisor):
if num % divisor == 0:
return divisor | 03be01271e97e42456a42959072cbe3f036a976c | 3,606,713 |
def solve_milp_problem(problem, eng, path='./estimation/matlab/matfiles/'):
"""
call m-file with solver function of MIXED-INTEGER LINEAR PROGRAMMING PROBLEM
:param problem: object of problem. It includes objective function,
number of integer variables, inequality matrix, linear inequality constraint
... | 50e61bba1a158d0b0a43819f83d5f3c625a53de5 | 3,606,714 |
def read_rms(filename):
"""Read back the RMS from one of IRAF's results files."""
with open(filename) as f:
good = []
line = 'a'
while line:
line = f.readline()
if line.startswith('# Xin and Yin fit rms:'):
linesplit = line[:-1].split()
... | 7d26d4aae90dbdaddc6248c5f538a57b89375fdd | 3,606,715 |
def validateAccessList(expectedUserTypes):
"""
Validate that the user is logged in, use the information in the
session data to determine if their username is valid and one of the
expectedUserTypes, return boolean, True if valid, False if invalid
"""
if 'email' not in session or session['email'] ... | 1f5dba60589ff7aca5f578c6e3f01837a6038d14 | 3,606,716 |
async def async_unload_entry(hass, entry):
"""Unload a config entry."""
LOGGER.error("async_unload_entry %s", entry.data)
bridge = hass.data[DOMAIN].pop(entry.entry_id)
return await bridge.async_reset() | 4c5ddbaa98734317c90195254da81f5ec47cf95f | 3,606,717 |
def get_version_info():
"""Retrieve version details from current Git HEAD."""
repository = git.Repo(search_parent_directories=True)
return {"author": repository.head.object.author.email, "hash": repository.head.object.hexsha} | 88f6d5f9cc18386e1928c67a9a0d9b0d882af99a | 3,606,718 |
def read_file(file_path, offset, numbytes):
"""reads from all chunk?"""
master = f"localhost:{Config.master_loc}"
with grpc.insecure_channel(master) as channel:
stub = gfs_pb2_grpc.MasterServerToClientStub(channel)
st = file_path + "|" + str(offset) + "|" + str(numbytes)
req = gfs_pb... | 6a3e1076f288daed65e3f1e6afe568356b8d24b9 | 3,606,719 |
def scoreMatrix(mms):
"""
Returns (rowNames, columnNames, S)
where:
- S is a matrix where S_{ij} represents the score delta
of mutation j against read i
- rowNames[i] is an identifier name for the the read i---presently
we use the the row number within the cmp.h5, encoded as a s... | 300786414006cb029c39b10411bb6ad3967f89a9 | 3,606,720 |
def generate_html_from_template(name, data=None):
"""Returns html using a template data
Args:s
name(str): The name of the template
data(dict): Data contain
Returns:
(str): String containing the html
"""
template = get_template(name)
return template.render(data) | 17e3e062352d80fe613becb37c3da92e36ac7b24 | 3,606,721 |
def graph_with_labels() -> StructureGraph:
"""Create a Graph objects that represents the same graph as the previous fixture
but with labels of different sizes
"""
graph = StructureGraph()
# Create the nodes first in order to set their labels
graph.add_node("1", width=3)
graph.add_node("2", w... | 61850d6249fed93fd2f4f85856e1f1caab07b1cf | 3,606,722 |
def unique_permutations(elements):
"""
Get all unique permutations of a list of elements
Parameters
----------
elements : list
a list containing the elements
"""
n = len(elements)
uniques = list(set(elements))
nu = len(uniques)
if not elements:
return []
eli... | 181e454905cda19c2247a80513a0314297fa915f | 3,606,723 |
def add_new_last_layer(base_model, nb_classes):
"""Add last layer to the convnet
Args:
base_model: keras model excluding top
nb_classes: # of classes
Returns:
new keras model with last layer
"""
x = base_model.output
x = GlobalAveragePooling2D()(x)
x = Dense(128, acti... | bdabed131283e3f166e2d368191e4630d3717cb0 | 3,606,724 |
def SteadyBEM(Omega,pitch,V0,xdot,u_turb,
nB, cone, r, chord, twist, polars, # Rotor
rho=1.225,KinVisc=15.68*10**-6, # Environment
nItMax=100, aTol=10**-6, bTipLoss=True, bHubLoss=False, bAIDrag=True, bTIDrag=True, bSwirl=True, relaxation=0.4, a_init=None, ap_init=None):
""" Run the BEM m... | 9d7270bbac166febd7602cc604b9168010f4aabf | 3,606,725 |
from typing import List
from typing import Tuple
from typing import Union
import logging
import io
def extract_answers_from_files(files: List[Tuple[bytes, str]]) -> List[Tuple[smart_forms_types.FormAnswer, List[List[Union[bytes, None]]]]]:
"""
Processes files, extracting their answers.
The files have to b... | 47caff89f13a51da0e7a5b6a2c50f3a13d3e870f | 3,606,726 |
def dataset_pre_0_3(client):
"""Return paths of dataset metadata for pre 0.3.4."""
project_is_pre_0_3 = int(client.project.version) < 2
if project_is_pre_0_3:
return (client.path / 'data').rglob(client.METADATA)
return [] | 892732100f46c8ad727b91d63d8563181d7a9dbb | 3,606,727 |
def before(min_dist=0, max_dist=INFTY):
"""Returns a function that computes whether a temporal interval is before
another, optionally filtering the time difference to be between
``min_dist`` and ``max_dist`` (inclusive).
The output function expects two temporal intervals (dicts with keys 't1'
and '... | 0e3d2594f5509006fd799cca81f23aee6fdf28b5 | 3,606,728 |
def calc_electronic_entropy(multiplicity):
"""
# Electronic entropy evaluation
# Depends on multiplicity
Calculates the electronic entropic contribution (J/(mol*K)) of the molecule
S_elec = R(Ln(multiplicity)
"""
entropy = GAS_CONSTANT * (np.log(multiplicity))
return entropy | d584d318e65b41fee217f4b5883e7e02f0dbeb2a | 3,606,729 |
import re
def ExtractFromSeqWithAnno(seqWithAnno):#{{{
"""
Extract information from the record seqWithAnno
Return (seqID, anno, seq, seqIdentity, dgscore)
==updated 2013-03-20
"""
posAnnoEnd = seqWithAnno.find('\n')
anno = seqWithAnno[1:posAnnoEnd]
anno = anno.lstrip('>')
seqID = m... | 7e88ebc27e5c69e9527154a341f9e61555df1982 | 3,606,730 |
import copy
def sanitize_slicing(slice_across, slice_relative_position):
"""
Return standardized format for `slice_across` and `slice_relative_position`:
- either `slice_across` and `slice_relative_position` are both `None` (no slicing)
- or `slice_across` and `slice_relative_position` are both lists,... | 1f7c3a0f70ecfc2bc66434d3acde684b499bb35c | 3,606,731 |
def distribution(
symbol="", refid="", token="", version="", filter="", **timeseries_kwargs
):
"""Distribution Obtain up-to-date and detailed information on all new announcements, as well as 12+ years of historical records.
Updated at 5am, 10am, 8pm UTC daily
https://iexcloud.io/docs/api/#distribution... | adefc3d85b687ac734c604a25a2f601a2555a322 | 3,606,732 |
def guinierplot(*args, **kwargs):
"""Make a Guinier plot. This is simply a wrapper around plotsascurve()."""
ret=plotsascurve(*args, **kwargs)
plt.xscale('power',exponent=2)
plt.yscale('log')
return ret | 9e4ab481422a9a39d260d70cfe113adbb8124790 | 3,606,733 |
from typing import Iterable
from typing import List
import os
def create_directory_structure(
directories: Iterable[str],
run_dir: str,
ens_suffix: str,
) -> List[str]:
"""
Construct a directory structure for PyBaCy. The structure is
iteratively created by: `run_dir/dir/ens_suffix`... | 84ed5d8b9e3c24f4fc1757a1511653bd6bb51ed6 | 3,606,734 |
def get_rdtype(ipaddr):
"""
Get the record type 'A' or 'AAAA' for this ipaddr.
:param ipaddr: ip address v4 or v6 (str)
:return: 'A' or 'AAAA'
"""
af = dns.inet.af_for_address(ipaddr)
return 'A' if af == dns.inet.AF_INET else 'AAAA' | b5f8ad8e34eecd97efc13638920e98b48d055a29 | 3,606,735 |
def _root_leastsq(fun, x0, args=(), jac=None,
col_deriv=0, xtol=1.49012e-08, ftol=1.49012e-08,
gtol=0.0, maxiter=0, eps=0.0, factor=100, diag=None,
**unknown_options):
"""
Solve for least squares with Levenberg-Marquardt
Options
-------
col_deri... | 5363788e4ef612797ee77fb02d73c8f94ee44e83 | 3,606,736 |
def _check_traits_for_alloc_request(res_requests, summaries, prov_traits,
required_traits, forbidden_traits):
"""Given a list of AllocationRequestResource objects, check if that
combination can provide trait constraints. If it can, returns all
resource provider internal I... | 443e22bdab9c14cc2a277c6cc20ce0480137892b | 3,606,737 |
def is_dependency_valid(dep: dict, dep_dict: dict) -> bool:
"""
:param dep: a dependency that may or may not be valid or up-to-date
:param dep_dict: a dictionary mapping dependency identifiers to their up-to-date dependency counterparts
:return: a boolean indicating whether the dependency is out-of-date... | 8a5a384ae94152921749d1d93cfe48ce6723e320 | 3,606,738 |
import os
def get_filepaths(directory):
"""
This function will generate the file names in a directory
tree by walking the tree either top-down or bottom-up. For each
directory in the tree rooted at directory top (including top itself),
it yields a 3-tuple (dirpath, dirnames, filenames).
"""... | 4fa8e185c9c840a98c2d62b360d1ba6337b13ec3 | 3,606,739 |
def equations(abs1, abs2, abs3, solvent):
"""Contains absorption constans (coef) and formulas."""
separator = "___________________________________________"
coef = [[10.05, 0.97, 16.36, 2.43, 7.62, 15.39, 1.43, 35.87, 205],
[9.93, 0.75, 16.23, 2.42, 7.51,15.48, 1.3, 33.12, 213],
... | 126dc09f0823bf4ae1e881ef3b6284ca76e81fb3 | 3,606,740 |
def wcov(x: np.ndarray, y: np.ndarray, w: np.ndarray) -> float:
"""
Compute weighted covariance between two arrays.
Parameters
----------
x : (N,) np.ndarray
scalar array
y : (N,) np.ndarray
scalar array
w : (N,) np.ndarray
weights
Returns
-------
float
... | 34f5393a3437240d68bbc1128f8789c4e1ad2919 | 3,606,741 |
def run_publish_from_s3_to_redis(
work_dict):
"""run_publish_from_s3_to_redis
Celery wrapper for running without celery
:param work_dict: task data
"""
label = work_dict.get(
'label',
'')
log.info(f'run_publish_from_s3_to_redis - {label} - start')
response = buil... | 1da7f067b674452918495455ecf8652976aa3c0e | 3,606,742 |
def _url_prefix_to_short(url_pref):
"""Returns the commonly used short abbreviation for a few common URL prefixes."""
return _CONVENTIONAL_URL_SHORTENINGS.get(url_pref) | 0c1c0a3728ad616c1eaaba2afe5b04770278aa2b | 3,606,743 |
import threading
def _open_session_with_timeout(transport):
"""
Helper function which encapsulates a difference between older and
newer Paramiko versions.
For a given paramiko.Transport object, returns a session opened
from the tranport, with a timeout of OPEN_SESSION_TIMEOUT seconds.
New ve... | 04d66e200dfc1a3449ed38f5267e2b65f06cb4ae | 3,606,744 |
import glob
import os
import random
import scipy
def gen_batch_function(data_folder, image_shape):
"""
Generate function to create batches of training data
:param data_folder: Path to folder that contains all the datasets
:param image_shape: Tuple - Shape of image
:return:
"""
def get_batc... | eeb312d5c3b3b5039aaabf5f172b3094413ee248 | 3,606,745 |
def best_promo(order: Order) -> Decimal:
"""Compute the best discount available"""
return max(promo(order) for promo in promos) | ad1284c18bf96a89d6e85d5877124be9ec151699 | 3,606,746 |
def LRPermTest(otuDf, labels, statfunc=_dmeanStat, nperms=999, adjMethod='fdr_bh', seed=110820):
"""Calculates pairwise log ratios between all OTUs and performs
permutation tests to determine if there is a significant difference
in OTU ratios with respect to the label variable of interest.
Parameters
... | 28e23a53ce8e1f3d0bce1f5486095581c0752bac | 3,606,747 |
def get_traitset_map(pop):
"""
Utility method which returns a map of culture ID's (hashes) and the trait set
corresponding to a random individual of that culture (actually, the first one
we encounter).
"""
traitsets = {}
graph = pop.agentgraph
for nodename in graph.nodes():
tra... | c80f1f05e0dd5268990e62e6b87726d5349b53f7 | 3,606,748 |
def is_image_file(filename):
"""Checks if a file is an allowed image extension.
Args:
filename (string): path to a file
Returns:
bool: True if the filename ends with a known image extension
"""
return has_file_allowed_extension(filename, IMG_EXTENSIONS) | b6b72bf54a4266fcce6994423e4418a6d8dd8dfc | 3,606,749 |
def load_image_to_numpy(image_path, mode="RGB"):
"""
Arguments:
image_path (str): Path to an image or mask
mode (str, optional): The mode to convert to
"""
return np.array(Image.open(image_path).convert(mode)) | 0aff5cd0757019bb3eee3543ff4340442c86cc07 | 3,606,750 |
def most_read_creators(num=10):
"""
Returns a QuerySet of the Creators who have the most Readings associated
with their Publications.
Because we're after "most read" we'll only include Creators whose role
was left empty or is 'Author'.
"""
return Creator.objects.by_readings()[:num] | 7e2a1b60c24601e6cb0645846114c92479a11afe | 3,606,751 |
def get_current_term_start(*args, **kwargs):
"""*args and **kwargs passed to timedelta if supplied.
Timedelta with no arguments is identity.
"""
term = Term.objects.first()
if term:
return term.start + timedelta(*args, **kwargs) | 4919ab04381df6a74dfc20a5983ccb106a04b765 | 3,606,752 |
def softmax_loss(user_embeddings, movie_embeddings, labels):
"""Returns the cross-entropy loss of the softmax model.
Args:
user_embeddings: A tensor of shape [batch_size, embedding_dim].
movie_embeddings: A tensor of shape [num_movies, embedding_dim].
labels: A tensor of [batch_size], such that labels[i... | a642e614b44f0c3feac9be62cd2a2f57f2df0aad | 3,606,753 |
def prefix(txt, pref):
"""
Place a prefix in front of the text.
"""
return str(pref) + str(txt) | e9b4efd78f9132f7855cccba84c8a2d4b58ae8bb | 3,606,754 |
from svgutils.compose import Figure, Text
def concatenate_svgs(
svgs,
max_columns=None,
scale=None,
label=False,
size=12,
weight="bold",
inset=(0.1, 0.1),
):
"""Create a grid of SVGs, with a maximum number of columns.
Parameters
----------
svgs : list
Items may be ... | 2f7cdc6c0ea46f1d1f8f6dd64d4ed821719d7a24 | 3,606,755 |
def prettycode(str):
"""Try to beautify a line of code."""
if len(str) < 80:
return str
lparen = str.find('(')
rparen = str.rfind(')')
if lparen < 0 or rparen < 0:
Fatal("Invalid code string")
head = str[ 0 : lparen ]
inner = str[ lparen+1 : rparen ]
tail = str[ rparen+1 : ]
args = inner.spl... | 1803a36b9934ae9d6184edcc437c0a04ae60e4e9 | 3,606,756 |
def color_from_string(s):
""" todo: add more, see matplotlib.colors.cnames """
colors = {'r' : (255, 0, 0), 'g' : (0, 255, 0), 'b' : (0, 0, 255)}
if s in colors:
return colors[s]
else:
ut.fail('unknown color: %s' % s) | c3c0f35571d9248875b65cfdf3763a1b1fb4774b | 3,606,757 |
import json
def get(event, context):
"""
Get All Sheets
"""
sheets_folder = event['sheets_folder']
all_current_sheet_names = get_all_sheets_names_for_a_folder(s3_client, sheets_folder, SHEET_DATA_S3_BUCKET)
return {
"statusCode": 200,
"body": json.dumps({
'result': ... | ffe77e71137287399b35072974ea56b6104a95fb | 3,606,758 |
def filter2():
"""
Returns a 1x1x12x12 matrix filled with a simple corner and shifts of it
"""
f = _get_filter(2)
# Reshape a 12x12 filter to 1x1x12x12
f = np.reshape(_roll_out_rows(f), [1, 1, 12, 12])
return tf.constant(f, tf.complex64) | fd56d3272e73afef5436eb72beb85713760da6be | 3,606,759 |
from typing import Tuple
import torch
import multiprocessing
def build(
task_config: task_config_pb2.TaskConfig
) -> Tuple[
SeqToSeq, int, torch.utils.data.DataLoader, torch.utils.data.DataLoader
]:
"""Builds a ``task_config`` and returns each component.
Args:
task_config: A :py:class:`task_c... | 2b5dbbaf560a3ea4e961e019f553970473da4979 | 3,606,760 |
import os
def GetParser():
"""Creates the argument parser."""
parser = commandline.ArgumentParser()
parser.add_argument('-b', '--boards')
parser.add_argument('--android_bucket_url',
default=constants.ANDROID_BUCKET_URL,
type='gs_path')
parser.add_argument('--andro... | 58d453751a86c298ff8ec2b1c630c03917f8cd19 | 3,606,761 |
def _f_dot_kinematic_car(state: EgoState, vehicle: VehicleParameters) -> EgoState:
"""
Compute x_dot = f(x) for a kinematic car
:param state for which to compute motion model
:param vehicle parameters
"""
lf = vehicle.front_length - vehicle.cog_position_from_rear_axle
lr = vehicle.rear_leng... | a477f9b9e464935d6e2291b946e9ce62b4c827f3 | 3,606,762 |
def _fix_basebox_url(url):
"""
Kinda fix a basebox URL
"""
if not url.startswith('http'):
url = 'http://%s' % url
if not url.endswith('/meta'):
url += '/meta'
return url | 5c1b446809089ae9239c232588b3f6176ec79549 | 3,606,763 |
def floodplain_elevation(
ds_model: xr.Dataset,
adjust_river_d8: bool = False,
connectivity=4,
logger=logger,
**kwargs,
) -> xr.Dataset:
"""Returns a binary floodplain classification and hydrologically adjusted elevation.
Parameters
----------
ds_model : xr.Dataset
Model dat... | d77700ed8a9b592571b9b4ce58022e4a04aa056d | 3,606,764 |
def altair_style(return_colors=True, return_palette=True, **kwargs):
"""
Assigns the plotting style for matplotlib generated figures.
Parameters
----------
return_colors : bool
If True, a dictionary of the colors is returned. Default is True.
return_palette: bool
If True, a... | c5cc1b93a626bcb5fe638b45c9329d9bcf825ae8 | 3,606,765 |
def isinstance_all(iterable, class_or_tuple):
"""
Check if all items of an iterable are instance of
a class ou tuple of classes
>>> isinstance_all(['Hello', 'World'], str)
True
>>> isinstance_all([1, 'Hello'], (str, int))
True
>>> isinstance_all([True, 'Hello', 5], int)
False
""... | 1ea1bf7d66e5436ac429123fef4b33ba92195292 | 3,606,766 |
import pyclbr
def get_module_classes(module_name):
"""Returns all classes in module."""
module_members = pyclbr.readmodule_ex(module_name, [])
module_members = dict(sorted(module_members.items(), key=lambda a: getattr(a, 'lineno', 0)))
module_members = module_members.values()
classes = [x for x i... | 67d0a83d50bec7d40e051447e675824df6c77986 | 3,606,767 |
def _tagging(clip_ending_second, onsets, offsets):
"""
Tag the audio by judging whether the clip contains a dialogue.
If the clip contains dialogues in it, we tag it as 1. Otherwise we tag it as 0.
"""
assert int(clip_ending_second)%DatasetConfig.dataset_clip_time == 0., 'Sorry, there is a length mi... | 397a7410cfe1d6bdda263c9e8168b9145f7b6061 | 3,606,768 |
def get_learn(data, model, name):
"""TODO"""
metrics = get_metrics()
learn = Learner(data, model, metrics=metrics, path="models", model_dir=name)
learn = learn.mixup(stack_y=False).to_fp16()
return learn | e86b3727b1c6816cba78867769bcea395931d464 | 3,606,769 |
def sample_recipe(user,**kwargs):
""" Create and return a sample recipe """
defaults = {
'title':'Sample recipe',
'time_miniutes':10,
'price':5.00
}
defaults.update(kwargs)
return Recipe.objects.create(user = user, **defaults) | 81d731b700c80bcaf3f7ac2c3674443515f3dd7a | 3,606,770 |
import os
def root_dir():
"""
find the root directory for web static files
Returns:
root path for static files
"""
return os.path.join(
os.path.join(
os.path.dirname(os.path.dirname(__file__)),
"web"
),
"static"
) | 3e3f40d501ece43f2f0b58cb25f36ef288b84c74 | 3,606,771 |
import imp
import sys
def main_is_frozen():
"""Return ``True`` if we're running from a frozen program."""
return (
# new py2exe
hasattr(sys, "frozen") or
# tools/freeze
imp.is_frozen("__main__")) | 37871436e0967709f368d5b6c1913c8218bed283 | 3,606,772 |
import sys
def create_nonce(context, ag):
"""
Creates a nonce to this actor for passing to the second actor; the second actor will use the
nonce to message back to the first actor.
:param context:
:return:
"""
try:
rsp = ag.actors.addNone()
except Exception as e:
print(... | 88203803f88d03a6ba4c260000a43379939929a6 | 3,606,773 |
import plistlib
def GetPlistFromExec(cmd, stdin=None):
"""Executes a command and returns a parsed plist from the output.
Args:
cmd: str or sequence, command and optional arguments to execute.
stdin: str, optional, to send to standard in.
Returns:
Dict from plistlib.readPlistFromString.
Raises:
... | b7a7ad78e24fab063c7bb7bc3e509f0369b8b981 | 3,606,774 |
from typing import Optional
from typing import Collection
def resume(
id: Optional[str],
namespaces: Collection[references.NamespacePattern],
clusterwide: bool,
peering_name: str,
) -> None:
""" Resume the resource handling in the operator(s). """
identity = peering.Identity(id... | d03ee817c895fd3388eaa8641838bc7d39d32d4d | 3,606,775 |
from typing import Any
import torch
def _recursive_copy_to_device(value: Any, non_blocking: bool, device: torch.device) -> Any:
"""
Recursively searches lists, tuples, dicts and copies tensors to device if
possible. Non-tensor values are passed as-is in the result.
.. note: These are all copies, so ... | 2778c9e9cfb942cb019eb119e24d1556af6fa48d | 3,606,776 |
def getDivisionsCount(xStarts: [int], yStarts: [int]):
"""
Return the number of division for given starting x and y coordinates
:param xStarts: the x-axis starting coordinates
:param yStarts: the y-axis starting coordinates
:return: number of divisions
"""
return len(xStarts) * len(yStarts) | 5f3f1133917a108ab2ef9546380b5f58dacfa562 | 3,606,777 |
from pathlib import Path
def config(base_config):
""":py:class:`nemo_nowcast.Config` instance from YAML fragment to use as config for unit tests."""
config_file = Path(base_config.file)
with config_file.open("at") as f:
f.write(
"""
vhfr fvcom runs:
host: arbutus.cloud
ssh key: Sal... | adaa1f4d53e912128e665d1915d70b3c9102a4b8 | 3,606,778 |
import random
def make_data(n,m):
"""make_data: prepare matrix of m times n random processing times"""
p = {}
for i in range(1,m+1):
for j in range(1,n+1):
p[i,j] = random.randint(1,10)
return p | 3a51402c3807ab8ca0f1f3386663299a3e254bf1 | 3,606,779 |
def get_errors(job_types=None, error_ids=None, error_names=None):
"""Exports all the errors in the system based on the given filters.
:param job_types: Only include errors that are referenced by the given job types.
:type job_types: list[:class:`job.models.JobType`]
:param error_ids: A list of unique e... | 68e42b99b3ae84098aa63c7cc0f2ce827e3262c5 | 3,606,780 |
import time
from datetime import datetime
import sys
import json
def save_pipeline_parameters(filename, pipeline):
"""
Saving pipeline parameters (inputs and outputs) to a Json file.
"""
def check_value(val):
"""
Checking if the value is a list, Undefined, a date or a time
:pa... | 0e37ee9ac5ed4f118b0495e099dcb184468dff16 | 3,606,781 |
def to_gigabytes(number):
"""Convert a number from KiB to GiB
This is used mainly for the gauge, everything else uses the dynamic
`unit` function.
"""
return number / 1024 ** 2 | d930541627f32415e432fea57da4c0bc2fa7909f | 3,606,782 |
import configparser
def upgrade_config(thelogger, cfg):
"""Upgrade config file if needed."""
try:
cfg.get("settings", "initial-stoploss-percentage")
except configparser.NoOptionError:
cfg.set("settings", "initial-stoploss-percentage", "[]")
with open(f"{datadir}/{program}.ini", "w... | bc6acd5faa86d442d02fe782710d4eeed171fde6 | 3,606,783 |
import os
import traceback
import sys
def get_private_key():
"""Read private key from hidden file and return it."""
if not os.path.exists(_private_key_path):
return None
try:
with open(_private_key_path) as secret_file:
return secret_file.read()
except Exception as exc:
... | d3d0b8c72c05f4363bed7f56f864de383d7dd7f9 | 3,606,784 |
import os
def locs_from_geolife():
"""Create locations from geolife staypoints."""
# read staypoints
spts_file = os.path.join('tests', 'data', 'geolife', 'geolife_staypoints.csv')
spts = ti.read_staypoints_csv(spts_file, tz='utc', index_col='id')
# cluster staypoints to locations
_, ... | 8b1b6ab8e1ba6b6847e0197dba75ae1bf1411d53 | 3,606,785 |
from typing import List
def get_bond_pairs(mol: Chem.Mol) -> List[List[int]]:
"""Returns a list of all pairs of atoms that have a bond between each other.
"""
bonds = mol.GetBonds()
res = [[],[]]
for bond in bonds:
res[0] += [bond.GetBeginAtomIdx(), bond.GetEndAtomIdx()]
res[1] +=... | 9c86600757f9a2daff182cf13bf1d818fc63195d | 3,606,786 |
def get_sorted_main_channels(mean_masks, unmasked_channels):
"""Weighted mean of the channels, weighted by the mean masks."""
main_channels = np.argsort(mean_masks)[::-1]
main_channels = np.array([c for c in main_channels
if c in unmasked_channels])
return main_channels | 290a74bc4343e786811dd2ceac8e3a6e968af41b | 3,606,787 |
import torch
def differential(f, A, E):
""" Computes the differential of f at A when acting on E: (df)_A(E) """
n = A.size(0)
M = torch.zeros(2*n, 2*n, dtype=A.dtype, device=A.device, requires_grad=False)
M[:n, :n] = A
M[n:, n:] = A
M[:n, n:] = E
return f(M)[:n, n:] | d424c9fbe7344b3ba4293c1e3e8e192dfa253f66 | 3,606,788 |
import scipy
def convert_sparse(data):
"""Convert columns with sparse data into sparse matrix.
Use sparse related function in Scipy to convert sparse data columns into
sparse matrix.
:param data: Dataframe. The Pandas dataframe to be processed.
:return: Dataframe. The converted dataframe.
"... | 318badefe9a1c6a1cdceaa55766e70ab88f1e999 | 3,606,789 |
def arctan(x):
"""
A generic tangent operator with backend selector
"""
backend = getBackend(x)
if backend == 'scalar':
return np.arctan(x)
elif backend == 'numpy':
return np.arctan(x)
elif backend == 'arrayfire':
return arrayfire.arith.atan(x)
elif backend == 'to... | 848592e2836881c4c3b76e96a2de2bca6a69f265 | 3,606,790 |
def get_distance(vectors):
"""[Calculate the euclidian distance between two vectors,
represented as columns in a DataFrame.]
Args:
vectors ([DataFrame]): [DataFrame containing the
two columns representing the vectors.]
Returns:
[Float]: [Euclidian distance of the vectors.]
... | 761681dd2f63cdd18b5d34bb28dfb8805d4e27d7 | 3,606,791 |
def comp_error_multi_init(x,C,n,*args,**kwargs):
""" computes the expected L1 norm between the empirical probabilities of a
choice set and those inferred by the MMNL with specified parameters
Arguments:
x- tuple of list of MMNL parameters and best parameters
K- number of MNL mixed
C- data for evaluation
"""
... | 9d7f96c6e6d6c3615bb10c399a5905e704ff1cdd | 3,606,792 |
def cal_similarity_matrix(x, y):
"""计算两个向量的增强皮尔逊相关系数
"""
nonzero_x = np.nonzero(x)[0]
nonzero_y = np.nonzero(y)[0]
intersect = np.intersect1d(nonzero_x, nonzero_y) # 交集
# 如果向量交集为空,则相似度为0
# 如果一个向量中所有值都相等,则无法计算皮尔逊相关距离(分母为0)
if len(intersect) == 0 or len(set(x[intersect])) == 1 or len(
... | c52791d9dffd118c45a2147256258293536f7f84 | 3,606,793 |
def cloudfront_distributions():
"""
Retrieve all CloudFront distributions (global).
Tags retrieved.
"""
service = boto3.client("cloudfront", config=MSAM_BOTO3_CONFIG)
response = service.list_distributions()
items = response["DistributionList"]["Items"]
while "NextMarker" in response["Dis... | 068f75000d31a9d50a35701108adc590e0e9f22b | 3,606,794 |
def inference_by_sample(n_steps, control_params):
"""
Returns
-------
output :
indference results
"""
# get input data
placeholders = control_params["placeholders"]
x = placeholders["x"]
pot_points = placeholders["potential_points"]
# get parameters
hy_param = hy.get_hyperparameter()
... | 4a7d0ba7c3724f7fb8eee530da092dc0965cb761 | 3,606,795 |
import torch
def swap_channels(img_1: np.ndarray, img_2: np.ndarray, ch_start: int, ch_end: int, model, swap_levels=None):
"""
rec_img_n1d2 has base of img_2 and selected channels from img_1 are inculcated.
"""
with torch.no_grad():
if swap_levels is None:
swap_levels = [True] * le... | 73f18ff24beeaa6e36635935458387b1fc76a258 | 3,606,796 |
def authorize_role(role=None):
"""
This route is used to ensure sensitive static content is witheld from withheld from clients.
"""
if role == "user" and safe_fail(api.user.get_user):
return "Client is logged in.", 200
elif role == "teacher" and safe_fail(api.user.is_teacher):
retur... | 54889dd6b2167e0ada4f656780b7ce9e85033e08 | 3,606,797 |
def pairwise_rho(X=None, reference_components=None, centroid="mean", interval_type="open", xlr=None, vlr=None):
"""
# Description
Pairwise proportionality `rho` (Erb et al. 2016)
# Parameters
* X: pd.DataFrame or 2D np.array of compositional data (rows=samples, columns=components)
*... | 70785f420a06c5ea9ff4d81baaed069cb3900845 | 3,606,798 |
def draw_polygons(img, polys):
"""Draw polygons on image.
Args:
img (np.ndarray): The original image.
polys (list[list[float]]): Detected polygons.
Return:
out_img (np.ndarray): Visualized image.
"""
dst_img = img.copy()
color_list = gen_color()
out_img = dst_img
... | 64f331348a4d068ff549b6e894949c92b0c0030c | 3,606,799 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.