content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def shift_preds(preds):
"""Returns uniformly shift preds so minimum is at 0 to avoid underflow.
Args:
preds: Tensor of shape [batch_size].
"""
preds_min = tf.reduce_min(preds)
shift = tf.where(preds_min < 0, -preds_min, 0)
return preds + shift | 01c9a9fd1d3cd2b67cf77db9bd86ec4a367595e8 | 3,623,500 |
def get_stagein_logfile_names():
"""
Get the proper names for the redirected stage-in logs.
:return: stagein_stdout (string), stagein_stderr (string).
"""
stagein_stdout = config.Container.middleware_stagein_stdout
if not stagein_stdout:
stagein_stdout = 'stagein_stdout.txt'
stagei... | d2484235004c57e92d67469cf6456dee25c13c73 | 3,623,501 |
def mylinearregression(x, y, confidence_level = 95, show_plots = False, report = False):
"""
function to calculate simple linear regression
inputs: x,y-data pairs and a confidence level (in percent)
outputs: slope = b1, intercept = b0 its confidence intervals
and R (+squared)
"""
#Basic stat... | 8db905c653e0b6ff398987799103a329b5c32548 | 3,623,502 |
def mode_batch_size(mode, hparams):
"""Returns the batch size for a given mode (train or eval).
Args:
mode: Either 'train' or 'eval'.
hparams: Hyperparameters.
Returns:
Integer batch size.
Raises:
ValueError: If mode is not 'train' or 'eval'.
"""
if mode == 'train':
return hparams.bat... | 42f45e54698a539b27ad764b0c6584fb3620990d | 3,623,503 |
import argparse
def read_cli_args() -> argparse.Namespace:
"""Read the command line arguments."""
parser = argparse.ArgumentParser("ceiba")
parser.add_argument(
'-f', "--file", required=True, type=exists, help="File with the allow users")
parser.add_argument('-m', '--mongo_url', default="local... | 2a4623349d8e3c2ec57f5adb211e6d275451911b | 3,623,504 |
import os
def path_with_ext(dialog, wildcards):
"""Append extension if necessary."""
_, ext = os.path.splitext(dialog.GetPath())
if not ext:
ext = wildcards[dialog.GetFilterIndex()][1] # use first extension
ext = ext[1:] # remove leading '*'
if ext == ... | e39fb990fcb8dbd4711d82ea217752d9007f9ef6 | 3,623,505 |
from math import asin
def vector_heading(p):
"""Returns heading angle of a 2-D vector p, in radians clockwise from
the y-axis ('north')."""
theta = asin(p[0] / norm(p))
if p[1] < 0: theta = np.pi - theta
if theta < 0: theta += 2. * np.pi
elif theta > 2. * np.pi: theta -= 2. * np.pi
return ... | 0737c8e98d72163fd356bfc89d369538f1e19d9f | 3,623,506 |
def find_route_energy_left(bundle_size=None, contact_plan=None, current_time=0,
nodes_state=None, source=None, target=None,
preferred_path=None):
"""
In this protocol, a vehile i selects the imediate neighbor j (i > j) that
1) has a direct conn... | 5f2e4d0e9914157143b47030d48085d0f55b73e6 | 3,623,507 |
from typing import Optional
import ast
def _parse_type_comment(
type_comment: Optional[str],
) -> Optional[ast.expr]:
"""
Attempt to parse a type comment. If it is None or if it fails to parse,
return None.
"""
if type_comment is None:
return None
try:
# pyre-ignore[16]: th... | 49aafd9df3d590ccebf1c4b20b0c2a04640a9797 | 3,623,508 |
def sylpos_inword_f(sylitem):
""" position of the current syllable in the current word (forward)
"""
return itempos_inparent_f(sylitem, "SylStructure") | e949dd084f19cdbdd2b29ed695e910fcdf15720e | 3,623,509 |
from .core import GasComa
def from_Haser(coma, mol_data, aper=25 * u.m):
"""
Calculate production rate for `GasComa`
Parameters
----------
coma : `sbpy.activity.gas.GasComa`
Gas coma model for ratio calculation of production rate, the
production rate `Q` that the gas coma model ex... | 4af6ecb58ba4586dbcc1d92214c1eb2e093c849c | 3,623,510 |
import urllib
def email_search(request):
"""
Generate email search results.
:param request: Django request object (Required)
:type request: :class:`django.http.HttpRequest`
:returns: :class:`django.http.HttpResponse`
"""
query = {}
query[request.GET.get('search_type',
... | 4c9d02bcd3b8be6a364dbe863776c0adaecca586 | 3,623,511 |
import os
import fileinput
import sys
import inspect
def builddir_content_updates(param_dict, osimage, version, debug):
"""
Summary:
Updates builddir contents:
- main exectuable has path to libraries updated
- builddir DEBIAN/control file version is updated to current
- updates... | 029b92e75b15a00eefd4e160d5970ea674f9aa47 | 3,623,512 |
def haversine_centimetres(Olon, Olat, Dlon, Dlat, earth_radius=EARTH_RADIUS):
"""
通过两经纬度点计算地表实际距离
"""
d_lat = np.radians(Dlat - Olat)
d_lon = np.radians(Dlon - Olon)
a = (np.sin(d_lat / 2.) * np.sin(d_lat / 2.) +
np.cos(np.radians(Olat)) * np.cos(np.radians(Dlat)) *
np.sin(d_lo... | c581ac6a2ff8add9e505ff8ba6a90d3ddb9894c4 | 3,623,513 |
def find_largest_digit(n):
"""
:param n: (int) to find the largest digit in it
:return: the largest digit of n
"""
if n < 0:
n = n - (2*n)
return helper(n, 0) | 1b32d35f31220fb952121a718cac426d288b4293 | 3,623,514 |
def extract_urls(lines):
"""Parses text for possible URLs.
Args:
lines: iterable containing text
Returns:
list of validated URLs
"""
links = []
for line in lines:
split_words = (word for word in line.split(' ') if not word.isalnum())
for word in split_words:
... | 85f17edc007426499a9e8ea3fe8a731a8c3d085d | 3,623,515 |
def unit_predict_by_trees(X: np.ndarray, list_trees: list) -> constants.TYPING_TUPLE_TWO_ARRAYS:
"""
It predicts a posterior distribution over `X`, given `list_trees`.
:param X: inputs. Shape: (n, d).
:type X: numpy.ndarray
:param list_trees: a list of decision trees.
:type list_trees: list
... | bd5927b91f44ba31b6860b4791feec7f5fa52440 | 3,623,516 |
import logging
def delta_cholesky(shape, inputs, var_name, summary=False, dropout=0., is_training=None):
"""
A Cholesky factor (parameter or prediction).
:param shape: [B, T, d]
:param inputs: if None, then we return a Cholesky trainable parameter for a d-by-d covariance and tile it
to the giv... | d8ed2e4c34d3d0024954dec64df160290b407c71 | 3,623,517 |
def is_even(number):
"""Check if a number is even."""
return Bool(number % 2 == 0) | 069c705c275f6a1e934bf886f64602a02e7e3e6a | 3,623,518 |
def aumentar(v=0, t=0, formato=False):
"""Função que adiciona uma porcetagem (t) em cima de um valor (v)
e retorna o valor formatado em número corrente."""
p = v + (v * t / 100)
return p if formato is False else moeda(p) | 487e5e14066a1c9c4468e4b0b4bf7b9dc700e882 | 3,623,519 |
def parse_dependencies(dataset, use_lemmas=False):
"""
Recovers Head word, head word TAG and dependencies.
"""
new_dataset = []
for entry in dataset:
if use_lemmas:
to_use = "lemmas"
else:
to_use = "tokens"
mapped_head = [entry["features"][to_use][i] f... | 0fef2af24cb8cc31a98b5a91b9009ee5975d6432 | 3,623,520 |
import pickle
import torch
import tqdm
import gc
def get_eval_map(env:ExpRLEnv, trainer:SemAntExpTrainer, M:int,depth_projection_net:DepthProjectionNet, step:int, objectName:str):
"""Given the environment and the configuration, compute the global
top-down wall and seen area maps by sampling maps for individu... | ae8a5cc8844c5d1c69af636e9db50e3bea40506b | 3,623,521 |
def elo_update(white_elo, black_elo, points, k=25, f=400):
"""
:param white_elo:
:param black_elo:
:param points: 1 if White wins, 0 if Black wins
:param k: K-Factor, how much to update
:param f: F-Factor
:return:
"""
d = black_elo - white_elo
expected_points = elo_expect... | 02a65a7e0a5e2d5dde4f82ee3aaef5eb8b2d7e91 | 3,623,522 |
def rotated_to_icrs():
"""Transformation matrix from rotated coordinates to ICRS Cartesian."""
return matrix_transpose(ICRS_ROT_MATRIX) | 551572e9b8d59c04e02b7a822a379acdea9287fc | 3,623,523 |
def create(isamAppliance, comment='', check_mode=False, force=False):
"""
Create a new snapshot
"""
if force is True or _check(isamAppliance, comment=comment) is False:
if check_mode is True:
return isamAppliance.create_return_object(changed=True)
else:
return isa... | aa9511192d5d7305359f95fa0ee5ee1bec287dd7 | 3,623,524 |
from typing import Dict
from typing import Any
import six
def _dict_to_example(instance: Dict[Text, Any]) -> tf.train.Example:
"""Decoded parquet to tf example."""
# Note that when convert to tf.Feature, Parquet data might lose precision.
feature = {}
for key, value in instance.items():
# TODO(jyzhao): su... | a2f622f6388f17f2b158e7c2cf1bf5a20181c102 | 3,623,525 |
import collections
def section_f():
"""
Retry Logic for Credit Cards
"""
results = collections.OrderedDict()
results['section'] = 'f'
order = Order(message_type='AC',
cc_num='4788250000028291',
order_id='601',
cc_expiry='1116',
... | 9133674952d3963b082729943b6184d35057978a | 3,623,526 |
import torch
def inner(tensor0: BKTensor, tensor1: BKTensor) -> BKTensor:
"""Return the inner product between two tensors"""
N = torch.numel(tensor0[0])
tensor0_real = tensor0[0].contiguous().view(N)
tensor0_imag = tensor0[1].contiguous().view(N)
tensor1_real = tensor1[0].contiguous().view(N)
... | 7e06d223a7dba6b0dc5e282ca6bf7d5b16bf15c1 | 3,623,527 |
def stft_to_wav(stft, hparams):
"""inverse the stft to produce the wav file data"""
_, hop_length, win_length = get_params(hparams)
return librosa.istft(
_i_phase_and_magnitude(stft), hop_length=hop_length, win_length=win_length
) | 2b5204b9d0e8535025354428cad5b792a9f75d3c | 3,623,528 |
from typing import Any
import json
def try_parse(value: Any):
"""Attempts to turn a string value into it's Python data
representation via json.loads. Has special handling
for strings 'True', 'False', and 'None'.
:param value: The value. If a string, attempts to parse as
JSON, ... | db963c34319c8aaee6ac17a52d24dbcf2e5806e5 | 3,623,529 |
import operator
import types
def d3plus_data_documents(document_list, field):
"""
Compute data suitable for feeding to d3plus/geo_map from OPSExchangeDocument data model.
Obtains a list of document objects of type OPSExchangeDocument and
a field name designating which object attribute to use for the ... | 9241eae60f75fcec514ebd4d627a8862acc006a9 | 3,623,530 |
from typing import Dict
def annotations_from_executor(
executor: local_executors.Kubernetes) -> Dict[str, str]:
"""Get Pod annotations from the executor for TPUs."""
if executor.cloud_provider != local_executors.GOOGLE_KUBERNETES_ENGINE_CLOUD_PROVIDER:
return {}
if executor.requirements.accelerator in ... | 4337791b11e7f947eb075478a6bab7c18ef37c50 | 3,623,531 |
import crypt
import socket
import json
def send_socket_request(request):
"""Send json request server and take response."""
# pylint: disable=invalid-name
crypted = crypt.encrypt(request, config.SERVER_PUBLIC_RSA_KEY)
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((config.HOST, con... | 24295030105cf3f8c9c4a6cd09f24f2054aab991 | 3,623,532 |
def prepare_batch_multimodal(batch, device=None, non_blocking=False):
"""Prepare batch for multimodal network training: pass to a device with options. Assumes the shape returned by a
`MultimodalDataset` subclass.
Args:
batch: data to be sent to device.
device: optional) (default: None) device t... | 793316ea85632d1f3592f65da0906b9920077a56 | 3,623,533 |
from re import DEBUG
def ObjectLocalization(objImg: np.ndarray, targetImg: np.ndarray) -> np.ndarray:
"""
https://docs.opencv.org/master/dc/dc3/tutorial_py_matcher.html
Feature based object detection
return: Homography matrix M (objImg->targetImg), if not found return None
"""
img1 = objImg
... | e73cae64b9dedf7cef0f440167faa74bb9dccc05 | 3,623,534 |
def get_look_attrs(node):
"""Returns attributes of a node that are important for the look.
These are the "changed" attributes (those that have edits applied
in the current scene).
Returns:
list: Attribute names to extract
"""
# When referenced get only attributes that are "changed sin... | b19bbbe59f32f6dbd951a7ca3a28a06b0c3dcb58 | 3,623,535 |
from typing import Dict
def get_max_document_bytes(env: Dict[str, str]) -> int:
"""Get the maximum number of bytes a document allowed to be stored in S3."""
try:
mb_count = int(env.get(
ENV__MAX_DOCUMENT_SIZE_MB, str(DEFAULT_MAX_DOCUMENT_SIZE_MB),
))
except ValueError:
... | b9ee2d5ebfcbbb2f09f2ef2426ac0bcd99ef9225 | 3,623,536 |
def by_deep_time_per_call(stat):
"""Sorting by inclusive elapsed time per call in descending order."""
return -stat.deep_time_per_call if stat.deep_hits else -stat.deep_time | 6419a76a292828d5fd5525998409d175924eea5f | 3,623,537 |
def parseDirectiveArguments(data):
"""Makes a list whose elements are delimited by commas in an input
string. Commas inside a scope started with brackets, parens, single-
or double-quotes, are skipped. Scopes delimited by brackets or
parentheses are assumed to be well formed. I.e. we simply coun... | 84efda543b6c874c6cc96c2e45a4784f6020e2a2 | 3,623,538 |
def color_map_cyclic(color_normalized: float) -> np.ndarray:
"""
Maps normalized value to color, cyclic.
Note: For JIT to work, this must be declared at the top level.
@param color_normalized: Normalized color value
@return: R, G, B
"""
hue = (color_normalized + 1 / 6) % 1
x = hue * 6
... | 134e56a0473121c7b670e71bd6eb6106a47e9812 | 3,623,539 |
from typing import Dict
from typing import Tuple
from typing import List
def ca_validate_input(input_json: Dict, ecosystem: str) -> Tuple[List[Dict], List[Package]]:
"""Validate CA Input."""
logger.debug('Validating ca input data.')
if not input_json:
error_msg = "Expected JSON request"
ra... | 7975678737729aed7df2a2ca4955293ce49258ec | 3,623,540 |
def _convert_to_kube_env(
env: infra_validator_pb2.EnvVar) -> k8s_client.V1EnvVar:
"""Convert infra_validator_pb2.EnvVar to kubernetes.V1EnvVar."""
if not env.name:
raise ValueError('EnvVar.name must be specified.')
if env.HasField('value_from'):
if env.value_from.HasField('secret_key_ref'):
val... | 7723a4345351332364608594279f4b1d6d8e491b | 3,623,541 |
import os
import csv
def _prep_cnv_file(cns_file, svcaller, work_dir, data):
"""Create a CSV file of CNV calls with log2 and number of marks.
"""
in_file = cns_file
out_file = os.path.join(work_dir, "%s-%s-prep.csv" % (utils.splitext_plus(os.path.basename(in_file))[0],
... | 1a472f0b96b2a50fb62bdc792e2241fe9316a82a | 3,623,542 |
def is_release(semver):
"""is a semver a release version"""
return not (semver.build or semver.prerelease) | de14f18e4df2bf7fc86a6af10d2ef07f93a8da6b | 3,623,543 |
def solve_value_fn(env: gym.Env, gamma: float) -> np.ndarray:
"""
Solve the value function for each state in an environment
:param env: gym environment
:param gamma: discount factor
:return:
"""
# Transition matrix
n_states = env.get_num_states()
P_trans = env.get_transition_matrix()... | 4f54ab8da4dcb3c50814d5d12a2250ddf2956e9c | 3,623,544 |
def CH4_rf(emission, years, tstep=0.01, kind='linear',
decay=True):
"""Transforms an array of methane emissions into radiative forcing with user-defined
time-step.
emission: an array of emissions, should be same size as years
years: an array of years at which the emissions take place
... | a67a799a8b6b42233816d32b198da84f232609e3 | 3,623,545 |
import json
import itertools
def search_v1(db, config):
"""
API v1 route to perform a fulltext search on flats.
Example::
POST /api/v1/search
Data: {
"query": "SOME_QUERY"
}
.. note::
Filtering can be done through the ``filter`` GET param, according
... | e4dce1713cc836f57797743e0d349f9742fff3d2 | 3,623,546 |
import torch
def train(n_epochs, loaders, model, optimizer, criterion, use_cuda, save_path):
"""returns trained model"""
print(f"Training model...")
# initialize tracker for minimum validation loss
valid_loss_min = np.Inf
for epoch in range(1, n_epochs+1):
# initialize variables to m... | 69ddf89fa772606a1ac0f7abfbc3ec9576e16481 | 3,623,547 |
def caclf(_freq, _pdos, T, dmu=0.0, energyunit='J'):
"""
Calculate thermal free energy from phonon density of states (p DOS)
Parameters
_freq : phonon frequency
-pdos : phobob DOS
dmu : to be used external phonon chemical potential
Returns
f : vibrational free energy
u : internal... | d612866ff74828469e642851cad1c58609255226 | 3,623,548 |
import torch
import itertools
import tqdm
def bn_update(loader, model, verbose=False, subset=None, **kwargs):
"""
BatchNorm buffers update (if any).
Performs 1 epochs to estimate buffers average using train dataset.
:param loader: train dataset loader for buffers average estimation.
... | 1a78b3081fbad4637399b79455cb25728ee4d228 | 3,623,549 |
def store_film_params(gammas, betas, contrasts, metadata, model, film_layers, depth):
"""Store FiLM params.
Args:
gammas (dict):
betas (dict):
contrasts (list): list of the batch sample's contrasts (eg T2w, T1w)
metadata (list):
model (nn.Module):
film_layers (li... | fcbc1e0cee76753a3edd8f4ca49af0354913c433 | 3,623,550 |
def get_tfidf(train_context_path, vocabulary):
"""
Inputs: path to contexts used for training
Outputs: TF-IDF sparse matrix.
Each row corresponds to a document
Each column corresponds to a word in the vocabulary
Because the output is a sparse matrix, each r... | 461e3f3cfb92af1abc36492e66b3dbbe182cd259 | 3,623,551 |
def GetFunctionAttr(ea, attr):
"""
Get a function attribute
@param ea: any address belonging to the function
@param attr: one of FUNCATTR_... constants
@return: -1 - error otherwise returns the attribute value
"""
func = idaapi.get_func(ea)
if func:
return _IDC_GetAttr(func, _... | 3e8aa3ddeeeee048353d3062b718ddafad25e02d | 3,623,552 |
def ifmeth(parser, token):
"""
Used to mark template blocks for Swagger/OpenAPI output.
If the specified method matches the *current* method in Swagger/OpenAPI
generation, show the block. Otherwise, the block is omitted.
{% ifmeth GET %}
Make a GET request to...
{% endifmeth %}... | 11f3e8ad71b23527cb2012e21a7278ea90eb90e4 | 3,623,553 |
import math
def atan(space, x):
"""atan(x)
Return the arc tangent (measured in radians) of x.
"""
return math1(space, math.atan, x) | 979db99c7a362b85728d2e79a039f71738385604 | 3,623,554 |
def load_policy(graph_def,
input_observation_name,
input_state_name,
output_state_name,
output_pd_params_name,
tf_sampling_fn):
"""Load a policy from a graph file.
Args:
graph_def: Graph definition.
input_observation_name: Name... | 817b738ca9db1c425360b210df1095acb03ec488 | 3,623,555 |
def get_df(model):
"""
Return pyomo results as pandas dataframe
Usage:
df1 = uma.get_df(model.variable)
"""
df = pd.DataFrame()
df_dict = {v.name: np.array([v[index].value for index in v]) for v in
model.component_objects(pyomo.Var, active=True)}
max_length = max([le... | eed59f77d9398dbcf22669582af65dac64e8bd46 | 3,623,556 |
def get_SMS_PGV(stat_codes, loc, absVal=True):
"""
Note: If stat_codes list is not sorted use get_SMS_Rrups to get a
list of stat_codes sorted according to Rrup values
stat_codes:
list containing SMS codes
loc:
location of .000, .090 and .ver data files
return:
array(len... | 69a18c1523c901fcfa4a49c7895905d7bfab3897 | 3,623,557 |
def identity(obj):
"""
Identity function computing no operation
Parameters
----------
obj : object
any object
Returns
-------
obj
the input object itself
"""
return obj | 252a44ce3251b74ad25e28bf6bff462f6227f04b | 3,623,558 |
def _multiply_gradients(grads_and_vars, gradient_multipliers):
"""Multiply specified gradients."""
multiplied_grads_and_vars = []
for grad, var in grads_and_vars:
if var in gradient_multipliers or var.name in gradient_multipliers:
key = var if var in gradient_multipliers else var.name
grad *= cons... | 635d584a8f72efbcaa247bc0027cfca9c70159e5 | 3,623,559 |
def cliques_containing_node(G, nodes=None, cliques=None):
"""Returns a list of cliques containing the given node.
Returns a single list or list of lists depending on input nodes.
Optional list of cliques can be input if already computed.
"""
if cliques is None:
cliques = list(find_cliques(G... | 1251479b2cb4a0e8fbad148e359ecbcb4b663dcf | 3,623,560 |
def copy_exam_1_to_2(request, id_structure):
"""
Copy primary exam to secondary exams
"""
structure_concerned = StructureObject.objects.get(id=id_structure)
exams = Exam.objects.filter(
id_attached=structure_concerned.id, code_year=currentyear().code_year)
exams_1 = exams.filter(session=... | ff124d15080494e5a2c10c8e08581158ba270ff2 | 3,623,561 |
def is_Gamma1(x):
"""
Return True if x is a congruence subgroup of type Gamma1.
EXAMPLES::
sage: from sage.modular.arithgroup.all import is_Gamma1
sage: is_Gamma1(SL2Z)
False
sage: is_Gamma1(Gamma1(13))
True
sage: is_Gamma1(Gamma0(6))
False
s... | 5a93728cc2506e060c9fd511f7ace7e202b43350 | 3,623,562 |
def get_table_service():
"""Return the TableService instance for this request initializing it if it doesn't exist."""
table_service = getattr(g, 'table_service', None)
if table_service is None:
table_service = g.table_service = TableService(
account_name=app.config['AZURE_STORAGE_ACCOUNT... | f8d90a567704ce342911337d17535e29562830fa | 3,623,563 |
def __project_geometry(geometry, crs=None, to_crs=None, to_latlong=False):
"""
Project a shapely Polygon or MultiPolygon from lat-long to UTM, or
vice-versa
Parameters
----------
geometry : shapely Polygon or MultiPolygon
the geometry to project
crs : dict
the starting coord... | ab7bebaf058aa9a6f62e00a3d284f63bdabb4dcd | 3,623,564 |
def who_includes(includeDict, name):
"""Finds all files who includes name, and recurses outwards."""
nameSet = set()
dependencySet = set()
recurse_who_includes(includeDict, name, nameSet, dependencySet)
result = "digraph G{\n"
result += 'graph[fontname="Helvetica",fontsize=13,ranksep=3.000,overl... | 7f67c2711c4a66320efe37d7e9d107f69bce47c0 | 3,623,565 |
def get_irods_tree(investigation):
"""Return HTML for iRODS collections"""
irods_backend = get_backend_api('omics_irods', conn=False)
if not irods_backend:
return ''
ret = '<ul><li>{}<ul>'.format(settings.IRODS_SAMPLE_COLL)
for study in investigation.studies.all():
ret += '<li>{}'.fo... | ac6088d713dfd0d049291bc6fca4fdbefb554c6f | 3,623,566 |
def get_acq_final_days(df, criteria, correct_amount, session_length):
"""
This function returns the last days for the Acquisition test. The function grabs all the rows that meet the minimum
correct trials amount and the maximum session length amount. Then it calculates the first instance when the animal
... | 2e9974fed030e50fdb400c95a7e353e85ad7d89f | 3,623,567 |
def create_needle_model(name, length, radius, tip_radius):
"""
Create a model that can be used to represent the style/probe.
"""
# TODO: Set colour
show_markers = False
create_model_module_logic = slicer.modules.createmodels.logic()
needle = create_model_module_logic.CreateNeedle(
le... | 7e407febe09e3439c27d8bb3b4e41fa51457020b | 3,623,568 |
def res_pairs(num_res, nearn):
"""
computes res-res pairs included for which to calculate minimum distance features
state num of residues, and nearest neighbour skip e.g. i+3 is nearn=3
"""
res=[]
for i in range(num_res-nearn):
for j in range(i+nearn,num_res):
res.append([i+1... | 909d1e5142e909eef009241548ae92012c17e6f3 | 3,623,569 |
import argparse
def get_arguments():
"""Parse all the arguments.
Returns:
A list of parsed arguments.
"""
parser = argparse.ArgumentParser(description="Binary class segmentation segmentation model modified on U-Net")
parser.add_argument("--batch_size", type=int, default=BATCH_SIZE,
... | bed41205e40672910e53c6e6f0bba93f16ec1bc9 | 3,623,570 |
def api_image():
"""Flask Application Image API
Returns:
Super hero image JSON response
"""
if 'id' in flask.request.args:
id = int(flask.request.args['id'])
rs = session.query(Image).filter_by(id=id).first()
if not rs is None:
return flask.jsonify({... | 94eb0c14f301b5553ce935c64051c19f2559ca26 | 3,623,571 |
def Packet_genReadGpsCompassBaseline(errorDetectionMode, buffer, size):
"""Packet_genReadGpsCompassBaseline(vn::protocol::uart::ErrorDetectionMode errorDetectionMode, char * buffer, size_t size) -> size_t"""
return _libvncxx.Packet_genReadGpsCompassBaseline(errorDetectionMode, buffer, size) | bf59ae916bc249d4fc8a2b5baf5b9f93b0c56eb3 | 3,623,572 |
def get_transition_mass(pile_height: float) -> float:
"""
Returns the mass of transition piece (in kg).
:return:
"""
transition_length = [15, 20, 15, 20, 15, 24, 20, 30, 20, 31]
transition_weight = [150, 250, 150, 250, 160, 260, 200, 370, 250, 420]
fit_transition_weight = np.polyfit(transiti... | cc92927f37326cfd5c682c63bd0cc4f12922de24 | 3,623,573 |
def get_image_code():
"""
获取图片验证码
:return:
"""
code_id = request.args.get('code_id')
name, text, image = captcha.generate_captcha()
try:
redis_store.setex('ImageCode_' + code_id, constants.IMAGE_CODE_REDIS_EXPIRES, text)
except Exception as e:
current_app.logg... | 17d80c5669354b5c50197cf50368a7d616f186f0 | 3,623,574 |
def delete_container_view(request, container):
""" Deletes a container """
response = delete_container(request, container)
if response:
messages.add_message(request, messages.SUCCESS, _('Container deleted.'))
else:
messages.add_message(request, messages.ERROR, _('Access denied.'))
... | 382491b3bcdddbe63b9ffae48e0bdfb6891f13f4 | 3,623,575 |
def full_dataset_individual_left_canonical_mps_compression_with_reconstruction(all_data, partition, max_bond_dimension):
"""
Performs a full left canonical MPS decomposition, and subsequent vector reconstruction, of every vector within a
dataset (i.e. every row in a matrix)
See "The density matrix reno... | bff94276be9ddccf74170542ebe7f9ee1a2e7707 | 3,623,576 |
def setup_platform(hass, config, add_devices, discovery_info=None):
""" setup the sensor platform for smappee """
smappee = hass.data[DATA_SMAPPEE]
dev = []
for sensor in SENSOR_TYPES:
dev.append(SmappeeSensor(smappee, sensor))
add_devices(dev)
return True | fa69a37c5fdf217dc11d5bbabaad8a3a8a5abe46 | 3,623,577 |
def extract(key, items):
"""Return the sorted values from dicts using the given key.
:param key: Dictionary key
:type key: str | unicode
:param items: Items to filter.
:type items: [dict]
:return: Set of values.
:rtype: [str | unicode]
"""
return sorted(item[key] for item in items) | d39b6d42a08ea8e2e7d7488fb00a28243c9a6718 | 3,623,578 |
def quat2ypr_rads(quat):
"""quat2ypr_rads(vec4f quat) -> vec3f"""
return _libvncxx.quat2ypr_rads(quat) | 34607c72e20ddffa9c940caeefb7d3abc25ab1a9 | 3,623,579 |
import time
def BM_stack(imageStack, blockwidth, delay, max_shift, canny = True, progressSignal = None, *args, **kwargs):
"""
gets optical flow of a complete imagestack, based on blockmatching
unit is px/frame as no scale is given here yet
blockwidth is width of square macroblock
m... | 4ccd0d6a49ceb35705fb83a49961b8e717311ae8 | 3,623,580 |
def page_not_found(e):
"""whatever you are looking for we don't have. Sorry"""
return 'no, it is not here', 404 | 6013c85c5dec5a22d58b8820c8333859e1ceaa08 | 3,623,581 |
import collections
def read_pointmatchers(wfile):
"""
Read a file of PointMatcher definition lines, and return an ordered dict of
(matcher, string2) pairs, where string2 is the rest of the line.
"""
rtn = collections.OrderedDict() #< need to preserve order
with open(wfile) as wf:
for l... | 5bbc40184057223b185b4f84ccd751202cbc28a7 | 3,623,582 |
def analyze_two(group1_data,
group2_data,
n_samples: int = 2000,
**kwargs) -> BestResultsTwo:
"""Analyze the difference between two groups
This analysis takes about a minute, depending on the amount of data.
(See the Notes section below.)
This function c... | 1ee6895e11d9e35f9072f2d1f26680eb5706dfa5 | 3,623,583 |
def runBacktesting(strategyClass, settingDict, symbol,
startDate, endDate, slippage,
rate, size, priceTick):
"""运行单标的回测"""
engine = BacktestingEngine()
engine.setBacktestingMode(engine.BAR_MODE)
engine.setDatabase(MINUTE_DB_NAME, symbol)
engine.setStartDate(st... | 5c2f38ac2e6061a1e27a9b888c247ad77dd2e38e | 3,623,584 |
def format_kvps(mapping, prefix=""):
"""Formats a mapping as key=value pairs.
Values may be strings, numbers, or nested mappings.
Nested mappings, e.g. host:{ip:'0.0.0.1',name:'the.dude.abides'},
will be handled by prefixing keys in the sub-mapping with the key,
e.g.: host.ip=0.0.0.1 host.name=the.... | 4780d5c705a8805331a1d981e87fa3d3dca263a8 | 3,623,585 |
def load_input(filename):
"""
:param filename: A string representing a text.
:return: A set of words representing the text.
"""
text = filename.lower().replace('?', ' ').replace('!',' ').replace('.',' ').replace('-',' ').replace(':',' ').replace(';',' ').replace(',',' ').replace('(',' ').replace(')',' ').replace('... | aa291c1fdf625f6380a607263562c3c47a667121 | 3,623,586 |
from typing import Iterable
def _get_merged_mapping(
to_keep_ids: np.ndarray, label_rule_masks: Iterable[np.ndarray], number_of_labels: int, make_sparse: bool
) -> np.ndarray:
"""
Creates a rule-to-label mapping matrix according to the rules selected for reduction.
Returns: Mapping array of shape M (d... | 010bd811399939903d0fd661a702540704f61c74 | 3,623,587 |
def get_projection_profile(binary_image):
"""
Parameters
----------
binary_image: numpy.ndarray
The binary image to be projected.
Returns
-------
projection_profile: numpy.ndarray
A binary image representing the projection_profile.
"""
chunk_percentage = 0.05
chu... | d78dcbe2acd569f571fc7243caf5e116f6393ed3 | 3,623,588 |
import torch
def project(meta_weights, P, Q):
""" project meta_weights to sub_weights
Args:
meta_weights: a 4-D tensor [cout, cin, k, k], the meta weights for one-shot model;
P: a 2-D tensor [cout, cout_p], projection matrix along cout;
Q: a 2-D tensor [cin, cin_p], projection matrix along cin;
Retu... | a693d51a4a74358bd831954c46bb8cb993dabf66 | 3,623,589 |
def make_move(board, player, alpha, beta, depth, idepth):
"""
:param board: A simplified version of the current board
:param player: The player the algorithm is playing as (Can only be an instance of Player)
(Note: the function maximises for the computer and minimises for the player)
... | 7ff054e7453ec8879b45ca10f3990bbfbe622a34 | 3,623,590 |
def _endx(parents, n_gene):
"""Extended Normal Distribution Xover"""
ALPHA = (1.-2*0.35**2)**0.5/2.
BETA = 0.35/(n_gene-1)**0.5
child = np.empty(n_gene+1)
t1 = (parents[1, :n_gene]-parents[0, :n_gene])/2.
t2 = np.random.normal(scale=ALPHA)*(parents[1, :n_gene]-parents[0, :n_gene])
t3 = np.... | 91c9e56e381bde05ef796d109fe994018ae65a72 | 3,623,591 |
def Trappist1PlanetPorbSample(planet, size=1, **kwargs):
"""
Sample Trappist1 system planet Porbs from Gaussian distributions based on
Gillon+2017, Luger+2017 measurements.
"""
# Light preprocessing of planet name
name = str(planet).lower()
ret = []
for ii in range(size):
if na... | f1fa1370fd89ec8b97c42f91b6cb442ad8093875 | 3,623,592 |
def com_in_limb_effector_frame_constraint(Robot, transform, limbId):
"""
Generate the inequalities constraints for the CoM position given a contact position for one limb
:param Robot:
:param transform: Transformation to apply to the constraints
:param limbId: the Id of the limb used (see Robot.limbs... | 031ddb499f904de6417d7ffb4b353ddc8719f842 | 3,623,593 |
def get_weth(account=None):
"""Mints WETH by depositing ETH."""
print(f'Active network: {network.show_active()}')
my_wallet_address = (account if account else accounts.add(config["wallets"]["from_key"]))
my_balance = my_wallet_address.balance()
print(f'My wallet address: {my_wallet_address}')
p... | da2c704125987b3074b015ec7768d9e991fc2560 | 3,623,594 |
from shutil import copyfile
from pathlib import Path
def _data_block(mode, names_and_jsons, output_dir, include_gene_sets=True, organism="human"):
"""
"""
data_block = []
if mode == "directory":
(output_dir / "data").mkdir(exist_ok=True, parents=True)
for name, json in names_and_jso... | fe2b540ef46fc9d41f24ed3bab1fba209d055849 | 3,623,595 |
def lj_sanity_test():
"""Sanity test to make sure we even have the plugin fixtures installed."""
return "sanity" | ddd4fee2ad3b8b3f81c3a2821ce5708d22d05d89 | 3,623,596 |
def randomString(length, chrs=None):
"""Produce a string of length random bytes, chosen from chrs."""
if chrs is None:
return getBytes(length)
else:
n = len(chrs)
return ''.join([chrs[randrange(n)] for _ in range(length)]) | 0152b2811a5bc05f40fc7fb7a161aa5f7192be4a | 3,623,597 |
from uuid import uuid4
import tempfile
from openeye import oechem
import os
from io import StringIO
def generateResidueTemplate(molecule, residue_atoms=None, normalize=True, gaff_version='gaff'):
"""
Generate an residue template for simtk.openmm.app.ForceField using GAFF/AM1-BCC.
This requires the OpenEy... | c8cec729925b33bb21825699864150d03901eef0 | 3,623,598 |
def compute_vertex_normals(points, trilist):
"""
Compute the per-vertex normals of the vertices given a list of
faces.
Parameters
----------
points : (N, 3) float32/float64 ndarray
The list of points to compute normals for.
trilist : (M, 3) int16/int32/int64 ndarray
The list... | 62e3ca5c4562f59221d498b3a115c3372117e06a | 3,623,599 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.