content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def get_data_upload_id(jwt: str) -> str:
"""Function to get a temporary upload ID from
DAFNI data upload API
Args:
jwt (str): Users JWT
Returns:
str: Temporary Upload ID
"""
url = f"{DATA_UPLOAD_API_URL}/nid/upload/"
data = {"cancelToken": {"promise": {}}}
return dafn... | dcce05a8efda1c90e6a78a19757f57deffd0c247 | 3,653,400 |
def StationMagnitudeContribution_TypeInfo():
"""StationMagnitudeContribution_TypeInfo() -> RTTI"""
return _DataModel.StationMagnitudeContribution_TypeInfo() | d9af45a3bbe993de37c351b5791ba8b87aeeedc9 | 3,653,401 |
def _get_operations(rescale=0.003921, normalize_weight=0.48):
"""Get operations."""
operation_0 = {
'tensor_op_module': 'minddata.transforms.c_transforms',
'tensor_op_name': 'RandomCrop',
'weight': [32, 32, 4, 4, 4, 4],
'padding_mode': "constant",
'pad_if_needed': False,
... | a3bab4147f1a2020fb87853fc30bede277f0f4bd | 3,653,402 |
def itm_command(
ticker: str = None,
):
"""Options ITM"""
# Check for argument
if ticker is None:
raise Exception("Stock ticker is required")
dates = yfinance_model.option_expirations(ticker)
if not dates:
raise Exception("Stock ticker is invalid")
current_price = yfinanc... | b2230ee5f8c520523f7ce844372a4f26d14fe53d | 3,653,403 |
def create_nx_suite(seed=0, rng=None):
"""
returns a dict of graphs generated by networkx for testing,
designed to be used in a pytest fixture
"""
if rng is None:
rng = np.random.RandomState(seed)
out_graphs = {}
for N in [1, 2, 4, 8, 16, 32, 64, 128]:
for dtype in [np... | eb64688850d48b755dc526ed3d64876d04ba3914 | 3,653,404 |
def _nearest_neighbor_features_per_object_in_chunks(
reference_embeddings_flat, query_embeddings_flat, reference_labels_flat,
ref_obj_ids, k_nearest_neighbors, n_chunks):
"""Calculates the nearest neighbor features per object in chunks to save mem.
Uses chunking to bound the memory use.
Args:
refere... | e9b7af295ddfab56f70748e42fb7b06f6192a3ac | 3,653,405 |
import heapq
def heap_pop(heap):
"""
Wrapper around heapq's heappop method to support updating priorities of
items in the queue.
Main difference here is that we toss out any queue entries that have been
updated since insertion.
"""
while len(heap) > 0:
pri_board_tup = heapq.heappo... | c640fd178a399332fc10ccbb55085cb08d118865 | 3,653,406 |
def _variant_po_to_dict(tokens) -> CentralDogma:
"""Convert a PyParsing data dictionary to a central dogma abundance (i.e., Protein, RNA, miRNA, Gene).
:type tokens: ParseResult
"""
dsl = FUNC_TO_DSL.get(tokens[FUNCTION])
if dsl is None:
raise ValueError('invalid tokens: {}'.format(tokens))... | 28e989087a91accf793eaaada2e65a71ee145c32 | 3,653,407 |
def project(name, param):
"""a tilemill project description, including a basic countries-of-the-world layer."""
return {
"bounds": [-180, -85.05112877980659, 180, 85.05112877980659],
"center": [0, 0, 2],
"format": "png",
"interactivity": False,
"minzoom": 0,
"maxz... | 9609c523cccc99168bbc0e7dbf10fe8624d399c2 | 3,653,408 |
def get_deepest():
"""Return tokens with largest liquidities.
Returns:
str: HTML-formatted message.
"""
url = config.URLS['deepest']
api_params = {'limit': 5,
'orderBy': 'usdLiquidity',
'direction': 'desc',
'key': POOLS_KEY
... | c944f20f65dd68716b4f436b02ec5e373c04848f | 3,653,409 |
def _grompp_str(op_name, gro_name, checkpoint_file=None):
"""Helper function, returns grompp command string for operation."""
mdp_file = signac.get_project().fn('mdp_files/{op}.mdp'.format(op=op_name))
cmd = '{gmx} grompp -f {mdp_file} -c {gro_file} {checkpoint} -o {op}.tpr -p'.format(
gmx=gmx_exec,... | 9201bd49fd09ce9faa268d8ea4d33482cea5d7ad | 3,653,410 |
import typing
import argparse
import sys
import os
import asyncio
import signal
def run(
master_cls: typing.Type[master.Master],
make_parser: typing.Callable[[options.Options], argparse.ArgumentParser],
arguments: typing.Sequence[str],
extra: typing.Callable[[typing.Any], dict] = None
... | d8e99b97df0cf69affe4fd8b757a40170dea8074 | 3,653,411 |
def get_role_with_name(role_name: str) -> Role:
"""Get role with given name."""
role = Role.query.filter(Role.name == role_name).one()
return role | e20858ef1bcbb54d2c1d09ba9d3a54bf15dfa658 | 3,653,412 |
def namespace_store_factory(
request, cld_mgr, mcg_obj_session, cloud_uls_factory_session, pvc_factory_session
):
"""
Create a NamespaceStore factory.
Calling this fixture lets the user create namespace stores.
Args:
request (object): Pytest built-in fixture
cld_mgr (CloudManager): ... | cc2d090d8dc0f12d89331ada54e4054e117e544d | 3,653,413 |
def get_user(request, username):
"""
Gets a user's information.
return:
{
status: HTTP status,
name: string,
gender: string,
marital_status: string,
first_name: string
}
"""
data = get_user_info(username)
if data:
... | 9820b441718629780ff72ab00776fc2d4c95a63f | 3,653,414 |
def find_changes(d_before, d_after):
"""
Returns a dictionary of changes in the format:
{
<system id>: {
<changed key>: <Change type>,
...
},
...
}
The changes should describe the differences between d_before and d_after.
... | 02e5eea5ac1264c593d542a8f745a8d3571d5fac | 3,653,415 |
def check_vector_inbetween(v1, v2, point):
""" Checks if point lies inbetween two vectors v1, v2. Returns boolean. """
if (np.dot(np.cross(v1, point), np.cross(v1, v2))) >= 0 and (np.dot(np.cross(v2, point), np.cross(v2, v1))) >= 0:
return True
else:
return False | 6eeaa4a9e37ea345c3399c103dadbc45c306887c | 3,653,416 |
def accuracy(y_preds, y_test):
"""
Function to calculate the accuracy of algorithm
:param y_preds: predictions for test data
:param y_test: actual labels for test data
:return: accuracy in percentage
"""
return np.sum(np.where(y_preds == y_test, 1, 0)) * 100 / len(y_test) | f41522663ae9a35e976f4d848f14e42ef0993fd9 | 3,653,417 |
def get_all(factory='official', **kwargs):
"""Construct and return an list of Class `Event`.
hookを呼び出す.
Args:
factory: `Event` の取得用マネージャ 今のところ,京大公式HP用のみ.
EventFactoryMixin classを継承したクラスか 'official' に対応
date (:obj:`datetime`, optional): 欲しいイベントのdatetime.
`month` , `y... | bc1fabe37fc8065ff5394259607caf32c6345b41 | 3,653,418 |
import docker
import json
import os
import time
from vent.helpers.meta import GpuUsage
def gpu_queue(options):
"""
Queued up containers waiting for GPU resources
"""
status = (False, None)
if (os.path.isfile('/root/.vent/vent.cfg') and os.path.isfile('/root/.vent/plugin_manifest.cfg')):
... | aedbff3959477d7f72a9e1d49d1d338cfade9c46 | 3,653,419 |
def nudupl(f):
"""Square(f) following Cohen, Alg. 5.4.8.
"""
L = int(((abs(f.discriminant))/4)**(1/4))
a, b, c = f[0], f[1], f[2]
# Step 1 Euclidean step
d1, u, v = extended_euclid_xgcd(b, a)
A = a//d1
B = b//d1
C = (-c*u) % A
C1 = A-C
if C1 < C:
C = -C1
# Step ... | 7f5a16c0fc2611a5f9dc0ebde00e3587c188f944 | 3,653,420 |
def remove_schema(name):
"""Removes a configuration schema from the database"""
schema = controller.ConfigurationSchema()
schema.remove(name)
return 0 | e45b415ea6eb57402790b04bbf1fa63749242a77 | 3,653,421 |
def get_unassigned_independent_hyperparameters(outputs):
"""Going backward from the outputs provided, gets all the independent
hyperparameters that are not set yet.
Setting an hyperparameter may lead to the creation of additional hyperparameters,
which will be most likely not set. Such behavior happens... | 6f28f3fcbaf4a875c3a42cdb4fc9ad715c99a093 | 3,653,422 |
def get_theta_benchmark_matrix(theta_type, theta_value, benchmarks, morpher=None):
"""Calculates vector A such that dsigma(theta) = A * dsigma_benchmarks"""
if theta_type == "benchmark":
n_benchmarks = len(benchmarks)
index = list(benchmarks).index(theta_value)
theta_matrix = np.zeros(n... | aa84006b7a69faa8803ecea20ffd24e35f178185 | 3,653,423 |
import os
import re
import importlib
def get_plugins(plugin_dir=None):
"""Load plugins from PLUGIN_DIR and return a dict with the plugin name
hashed to the imported plugin.
PLUGIN_DIR is the name of the dir from which to load plugins. If
it is None, use the plugin dir in the dir that holds this func... | fd9861233b08141a522628a59081ae9f255dc958 | 3,653,424 |
def reorder_points(point_list):
"""
Reorder points of quadrangle.
(top-left, top-right, bottom right, bottom left).
:param point_list: List of point. Point is (x, y).
:return: Reorder points.
"""
# Find the first point which x is minimum.
ordered_point_list = sorted(point_list, key=lambd... | 8ef3466616ecf003750cce7e1125d913d258cf15 | 3,653,425 |
import torch
def ppg_acoustics_collate(batch):
"""Zero-pad the PPG and acoustic sequences in a mini-batch.
Also creates the stop token mini-batch.
Args:
batch: An array with B elements, each is a tuple (PPG, acoustic).
Consider this is the return value of [val for val in dataset], where
... | 1357a8a9fa901a9be4f79ea13fd5ae7c3810bbeb | 3,653,426 |
def problem004():
"""
Find the largest palindrome made from the product of two 3-digit numbers.
"""
return largest_palindrome_from_product_of_two_n_digit_numbers(3) | 516c98d75ac2b4e286e58ea940d49c1d2bcd2dc7 | 3,653,427 |
import torch
def residual_l1_max(reconstruction: Tensor, original: Tensor) -> Tensor:
"""Construct l1 difference between original and reconstruction.
Note: Only positive values in the residual are considered, i.e. values below zero are clamped.
That means only cases where bright pixels which are brighter... | 8649b1947845c0e3f9e57c0ec2e68d7bed94be5d | 3,653,428 |
def build_url(path):
"""
Construct an absolute url by appending a path to a domain.
"""
return 'http://%s%s' % (DOMAIN, path) | fa9df465607082993571ca71c576d7b250f6cc76 | 3,653,429 |
def get_registration_url(request, event_id):
"""
Compute the absolute URL to create a booking on a given event
@param request: An HttpRequest used to discover the FQDN and path
@param event_id: the ID of the event to register to
"""
registration_url_rel = reverse(booking_create, kwargs={"event_i... | d8b344c6574a120d365a718934f5dc0e78173a6f | 3,653,430 |
def create_no_args_decorator(decorator_function,
function_for_metadata=None,
):
"""
Utility method to create a decorator that has no arguments at all and is implemented by `decorator_function`, in
implementation-first mode or usage-first mode.
T... | 7067974d7bd15c238968f78aa0057086458940bf | 3,653,431 |
import os
def load_electric_devices_segmentation():
"""Load the Electric Devices segmentation problem and returns X.
We group TS of the UCR Electric Devices dataset by class label and concatenate
all TS to create segments with repeating temporal patterns and
characteristics. The location at which dif... | 06533351c0a95e6de041389766dc8dbd1d0c70fd | 3,653,432 |
import torch
def compute_batch_jacobian(input, output, retain_graph=False):
"""
Compute the Jacobian matrix of a batch of outputs with respect to
some input (normally, the activations of a hidden layer).
Returned Jacobian has dimensions Batch x SizeOutput x SizeInput
Args:
input (list or t... | c18f596a3500f2f82e2b4716e6f9892a01fb31c7 | 3,653,433 |
def is_associative(value):
"""Checks if `value` is an associative object meaning that it can be
accessed via an index or key
Args:
value (mixed): Value to check.
Returns:
bool: Whether `value` is associative.
Example:
>>> is_associative([])
True
>>> is_ass... | 5d2a9e0e69ad793a98657dc13b26f79900f29294 | 3,653,434 |
def join_audio(audio1, audio2):
"""
>>> join_audio(([1], [4]), ([2, 3], [5, 6]))
([1, 2, 3], [4, 5, 6])
"""
(left1, right1) = audio1
(left2, right2) = audio2
left = left1 + left2
right = right1 + right2
audio = (left, right)
return audio | 23348b746469d362fd66371d61142b4227814ff3 | 3,653,435 |
def csi_from_sr_and_pod(success_ratio_array, pod_array):
"""Computes CSI (critical success index) from success ratio and POD.
POD = probability of detection
:param success_ratio_array: np array (any shape) of success ratios.
:param pod_array: np array (same shape) of POD values.
:return: csi_array: ... | 84952fe6f7c8bd780c64c53183342ab0d8f3f90f | 3,653,436 |
import sys
def portrait_plot(
data,
xaxis_labels,
yaxis_labels,
fig=None,
ax=None,
annotate=False,
annotate_data=None,
annotate_fontsize=15,
annotate_format="{x:.2f}",
figsize=(12, 10),
vrange=None,
xaxis_fontsize=15,
yaxis_fontsize=15,
cmap="RdBu_r",
cmap_b... | 293897dd09644969ae00f61000b603a5fe2d06ae | 3,653,437 |
def compute_secondary_observables(data):
"""Computes secondary observables and extends matrix of observables.
Argument
--------
data -- structured array
must contains following fields: length, width, fluo, area, time
Returns
-------
out -- structured array
new fields are ad... | 7141d16a579e4b629e25fee3a33c9a844a08e48f | 3,653,438 |
def get_account_number(arn):
"""
Extract the account number from an arn.
:param arn: IAM SSL arn
:return: account number associated with ARN
"""
return arn.split(":")[4] | 3d0fe552691ae98cf0dc70bc2055297f01a5d800 | 3,653,439 |
def get_hashtags(tweet):
"""return hashtags from a given tweet
Args:
tweet (object): an object representing a tweet
Returns:
list: list of hastags in a tweet
"""
entities = tweet.get('entities', {})
hashtags = entities.get('hashtags', [])
return [get_text(tag) for tag in ha... | ef222d64294c62d27e86a4c8520bb197701ed1af | 3,653,440 |
import logging
import asyncio
from typing import cast
from typing import Dict
from typing import List
async def get_organization_catalogs(filter: FilterEnum) -> OrganizationCatalogList:
"""Return all organization catalogs."""
logging.debug("Fetching all catalogs")
async with ClientSession() as session:
... | 30245f4e20156b1b5e580e72ec8d5c0f926fcb2b | 3,653,441 |
def get_appliance_ospf_neighbors_state(
self,
ne_id: str,
) -> dict:
"""Get appliance OSPF neighbors state
.. list-table::
:header-rows: 1
* - Swagger Section
- Method
- Endpoint
* - ospf
- GET
- /ospf/state/neighbors/{neId}
:param n... | 25a985ccf8b00ee3f27ea43d2a8371eef2443963 | 3,653,442 |
import os
def filter_toolchain_files(dirname, files):
"""Callback for shutil.copytree. Return lists of files to skip."""
split = dirname.split(os.path.sep)
for ign in IGNORE_LIST:
if ign in split:
print('Ignoring dir %s' % dirname)
return files
return [] | 1b8f4a9ca0b0828cb76a2b5de27f0b69715cf7e0 | 3,653,443 |
def info(obj):
"""Return info on shape and dtype of a numpy array or TensorFlow tensor."""
if obj is None:
return 'None.'
elif isinstance(obj, list):
if obj:
return 'List of %d... %s' % (len(obj), info(obj[0]))
else:
return 'Empty list.'
elif isinstance(obj, tuple):
if obj:
ret... | 64ffab112b0f0397541f8661a861a958c8ccf26e | 3,653,444 |
def first_index_k_zeros_left(qstr, k, P):
"""
For a binary string qstr, return the first index of q with k (mod P) zeros to the left.
Return: index in [0, qstr.length]
"""
num_zeros_left = 0
for j in range(qstr.length+1):
if (num_zeros_left - k) % P == 0:
return j
if ... | 62e505290fb32b43860deae3477dec718028e7af | 3,653,445 |
def transform_points(points, transf_matrix):
"""
Transform (3,N) or (4,N) points using transformation matrix.
"""
if points.shape[0] not in [3, 4]:
raise Exception("Points input should be (3,N) or (4,N) shape, received {}".format(points.shape))
return transf_matrix.dot(np.vstack((points[:3, ... | f478dfdfe41c694ada251deca33820336001d61e | 3,653,446 |
def get_lat_long(zip):
"""
This function takes a zip code and looks up the latitude and longitude using
the uszipcode package. Documentation: https://pypi.python.org/pypi/uszipcode
"""
search = ZipcodeSearchEngine()
zip_data = search.by_zipcode(zip)
lat = zip_data['Latitude']
long =... | 4fa8dc583bba9a6068db58ab86c2cab5f310edc4 | 3,653,447 |
def propose_perturbation_requests(current_input, task_idx, perturbations):
"""Wraps requests for perturbations of one task in a EvaluationRequest PB.
Generates one request for each perturbation, given by adding the perturbation
to current_input.
Args:
current_input: the current policy weights
task_idx... | 279da36eb633005c8f8ee79e66b71b3bdf8783f3 | 3,653,448 |
import google
def id_token_call_credentials(credentials):
"""Constructs `grpc.CallCredentials` using
`google.auth.Credentials.id_token`.
Args:
credentials (google.auth.credentials.Credentials): The credentials to use.
Returns:
grpc.CallCredentials: The call credentials.
"""
reque... | 433bb494d9f8de529a891f529a42f89af0b5ef77 | 3,653,449 |
import time
def test_analyze(request,hash,db_name):
"""
Get features of a sequence, using the sequence's sha-1 hash as the
identifier.
"""
db = blat.models.Feature_Database.objects.get(name=db_name)
sequence = blat.models.Sequence.objects.get(db=db,hash=hash)
ts = int(time.mktime(sequence.... | 173ebb356167558cb64a35265caa39e828a43bae | 3,653,450 |
from typing import List
def _collect_scaling_groups(owner: str) -> List:
"""Collect autoscaling groups that contain key `ES_role` and belong to the specified owner"""
client = boto3.client("autoscaling")
print("Collecting scaling groups")
resp = client.describe_auto_scaling_groups()
assert "NextT... | f1f75e6158450aaef834a910f8c36bb8812b1ede | 3,653,451 |
def cross_entropy_loss(logits, labels, label_smoothing=0., dtype=jnp.float32):
"""Compute cross entropy for logits and labels w/ label smoothing
Args:
logits: [batch, length, num_classes] float array.
labels: categorical labels [batch, length] int array.
label_smoothing: label smoothing ... | 7b6ce3145bc85433e54cef0ac85570eeb0fe7230 | 3,653,452 |
import torch
def set_optimizer(name, model, learning_rate):
"""
Specify which optimizer to use during training.
Initialize a torch.optim optimizer for the given model based on the specified name and learning rate.
Parameters
----------
name : string or None, default = 'adam'
The name... | 5c1a5e836176b90506ca6344c01ce6828b43d917 | 3,653,453 |
import httplib
import urllib
def get_http_url(server_path, get_path):
"""
Вариант с использованием httplib напрямую; ничем не лучше urllib2
server_path = "example.com"
get_path = "/some_path"
"""
# urllib - более высокого уровня библиотека, которая в случае http использует
# httplib;
... | d759609b1c48af28e678fa75bd9ff102f7eaafae | 3,653,454 |
def not_found_view(request):
"""Not Found view.
"""
model = request.context
return render_main_template(model, request, contenttile='not_found') | 0fe250d09f8fc007ffb07f848e59e779da9aefb0 | 3,653,455 |
import torch
def top_filtering(
logits, top_k=0, top_p=0.0, threshold=-float("Inf"), filter_value=-float("Inf")
):
""" Filter a distribution of logits using top-k, top-p (nucleus) and/or threshold filtering
Args:
logits: logits distribution shape (vocabulary size)
top_k: <=0: n... | 7b230fc959e0078f1cfc5b2f2f991c79e0f4fd86 | 3,653,456 |
def get_physical_type(obj):
"""
Return the physical type that corresponds to a unit (or another
physical type representation).
Parameters
----------
obj : quantity-like or `~astropy.units.PhysicalType`-like
An object that (implicitly or explicitly) has a corresponding
physical t... | 03d28bdb9a507939e52bc0021dae3c539b4954a5 | 3,653,457 |
def reverse(list):
"""Returns a new list or string with the elements or characters in reverse
order"""
if isinstance(list, str):
return "".join(reversed(list))
return _list(reversed(list)) | ba74d9e4e54782114f534fb4c888c681ab708b67 | 3,653,458 |
from typing import Dict
def PubMedDiabetes(
directed: bool = False,
preprocess: bool = True,
load_nodes: bool = True,
verbose: int = 2,
cache: bool = True,
cache_path: str = "graphs/linqs",
version: str = "latest",
**additional_graph_kwargs: Dict
) -> Graph:
"""Return new instance ... | ddac0cfb8a525c42fe5a8d6c1a70677ab57451e0 | 3,653,459 |
def find_neighbor_indices(atoms, probe, k):
"""
Returns list of indices of atoms within probe distance to atom k.
"""
neighbor_indices = []
atom_k = atoms[k]
radius = atom_k.radius + probe + probe
indices = list(range(k))
indices = indices + list(range(k+1, len(atoms)))
for i in ind... | 05c3218357d660d6b66c3d614bfcb0d78431d32e | 3,653,460 |
def genDir(EAs):
"""
Generate the projection direction given the euler angles. Since the image
is in the x-y plane, the projection direction is given by R(EA)*z where
z = (0,0,1)
"""
dir_vec = np.array([rotmat3D_EA(*EA)[:, 2] for EA in EAs])
return dir_vec | 0753fad9638ca8b0ac4e899ad103dc08266a208b | 3,653,461 |
def plainica(x, reducedim=0.99, backend=None, random_state=None):
""" Source decomposition with ICA.
Apply ICA to the data x, with optional PCA dimensionality reduction.
Parameters
----------
x : array, shape (n_trials, n_channels, n_samples) or (n_channels, n_samples)
data set
reduced... | 7ffe9ebc78220898c84459fed61fc0f32fe05e69 | 3,653,462 |
import json
import math
import copy
import os
import itertools
def make_spectrum_layout(obj, spectra, user, device, width, smoothing, smooth_number):
"""
Helper function that takes the object, spectra and user info,
as well as the total width of the figure,
and produces one layout for a spectrum plot.... | d99ec2027eaea46283d0581e7f48942c61bf22c0 | 3,653,463 |
def all_equal(values: list):
"""Check that all values in given list are equal"""
return all(values[0] == v for v in values) | 8ed08f63959367f3327554adc11b1286291963d8 | 3,653,464 |
def _tester(func, *args):
"""
Tests function ``func`` on arguments and returns first positive.
>>> _tester(lambda x: x%3 == 0, 1, 2, 3, 4, 5, 6)
3
>>> _tester(lambda x: x%3 == 0, 1, 2)
None
:param func: function(arg)->boolean
:param args: other arguments
:return: something or none
... | 035c8bf68b4ff7e4fbdb7ed1b2601f04110287d8 | 3,653,465 |
from datetime import datetime
def new_revision(partno):
"""
Presents the form to add a new revision, and creates it upon POST submit
"""
_load_if_released(partno) # ensures the component exists and is released
form = RevisionForm(request.form)
if request.method == 'POST' and form.validate_on_... | 722a3860e9daeb4bd5d9339f7dcaf5245c51b5de | 3,653,466 |
def fresnel_parameter(rays, diffraction_points):
""" returns the fresnel diffraction parameter (always as a positive)
Parameters
----------
rays : [n] list of shapely LineString (3d)
diffraction_points: [n] list of Points (3d)
diffraction point which the ray is rounding
Returns
---... | cd398797161f1e9e66805cd09162359ed6e89330 | 3,653,467 |
def validate(net, val_data, ctx, eval_metric):
"""Test on validation dataset."""
eval_metric.reset()
# set nms threshold and topk constraint
net.set_nms(nms_thresh=0.45, nms_topk=400)
net.hybridize()
for batch in val_data:
data = gluon.utils.split_and_load(batch[0], ctx_list=ctx, batch_a... | 79dcd9b0d1920952b5badd4aa9f3f234776f6e06 | 3,653,468 |
from re import S
def add_unique_geom_id(point_gdf: gpd.GeoDataFrame, log: Logger=None) -> gpd.GeoDataFrame:
"""Adds an unique identifier (string) to GeoDataFrame of points based on point locations (x/y).
"""
point_gdf[S.xy_id] = [f'{str(round(geom.x, 1))}_{str(round(geom.y, 1))}' for geom in point_gdf[S.... | 0663e24b217c2911083d68146a5d8ff25c4fd8bd | 3,653,469 |
def get_data_parallel_rank():
"""Return my rank for the data parallel group."""
return _TOPOLOGY.get_data_parallel_rank() | a1da062793f6798e2e56809b3076c811f786a82b | 3,653,470 |
import math
def entropy(data):
"""
Compute the Shannon entropy, a measure of uncertainty.
"""
if len(data) == 0:
return None
n = sum(data)
_op = lambda f: f * math.log(f)
return - sum(_op(float(i) / n) for i in data) | ebfd9a84885a95ec6e4e7b2d88a0fb69fbbfaea1 | 3,653,471 |
def transform_mtl_to_stac(metadata: dict) -> Item:
"""
Handle USGS MTL as a dict and return a STAC item.
NOT IMPLEMENTED
Issues include:
- There's no reference to UTM Zone or any other CRS info in the MTL
- There's no absolute file path or reference to a URI to find data.
"""
L... | 6e215de93da9e20451b999a963fe2d42f1ad3548 | 3,653,472 |
import torch
def alexnet(pretrained=False):
"""AlexNet model architecture from the
`"One weird trick..." <https://arxiv.org/abs/1404.5997>`_ paper.
Args:
pretrained (bool): If True, returns a model pre-trained on ImageNet
"""
model = AlexNet()
if pretrained:
model_path = './mod... | a42df7c926472b88501001eefd691959e6acb3ac | 3,653,473 |
import torch
def generate_random_targets(labels: Tensor, num_classes: int) -> Tensor:
"""
Generates one random target in (num_classes - 1) possibilities for each label that is different from the original
label.
Parameters
----------
labels: Tensor
Original labels. Generated targets wi... | c0740c5ddc7c1f866b4c3cb2986f45a672d22e49 | 3,653,474 |
def recall_k(sent_im_dist, im_labels, ks=(1, 5, 10)):
"""
Compute recall at given ks.
"""
im_labels = tf.cast(im_labels, tf.bool)
def retrieval_recall(dist, labels, k):
# Use negative distance to find the index of
# the smallest k elements in each row.
pred = tf.nn.top_k(-dist, k=k)[1]
# ... | 188f2cb4c3581f9c565253fbb17797a408ce3d74 | 3,653,475 |
def get_suggestion(project_slug, lang_slug, version_slug, pagename, user):
"""
| # | project | version | language | What to show |
| 1 | 0 | 0 | 0 | Error message |
| 2 | 0 | 0 | 1 | Error message (Can't happen) |
| 3 | 0 | 1 | 0 | Error messa... | 66ddf3e44f006fcd1339b0483c3219c429643353 | 3,653,476 |
def resample_data_or_seg(data, new_shape, is_seg, axis=None, order=3, do_separate_z=False, cval=0, order_z=0):
"""
separate_z=True will resample with order 0 along z
:param data:
:param new_shape:
:param is_seg:
:param axis:
:param order:
:param do_separate_z:
:param cval:
:param... | ab7aa7ab1db40ec605d7069ccf3b1bc8751c3855 | 3,653,477 |
def get_eval(appdir, config):
"""Get an Evaluation object given the configured `GlobalConfig`.
"""
return core.Evaluation(appdir, config.client, config.reps,
config.test_reps, config.simulate) | 89b1a7bbbbbf936b622c90635a54ab6517b7bc65 | 3,653,478 |
def load_queue_from_disk(filename):
"""
Load the old queue from disk when started. Old messages that weren't
posted yet are read from the queue and processed.
"""
if os.path.exists(filename):
log.msg("Loading queue from %s" % filename)
try:
with closing(open(filename, 'r'... | b2641c7c4ad58e683b856d82825f7bd71ec00f91 | 3,653,479 |
def ask_ok(title="Confirm", message=""):
"""Ask the user to confirm something via an ok-cancel question.
Parameters:
title (str): the text to show as the window title.
message (str): the message to show in the body of the dialog.
Returns:
bool: Whether the user selected "OK".
"... | 43e88f56219715a4f292ab6021d08d1e1fbc44de | 3,653,480 |
def indexate(points):
"""
Create an array of unique points and indexes into this array.
Arguments:
points: A sequence of 3-tuples
Returns:
An array of indices and a sequence of unique 3-tuples.
"""
pd = {}
indices = tuple(pd.setdefault(tuple(p), len(pd)) for p in points)
... | f78ef40ea9bf6cfe427d366026b633fbb67016a2 | 3,653,481 |
import ray
def get_handle(endpoint_name,
relative_slo_ms=None,
absolute_slo_ms=None,
missing_ok=False):
"""Retrieve RayServeHandle for service endpoint to invoke it from Python.
Args:
endpoint_name (str): A registered service endpoint.
relative_slo... | 9db603fb9f0069a328f3fce86c2b56eec719dd21 | 3,653,482 |
def create_symbolic_controller(states, inputs):
""""Returns a dictionary with keys that are the joint torque inputs and
the values are the controller expressions. This can be used to convert
the symbolic equations of motion from 0 = f(x', x, u, t) to a closed
loop form 0 = f(x', x, t).
Parameters
... | 98d8cc545e6b70dce6161ef6c14d8bc12e0dfe77 | 3,653,483 |
def is_gene_name(instance):
"""This SHOULD check a webservice at HGNC/MGI for validation, but for now this just returns True always.."""
ignored(instance)
return True | a8a5b4047e8d0d8e70280f54365adf7a5eec20ee | 3,653,484 |
import re
def install_package_family(pkg):
"""
:param: pkg ie asr900rsp2-universal.03.13.03.S.154-3.S3-ext.bin
:return: device_type of the installed image ie asr900
"""
img_dev = None
m = re.search(r'(asr\d+)\w*', pkg)
if m:
img_dev = m.group(1)
return img_dev | b344d51ae426e167dbd2397ab93cbf8707b01496 | 3,653,485 |
def get_dendritic_mask_path_from_sessid(maindir, sessid, runtype="prod",
check=True):
"""
get_dendritic_mask_path_from_sessid(maindir, sessid)
Returns path to dendritic mask file for the specified session.
Required args:
- maindir (str): main directory
... | 3dafdc661f933f93fdfdfa9d7279649ce0d08b01 | 3,653,486 |
def abbn_min_vol():
"""
Real Name: b'"Ab-bn min vol"'
Original Eqn: b'25.6'
Units: b''
Limits: (None, None)
Type: constant
b''
"""
return 25.6 | 9fdde32cf832354b9bda9fe23ab000da66205d60 | 3,653,487 |
def clear(self: Client, player: str = None, item_name: str = None,
data: int = None, max_count: int = None) -> str:
"""Clears items from player inventory, including
items being dragged by the player.
Bedrock Edition implementation.
"""
return self.run('clear', player, item_name, data, max... | 3b7975b80f08c1f44c1a49b0a973586859f949bf | 3,653,488 |
def load_glove_embeddings(dim, vocab):
"""
Load GloVe embedding vectors for all words in our vocabulary.
https://machinelearningmastery.com/use-word-embedding-layers-deep-learning-keras/
Parameters
----------
dim : int
Dimension of GloVe embeddings. Can be 50, 100, 200 and 300.
voca... | 63bf52b86efbb20ade43d144fd674bebd8111901 | 3,653,489 |
def check_vat_number(vat_number, country_code=None):
"""Check if a VAT number is valid.
If possible, the VAT number will be checked against available registries.
:param vat_number: VAT number to validate.
:param country_code:
Optional country code. Should be supplied if known, as there is no
... | 142a2dce1def90beed2a222b67f47e9458f97ea0 | 3,653,490 |
def argextrema(y, separate=True):
"""
Deprecated in favor of argrel{min|max} in scypy.signal to get separate
extrema in about the same CPU time.
If you need a list of
all relative extrema in order, using this with separate=False takes about
half the time as by combining the scipy
functions ... | 709c045d608c35c3af5ca29131da8629716a07d5 | 3,653,491 |
from typing import Union
def examine_normal_mode(r_mol: RDKitMol,
p_mol: RDKitMol,
ts_xyz: np.array,
disp: np.array,
amplitude: Union[float, list] = 0.25,
weights: Union[bool, np.array] = True,
... | 96fc2f4153dd231756a88e46ee608a0f54d6dabc | 3,653,492 |
def generate_sprites(factor_dist, num_sprites=1):
"""Create callable that samples sprites from a factor distribution.
Args:
factor_dist: The factor distribution from which to sample. Should be an
instance of factor_distributions.AbstractDistribution.
num_sprites: Int or callable returning int. Number... | 8c09b3fe9916d0d8bc4094d62de3910de800f835 | 3,653,493 |
import warnings
def recode_from_index_mapper(meta, series, index_mapper, append):
"""
Convert a {value: logic} map to a {value: index} map.
This function takes a mapper of {key: logic} entries and resolves
the logic statements using the given meta/data to return a mapper
of {key: index}. The inde... | e8d2afc8536f552e2af277b60af47f8b8c07d961 | 3,653,494 |
def get_variables():
"""Loads ODAHU config as Robot variable
"""
return {'CONFIG': {var: getattr(config, var) for var in config.ALL_VARIABLES}} | 78ae110fdbe2837df00b06e47132b0ceda3648dd | 3,653,495 |
import string
def is_number(char: Text) -> bool:
"""Checks if char is number. Returns Boolean."""
return char in string.digits | 4bec510537057c8f6a48f35c6d0b6d9f300c00b7 | 3,653,496 |
def sliceData(data, slicebox=[None,None,None,None]):
"""
Sum 2d data along both axes and return 1d datasets
**Inputs**
data (sans2d) : data in
slicebox (range?:xy): region over which to integrate (in data coordinates)
**Returns**
xout (sans1d) : xslice
yout (sans1d) : yslice
... | 1d30a500a29c1803eb6982bb7442f9e328e3f245 | 3,653,497 |
def GetChangeUrl(host, change):
"""Given a Gerrit host name and change ID, returns a URL for the change."""
return '%s://%s/a/changes/%s' % (GERRIT_PROTOCOL, host, change) | 61ff03daa28b22ca88ab2b2f67ec18ab9617c691 | 3,653,498 |
from typing import List
import json
import os
def _ignored_jenkins_node_names() -> List[str]:
"""
Ignore nodes with these names
:return: Config list
"""
return json.loads(os.environ['IGNORED_JENKINS_NODE_NAMES']) | cec9685517cb1344bbf1ec7a6352e6727d7e80e2 | 3,653,499 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.