content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def capture(*args, **kwds) -> str:
"""\
Like `rich.console.Console.print`, but renders to a string.
Yes, this is confusing because we already had `render_to_string`, which does
something different -- I _think_ it's useful for intermediate renders that
will eventually be given to `rich.console.Conso... | dbd0e7e3eb8923a8670b4d2f4496b92b6359d79a | 3,605,466 |
from datetime import datetime
def upgrade_trial(request):
"""
View that handles upgrading from a Free account to a Trial account.
"""
userprofile = request.user.userprofile
if userprofile.account_level.level == 'Paid':
messages.error(request, 'You already have a Paid account.')
... | 43ed366ecc9ce11abb6ebdab8a092c148042f446 | 3,605,467 |
def stitch_image(mat1, mat2, overlap, side, wei_mat1=None, wei_mat2=None,
norm=True, total_width=None):
"""
Stitch projection images or sinogram images using a linear ramp.
Parameters
----------
mat1 : array_like
2D array. Projection image or sinogram image.
mat2 : arr... | 2bb65f533c9e2288f1632721a627491eacaf5e1e | 3,605,468 |
def skeleton_binary(image, kernel=None, n=None):
"""
This operation reduces the foreground regions in a binary image
to a skeletal remnant that largely preserves the extent and
connectivity of the original region while throwing away most of
the original foreground pixels.
https://homepages.... | e109469e249e40323203627ee6b24e96900aaff8 | 3,605,469 |
def predict_factor(h_abs, h_abs_old, error_norm, error_norm_old, prec):
"""Predict by which factor to increase/decrease the step size.
The algorithm is described in [1]_.
Parameters
----------
h_abs, h_abs_old : float
Current and previous values of the step size, `h_abs_old` can be None
... | 1b7ff5987fce3b9c03a3a88e1c192d9989a32358 | 3,605,470 |
def getRealPythonOrder()->str:
"""获取非虚拟环境的Python命令"""
obj = getEnvXmlObj()
node = obj.get_xpath_node('real/python3')
return node.text | 60a6a86525428f34223bc43e32e7f0f037a50107 | 3,605,471 |
from tensorflow.python.framework.graph_util import convert_variables_to_constants
def freeze_session(session, keep_var_names=None, output_names=None, clear_devices=True):
"""
Freezes the state of a session into a pruned computation graph.
Creates a new computation graph where variable nodes are replaced ... | 00b2b63d7b2aa59d91f225d0257adbbebde182b5 | 3,605,472 |
from pm4py.statistics.ocel import objects_ot_count
from typing import Dict
def ocel_objects_ot_count(ocel: OCEL) -> Dict[str, Dict[str, int]]:
"""
Counts for each event the number of related objects per type
Parameters
-------------------
ocel
Object-centric Event log
parameters
... | 6209e230dd688aa82e862c0b92e57037aaaa2d71 | 3,605,473 |
def apply_argmax(array, argmax, axis):
"""Apply precomputed argmax indices in multi dimension arrays
array[np.argmax(array)] works fine in dimension 1, but not in higher ones.
This function extends it to higher dimensions.
Examples
--------
>>> import cupy
>>> array = cupy.random.randn(10,... | 7d6168a4f610283b7b442c5b6e6a9c7f6a7e9089 | 3,605,474 |
def checkIfDuplicates_2(listOfElems):
""" Check if given list contains any duplicates """
setOfElems = set()
for elem in listOfElems:
if elem in setOfElems:
return True
else:
setOfElems.add(elem)
return False | a7d9f322faefa4b0b0191ca96097bbf38c61ee3d | 3,605,475 |
def get_gpus():
"""List of NVIDIA GPUs
"""
return _GPUS | c537c5cbb36d1d9e4df6450d2686423781397a61 | 3,605,477 |
from datetime import datetime
def raw_to_session(timestamp):
""" :param timestamp: <float> from time.time() output
:return string in YYYYMMDDHHmmSS format"""
t = datetime.utcfromtimestamp(timestamp)
return t.strftime(SYNERGY_SESSION_PATTERN) | bf04ea331f7878b01c8adc2de48aaa48cbfd33b3 | 3,605,478 |
def gtex_position_translate(ens_gene_id,gtex_variants,tss,promoter_start,promoter_end,strand,promoter_before_tss,promoter_after_tss):
"""
Convert the GTEx data genome positions to those which can be mapped into the final figure.
Reduce to those that are within range of the promoter before/after tss.
"""... | 3f4c9de586975b788e38599793209700a5569708 | 3,605,479 |
def output_addresses(df, file_out):
"""
"""
addresses = get_addresses(df)
with open(file_out, 'w') as output:
for address in addresses:
output.write(address + '\n')
return addresses | f15c0937e30e7bb76477e31d77da6c7fe7de1f4b | 3,605,480 |
def qn(tag):
"""
qn is short for *qualified name*. Return fully qualified (Clark notation)
tagname corresponding to short-form prefixed tagname *tag*.
"""
prefix, tagroot = tag.split(':')
uri = nsmap[prefix]
return '{%s}%s' % (uri, tagroot) | dbb09c62fb64118f10a84fe3cc6cdcfba9308c5a | 3,605,481 |
def flow_to_image(flow):
"""
Convert flow into middlebury color code image
:param flow: optical flow map
:return: optical flow image in middlebury color
"""
u = flow[:, :, 0]
v = flow[:, :, 1]
maxu = -999.
maxv = -999.
minu = 999.
minv = 999.
idxUnknow = (abs(u) > UNKNO... | 70ce644fb34af309cbf4498cb5f3eaa134409a9f | 3,605,482 |
import platform
def is_windows():
"""
Check and return if running platform is Windows.
Arguments:
None
Returns:
bool
"""
return any(platform.win32_ver()) | 4c166c57d96c84bafa6750327b7481be584129e8 | 3,605,483 |
def riemann_metric(Y, laplacian, n_dim=None, invert_h=False, mode_inv = 'svd'):
"""
Parameters
----------
Y: array-like, shape = (n_samples, mdimY )
The embedding coordinates of the points
laplacian: array-like, shape = (n_samples, n_samples)
The Laplacian of the data. It is recommen... | d7eb4e013d22dd23436f56e2270162acf3934efb | 3,605,484 |
def mk_co_eclip (lambda_str, beta_str,equinox=''):
"""
Create a coordinate in the Ecliptic coordinate system. By default,
in J2000 equinox
Args:
lambda_str : Ecliptic longitude in angle units as string (e.g. "184d43m35.5s")
[0,360) degrees
beta_str: Ecliptic latitu... | 5547ba2592dccc6b90cb1c7d8ac8a2f689936c87 | 3,605,485 |
def fib(n):
"""Assumes n int >= 0
Returns Fibonacci of n"""
global fib_2_counter
if n == 2:
fib_2_counter += 1
if n == 0 or n == 1:
return 1
else:
return fib(n-1) + fib(n-2) | 77717282869da8dc09032907ed81d2171877de36 | 3,605,486 |
async def root():
"""
Default endpoint for testing if the server is running
:return: Positive JSON Message
"""
return {"MLDatasetTemplate is Running!"} | 17fccde4f21561a5166e39ca43df9e88539e0b2e | 3,605,487 |
def load_CIFAR100_batch(filename, number):
""" load single batch of cifar """
with open(filename, "rb") as f:
datadict = load_pickle(f) # dict类型
X = datadict["data"] # X, ndarray, 像素值
Y = datadict["fine_labels"] # Y, list, 标签, 分类
# reshape, 一维数组转为矩阵10000行3列。每个entries是32x32
... | 98724d3cf6dc63c441ae2a0f6417e2fead682524 | 3,605,488 |
from datetime import datetime
def parse_trioptics_metadata_mtflab_v5(file_contents):
"""Read metadata from the contents of a Trioptics .mht file. Compatible with MTF-Lab v5.
Parameters
----------
file_contents : `str`
contents of a .mht file.
Returns
-------
`dict`
dicti... | 07b7611f77b7097deec5efd970058e342d97a740 | 3,605,489 |
def get_details_format(s: str, lang: str = 'zh-cn'):
"""
Get API Request
Parameters
----------
s: Company Name
lang: Lang
Returns
-------
URL
"""
return "http://www.solvusoft.com/%s/file-extensions/software/%s/" % (lang, s) | 4df1c9526febf2eadb9f6fe9d13d8b9615535aa2 | 3,605,490 |
def semiFixedComponentConstraintsNMF(W, H, iter, numIter, parameter):
"""Implements a simplified version of the soft constraints in [2].
References
----------
[2] Patricio López-Serrano, Christian Dittmar, Jonathan Driedger, and
Meinard Müller.
Towards modeling and decomposing loop-base... | be18460624d8ae319acdc3bb4d1a992b8bb5f954 | 3,605,491 |
def create_admin_agent(
client_args,
client_id,
req_processors,
secure_train,
server_args,
federated_client: FederatedClient,
args,
is_multi_gpu,
rank,
):
"""Creates an admin agent.
Args:
client_args: start client command args
client_id: client name
r... | d36e63db74190ac30cd256659999a9f3ae468f1d | 3,605,493 |
def delete(context, key):
"""Delete a key from the current task context."""
return context.pop(key, None) | 0b697ede943653ba41e7c50fff86907f93becee1 | 3,605,494 |
def login_user(request):
"""Logs the user in
Retrieves the username and password provided by the
user after validating the form. The username and
password is authenticated, and if successful, the
user is logged into the current session.
If the authentication fails, or the form data provided
... | 0f4eaa7974bf25fec30cec5b2302c42519f6053d | 3,605,495 |
def matches_beginning(prefix: str, allowlist_key: str) -> bool:
""""
:param prefix: the value of the prefix query parameter
:param allowlist_key: the key from
:return: a bool of whether the prefix can be found on the allowlist.
Both values are stripped of leading `/` before comparison.
"""
... | ef047dfe16722d98b8fe894d3c400330a2defd74 | 3,605,496 |
def readstarmodel(starmodel_file, nmodeltype, quiet=False):
"""Usage: starmodel_wv,starmodel_flux=readstarmodel(starmodel_file,smodeltype)
Inputs:
starmodel_file - full path and filename to star spectral model
smodeltype - type of model. 2==ATLAS
Returns:
starmodel_wv : wavelength (A)
... | 7bb94f178d2a50e41e091240096c99b738e4038b | 3,605,497 |
def gene_to_cds(feature, start, end=None, raise_error=True):
"""Map gene coordinates to CDS coordinates."""
result = []
for pos in gene_to_transcript(feature, start, end, raise_error=False):
result.extend(transcript_to_cds(*pos.to_tuple(), raise_error=False))
if not result and raise_error:
... | 6b0e3da826d387982b3de57e8c86e0ff1c45b0cc | 3,605,498 |
def ExecuteFunction(function, *args, **kwargs):
"""Stub method so that it can be used for mocking purposes as well.
"""
return function(*args, **kwargs) | 1b3d30c4053fe7b64f530d1c2e45518473c27b0e | 3,605,499 |
import torch
import tqdm
def validate(model, valset, iteration, batch_size, n_gpus,
collate_fn, logger, distributed_run, rank):
"""Handles all the validation scoring and printing"""
model.eval()
with torch.no_grad():
val_sampler = DistributedSampler(valset) if distributed_run else Non... | 6db04182aa04abb2059ffdfc9a9fb1414b3c3ec8 | 3,605,500 |
def klucbPoisson(x, d, precision=1e-6):
""" KL-UCB index computation for Poisson distributions, using :func:`klucb`.
- Influence of x:
>>> klucbPoisson(0.1, 0.2) # doctest: +ELLIPSIS
0.450523...
>>> klucbPoisson(0.5, 0.2) # doctest: +ELLIPSIS
1.089376...
>>> klucbPoisson(0.9, 0.2) # doc... | 12c681cbca8aad17d0362ac8991bb0507ecff03a | 3,605,502 |
import json
def api_download_version(request, preprocess_id, version):
"""Download preprocess info by version"""
if version:
# use this param for the query
version_decimal = Decimal(str(version))
else:
# Default to version 1.0
version_decimal = Decimal('1.0')
# Return... | 78af91ddf91503d1ff5bf58019b320b439903417 | 3,605,503 |
def get_confusion_matrix_elements(groundtruth_list, predicted_list):
"""
Return confusion matrix elements covering edge cases
:param groundtruth_list list of groundtruth elements
:param predicted_list list of predicted elements
:return returns confusion matrix elements i.e TN, FP, FN, TP in that or... | da7232d7c1123c706bbd280311692db1f1debc40 | 3,605,504 |
def densityice(airf=None,temp=None,pres=None,entr=None,dhum=None,
chkvals=False,chktol=_CHKTOL,airf0=None,temp0=None,pres0=None,
dhum0=None,chkbnd=False,mathargs=None):
"""Calculate icy air ice density.
Calculate the density of ice in icy air.
:arg airf: Dry air mass fraction in kg/kg. If ... | d53319867ef449f89788bacc308459a4ad86868a | 3,605,505 |
def convert_mutation_list_to_df(mutations_list, count_label):
""" Take in a list of mutations and count how many of there in a dataframe
The number of counts appears in the count_label column
This works for both single and double mutations
"""
df = pd.Series(mutations_list)
unique_counts... | b83a9b92c883c84c1fdde30122bdcdb44c5c5598 | 3,605,506 |
def r2(y_true, y_pred):
"""
R2 score
$$ 1 - \frac{MSE}{TSS}, \quad TSS= \sum\limits_{i}^{N} (y_i - \bar{y})^2) $$
$$ \bar{y} = \frac{1}{N} sum\limits_{i}^{N} y_i $$
"""
return 1. - K.mean(K.sum(K.square(y_true - y_pred))) / K.sum(K.square(y_true - K.mean(K.identity(y_true)))) | 988db482da7c094276eb8d0819193c201242533b | 3,605,507 |
def predict_map(map, predict, window_h, window_w, stride, batch_size, **kwargs):
"""Creates a probability map of predictions of the high resolution input
image `map` using a sliding window approach.
Arguments:
map: Array. Input image with dimensions of (height, width, 6).
predict: Fu... | 7c5d4da5c2d6a862cdda5c44511c19586892472e | 3,605,508 |
import torch
def create_tau( fval, gradf, d1x, d2x, smoothing_operator=None ):
"""
tau = create_tau( fval, gradf, d1x, d2x )
In:
fval: torch.FloatTensor
of shape B
gradf: torch.FloatTensor
of shape B*C*H*W
d1x: torch.FloatTensor
of shape B*C*H*W
d2x: torch.FloatTen... | 5e086908e432fbc6a34e1ce72bee84a1f467823e | 3,605,510 |
def drmaa_singlejob(cmd, jobtemplate, session, waitforever, lock):
"""
:param cmd:
:param jobtemplate:
:param session:
:param waitforever:
:return:
"""
out, err = '', ''
try:
with lock:
outpath = jobtemplate.outputPath
errpath = jobtemplate.errorPath
... | 71e5c3b0d2f1c596f3bfb08a50bd25dceb1f5f3a | 3,605,512 |
from datetime import datetime
def date_from_epoch(epoch, in_ms=None):
"""
Args:
epoch (int | float): Unix epoch in seconds or milliseconds, utc or local
in_ms (bool | None): In milliseconds if True, auto-determined if None
Returns:
(datetime.date): Corresponding datetime object
... | cb96189e82f2bd4a82e3b5b53a38cb785e35707c | 3,605,513 |
import torch
def adjust_m4i_data(source_data):
"""
Input: (iteration, segment, sample, channel)
"""
print("Begin reshaping ... {}".format(source_data.shape))
# Remove channel (last index) and cute data shape to fit into model
# model currenly has a window of 128, need to make adjustable
... | d9d44504992f0232ccf7d42dc9babca0aae60ee1 | 3,605,514 |
import json
def run_extract(config):
"""
run_extract(config)
Main function that gets configuration to run a given extract:
2 - M-extract
3 - P-Extract
3 or 4 - R-Extract
"""
category = int(config.get('category'))
if category == 2:
# Extrac... | 07ea0ce6998b1a5815be094eb32dfbfc73ac3e51 | 3,605,515 |
def format_seconds(delta):
"""
Given a time delta object, calculate the total number of seconds and return
it as a string.
"""
def _total_seconds(td):
return (td.microseconds + (td.seconds + td.days * 24 * 3600) * 10 ** 6) / 10 ** 6
return '%s' % (_total_seconds(delta)) | 60248f96a64b04be6480e27aa134c943461a6daa | 3,605,516 |
from tqdm import tqdm
from typing import List
import concurrent
def tiles_urllib(tile_metas: List[HipsTileMeta], hips_survey: HipsSurveyProperties,
progress_bar: bool, n_parallel, timeout: float) -> List[HipsTile]:
"""Generator function to fetch HiPS tiles from a remote URL."""
with concurren... | c8803a085e1bbdde8c1ae640b9c77409cd971d9c | 3,605,518 |
def defineShapePerimeter():
"""Define the perimeter and radius of each shape for different sizes"""
allowedRadius = {
"circle" : {
"small" : [16,25], "medium" : [32,40], "large" : [45,58]
},
"quadrilateral" : {
"small" : [16,32], "medium" : [40,48], "large" : [56,72]
},
"triangle" : {
"small" : [2... | 92ad63dcfe4f93fc8910bdb41d52f80169a91c1c | 3,605,519 |
def ldns_key_keytag(*args):
"""LDNS buffer."""
return _ldns.ldns_key_keytag(*args) | 4d2c91c111a3d81b6f46980a06e776ada69899a7 | 3,605,520 |
def setup_module(module):
"""Setup fixtures for module."""
class SubClassUnitTest(PotentialSampler, key="unittest"):
def __call__(self, n, *, random=None, **kwargs):
representation_type = self.representation_type # can be None
if random is None:
random = np.rand... | a57fc5624126a693c125712a1e8b527788448efc | 3,605,521 |
def ols(y, X, const=True):
"""Performs an OLS regression"""
y = np.array([y]).transpose()
ones = np.ones(y.shape)
X = np.array(X).transpose()
X = np.hstack([X, ones])
Xp = X.transpose()
beta = np.linalg.inv(Xp.dot(X)).dot(Xp).dot(y)
yp = X.dot(beta)
u = y - yp
return beta, yp, ... | f3b7076f1294ec77354fd990d011e63753ad70fe | 3,605,522 |
def write_atoms(fp, elem, pos, pseudized_charge, atomic_number_map={'H': 1, 'Li': 3, 'C': 6}):
""" create and fill the /atoms group
!!!! QMCPACK does NOT check valence_charge, pseudized_charge matters?
Args:
fp (h5py.File): hdf5 file object
elem (np.array): array of atom names
pos (np.array): array o... | 5441cf2b2bc2a22ac35e700f9b5b53339f532ab9 | 3,605,523 |
def clpool():
"""clpool()"""
return _cspyce0.clpool() | b2ef48500759fe89db1f42f95584aaa65b8bac7a | 3,605,524 |
def reset_db(ctx, with_testdb):
"""
Init and seed automatically.
:param with_testdb: Create a test database
:return: None
"""
ctx.invoke(init, with_testdb=with_testdb)
ctx.invoke(seed)
return None | a35a6cc53653edb7aeee3087871a4969d52b6882 | 3,605,525 |
def dataset_detail(request, dataset_id):
"""Renders individual dataset detail page."""
active_dataset = get_object_or_404(Dataset, pk=dataset_id)
datadict_id = active_dataset.data_dictionary_id
datadict = DataDictionaryField.objects.filter(
parent_dict=datadict_id
).order_by('columnIndex')
... | dd033c8264120753642692837f6c3076d845a648 | 3,605,526 |
def scanner_position(n, t):
"""Return positin of scanner of range n at time t."""
n1 = n - 1
return n1 - abs(t % (2*n1) - n1) | 3651f5997b370e703e09ff1f97c1d7d249cf286c | 3,605,527 |
from datetime import datetime
def get_rolling_average(date, df, column):
"""Calculate rolling average from a column.
We apply mean for each values of a specific column
within the range of last week date and date itself
"""
lowestDate = datetime.strftime(
datetime.strptime(date, "%Y-%m-%d"... | 5deff4293d72f272569f228dc66b9686405e7982 | 3,605,528 |
import numba
import functools
def compile_function(
_func: callable = None,
*,
compilation_mode: str = None,
**decorator_kwargs,
) -> callable:
"""A decorator to compile a given function.
Numba functions are by default set to use `nogil=True` and `nopython=True`,
unless explicitly defined... | 261147323278fa9eefaf8537aec6b5886f3a10e3 | 3,605,529 |
from re import T
def create_php(idx, ar, rip='0x????????', pc=None):
"""Collect metadata for a PHP frame.
All arguments are expected to be gdb.Values, except `idx'.
"""
func = ar['m_func']
shared = rawptr(func['m_shared'])
# Pull the function name.
if not shared['m_isClosureBody']:
... | 7b28d16349031bcd97593ab496ee092d85109a69 | 3,605,530 |
def equal_images(img1, img2):
"""Adapted from Nicolas Hahn:
https://github.com/nicolashahn/diffimg/blob/master/diffimg/__init__.py
"""
if img1.mode != img2.mode or img1.size != img2.size or img1.getbands() != img2.getbands():
return False
diff_img = ImageChops.difference(img1, img2)
sta... | 811e993c4c3fc0225f4917039ac4df320dd0429f | 3,605,531 |
import socket
import struct
def discover(service, timeout=2, retries=1):
"""discover pilight servers"""
group = ("239.255.255.250", 1900)
message = "\r\n".join([
'M-SEARCH * HTTP/1.1',
'HOST: {0}:{1}'.format(*group),
'MAN: "ssdp:discover"',
'ST: {st}', 'MX: 3', '', ''])
... | 6e220b66de64b00d18d71883791dd2d1ad5d9a96 | 3,605,532 |
def valid_date_version(s: str) -> bool:
"""Check that the string is a valid date versions string."""
return _validate_date_fmt(s, DATE_VERSION_FMT) | 4b81a9ddaa6dd072c9f29e0a287eb7d4ed759cf5 | 3,605,533 |
def calc_pq(hmm_annotation, fs, p_states=P_STATES, q_state=Q_STATE, r_state=R_STATE):
""" Calculate PQ based on HMM prediction.
Parameters
----------
hmm_annotation : numpy.array
Annotation for the signal from hmm_annotation model.
fs : float
Sampling rate of the signal.
p_state... | e78b3257b7af6d3c08f46936b922a5ecafb15b00 | 3,605,535 |
import json
def zp3111_state_fixture():
"""Load the zp3111 4-in-1 sensor node state fixture data."""
return json.loads(load_fixture("zwave_js/zp3111-5_state.json")) | c24dd3ae6f26d4a4f346c32cbcb970fc2e03cc05 | 3,605,536 |
from typing import TypeVar
from typing import Callable
def literal_substitute(t, type_map):
"""Make substitutions in t according to type_map, returning resulting type."""
if isinstance(t, TypeVar) and t.__name__ in type_map:
return type_map[t.__name__]
elif isinstance(t, TuplePlus):
subbed... | 4b44e42093800f3d0e8e2cdea7f85fa2b2c7a0e3 | 3,605,537 |
def get_18(input_shape, num_classes, unit_cls=ResidualUnit):
"""As described in [1]"""
_validate_non_bottleneck_unit(unit_cls)
return get(input_shape, num_classes, unit_cls, [2, 2, 2, 2]) | 1da78467bd96184e6379ca0978d05647660794e9 | 3,605,538 |
def generate_values(TR,P=101325):
""" Starting with T,R as inputs, generate all other values """
T,R = TR
psi_w = CP.HAPropsSI('psi_w','T',T,'R',R,'P',P)
other_output_keys = ['T_wb','T_dp','Hda','Sda','Vda','Omega']
outputs = {'psi_w':psi_w,'T':T,'P':P,'R':R}
for k in other_output_keys:
... | 5e557b1ef8943d2848874474a204da5c34125e4b | 3,605,539 |
def _query_comcat(start_time, end_time, min_magnitude=2.50,
min_latitude=31.50, max_latitude=43.00,
min_longitude=-125.40, max_longitude=-113.10, extra_comcat_params=None):
"""
Return eventlist from ComCat web service.
Args:
start_time (datetime.datetime): start ti... | f85dc83bfff42bdbb35df1d63cd484a348cdebf7 | 3,605,540 |
from functools import reduce
def reduce_2array(A, B, fun, axis=-1, initializer=0.0, keepDims=False):
"""
Compute the dot product along the given axis.
a and b must have exactly the same shape, as the axis dimension will be reduced by element-wise multiplication and summation along that dimension.
Args:
- a, ... | 0875c00fb71808a926b41d771ea260692d8a5a10 | 3,605,541 |
def get_advice_tab_context(case, caseworker, queue_id):
"""Get contextual information for the advice tab such as the tab's URL and
button visibility, based off the case, the current user and current user's queue.
"""
team_alias = caseworker["team"]["alias"]
queue_alias = next((item["alias"] for item... | ff3164724d0a9e4aecf5f9e9a27ce909553fd7f4 | 3,605,542 |
def find_tree_root(tree, key):
"""Find a root in a tree by it's key
:param dict tree: the pkg dependency tree obtained by calling
`construct_tree` function
:param str key: key of the root node to find
:returns: a root node if found else None
:rtype: mixed
"""
result = ... | 372bf64f3230fe01d4369ae79bd61edc503b0fd6 | 3,605,543 |
def get_initializer(initializer_config, seed=None):
"""Get variable initializer.
Args:
- initializer_config: Configuration for initializer.
Returns:
initializer: Instantiated variable initializer.
"""
if 'type' not in initializer_config:
raise ValueError('Initializer missi... | 7eb8f1d8bd21cc7b4d004e4034b2987a4da71765 | 3,605,544 |
def einsum2(*args, **kwargs):
"""
einsum2(subscripts_str, arr0, arr1)
or,
einsum2(op0, subscript_list0, arr1, subscript_list1,
output_subscript_list)
This function is similar to einsum, except it only operates
on two input arrays, does not allow diagonal operations
(repeated sub... | 749c9f9a66a26dd0595a1c0a37ba02ccc2516557 | 3,605,546 |
def convert_str_to_list(sequence: str, is_ordered_sequence: bool = True, is_first_term_seq_name: bool = True):
"""
sequence: A string that contains a comma seperated numbers
is_first_term_seq_name: True to drop the first term (i.e. A01255,1,3,5, ...)
return: A list of integers in a list (String ---> Lis... | f73213ae3484e00824920722eb58368bb116886b | 3,605,547 |
def get_rotation_matrix(zone, verbose=False):
"""Calculates the rotation matrix to rotate the zone axis parallel to the cartasian z-axis.
We use spherical coordinates to first rotate around the z-axis and then around the y-axis.
This makes it easier to apply additional tilts, than to use the cross produc... | 87655da0deeceef16f241ed4038d53c9727167f1 | 3,605,548 |
def create_user(db: Session, user: schemas.UserCreate):
"""
Function to create user to `users` table and
password to `users_hashes` table.
Uses schemas.User to add to models.User
models.User attributes:
- user_id: int, non-nullable, unique
- username: str, non-nullable, unique
... | 884acde0899c8e88df45d6fa43e01c93c9873da8 | 3,605,549 |
def _terms_match(t1, t2):
"""check that all the fields in the first term t1 are in t2 and
have the same values
"""
for k, val in t1.items():
if k not in t2:
if val:
return False
else:
if k == 'parents' or k == 'slim_terms' or k == 'source_ontol... | 476a03057953d648d9097c9c2c920eaf0f5d44ed | 3,605,550 |
def get_obs_lsstSim_camera(log_level=lsstLog.WARN):
"""
Get the obs_lsstSim CameraMapper object, setting the default
log-level at WARN in order to silence the INFO message about
"Loading Posix exposure registry from .". Note that this only
affects the 'CameraMapper' logging level. The logging level... | 8cfda186f667cb88b4cbfd805dd04bfc735e0a34 | 3,605,551 |
def volume_down(y: np.ndarray, db: float):
"""
Low level API for decreasing the volume
Parameters
----------
y: numpy.ndarray
stereo / monaural input audio
db: float
how much decibel to decrease
Returns
-------
applied: numpy.ndarray
audio with decreased volum... | ac1d47681e25b4550f9c44d25e36ded9918e3b6c | 3,605,553 |
def get_random_idx(dataset, n_samples, seed=10):
"""Take random n images from target for comparison"""
n = n_samples
if len(dataset) < n:
n = len(dataset)
idx = list(range(len(dataset))) # Set pseudo idx list
currRandom = Random(seed)
r_idx = currRandom.sample(idx, n) # Sample idx
... | 930ad883c48d09f9657eb7c0bd6bf10037b77c47 | 3,605,554 |
def now():
"""<p>Get the current temperature, humidity and dewpoint for the
requested OMEGA iServer(s).</p>
<h3>Parameters</h3>
<ul>
<li>
<b>serial</b> : string (optional)
<p>The serial number(s) of the OMEGA iServer(s) to get the data from.
If requesting data from multipl... | 0c828aab44c124cc6f295e66c498eaa8a37ac874 | 3,605,555 |
def test_mixin_mi():
"""Does comparable mixin works w/ MI (other __new__'s get called)"""
class TestMixin(object):
def __new__(cls, *a, **ka):
newcls = super(TestMixin, cls).__new__(cls, *a, **ka)
newcls.foo = 'bar'
return newcls
class TestClass(TestMixin, Compara... | 40c0637107323e874724af863a98c2c435b14dfd | 3,605,556 |
def get_enrollment_attributes(user_id, course_id):
"""Retrieve enrollment attribute array"""
return _ENROLLMENT_ATTRIBUTES | 398f1a55287fa25af33e743629228801679d63b8 | 3,605,557 |
from pathlib import Path
import venv
def _create_new_venv() -> Path:
"""Create a new venv.
Returns:
path to created venv
"""
# Create venv
venv_dir = _create_tmp_dir()
venv.main([str(venv_dir)])
return venv_dir | f7874f4607476f98ba8defb8d5eee3298788dbfb | 3,605,558 |
def predict(features, weights):
"""
Given the input data features and the weight calls forward propogation and returns the index of value
the neural network is most confident in.
:param features: Numpy matrix of input data used to make prediction.
Each row is a training example an... | d4819903bdd481d3dacffb46d98521484eeffa3d | 3,605,559 |
from typing import Collection
def get_user_xp_rank(uid: int):
"""
Returns the xp rank of a user.
@param uid: int - The unique identifier of the user.
@return: rank: int
"""
try:
users: Collection = _db[config.mongodb_users]
xp = get_user(uid).xp
rank = users.count_docu... | 40ed043af2d57c87f6b051ea539c10924be56a54 | 3,605,560 |
def file2matrix(filename):
"""
Desc:
导入训练数据
parameters:
filename: 数据文件路径
return:
数据矩阵 returnMat 和对应的类别 classLabelVector
"""
fr = open(filename)
# 获得文件中的数据行的行数
numberOfLines = len(fr.readlines())
# 生成对应的空矩阵
# 例如:zeros(2,3)就是生成一个 2*3的矩阵,各个位置上全是 0
returnMat = zeros((... | 7ddc35998fcaea8e3f1877eec561ef710d2946fe | 3,605,561 |
def toFile(chant, filepath=None, showOptions=True, showSections=False,
showWords=False, showSyllables=False, showNeumes=False,
showMetadata=False, showMisalignments=True):
"""Export a Chant to an HTML file.
Args:
chant (chant21.Chant): A chant object
filepath (string, optional): If... | a83b0c94920c97daa2721e486ffeb3c56dc1444a | 3,605,563 |
import torch
def cbf_qp_filter(x, u_ref, relaxation_penalty):
"""Use the CBF QP to filter a provided reference control signal
args:
x: an N x 6 numpy array of states (x, y, z, vx, vy, vz)
u_ref: an N x 3 numpy array of controls (fx, fy, fz)
relaxation_penalty: the penalty to use for C... | 1c2cef18ed14c19d26c65803605cc32f4b6e65e8 | 3,605,567 |
def filter_chants_without_notes(chants, logger=None):
"""Exclude all chants without notes"""
notes_pattern = r'[89abcdefghjklmnopqrs\(\)ABCDEFGHJKLMNOPQRS]+'
contains_notes = chants.volpiano.str.contains(notes_pattern) == True
return chants[contains_notes] | 98324a2b9c17d975ebfc7860ad9ca38e65db481e | 3,605,568 |
def correct_eval_poly(d):
"""This function evaluates the polynomial poly at point x.
Poly is a list of floats containing the coeficients
of the polynomial
poly[i] -> coeficient of degree i
Parameters
----------
poly: [float]
Coefficients of the polynomial,
where poly[i... | 5a0042c0fb28a5fa4891f86b8b8fa70516fbed34 | 3,605,569 |
def parse_args_and_kwargs(parser, bits):
"""
Parses template tag arguments and keyword arguments
Returns a tuple ``args, kwargs``.
Usage::
@register.tag
def custom(parser, token):
return CustomNode(*parse_args_and_kwargs(parser,
token.split_contents()[1:]))... | 4075a1189ec1d2fbb331b6481f6599446d024d1d | 3,605,570 |
def stim_circuit_to_cirq_circuit(circuit: stim.Circuit) -> cirq.Circuit:
"""Converts a stim circuit into an equivalent cirq circuit.
Qubit indices are turned into cirq.LineQubit instances. Measurements are
keyed by their ordering (e.g. the first measurement is keyed "0", the second
is keyed "1", etc).
... | 82459bf32cc22ea2f4d0b9860ff485c24691a5aa | 3,605,571 |
def admit_dir(file):
""" create the admit directory name from a filename
This filename can be a FITS file (usually with a .fits extension
or a directory, which would be assumed to be a CASA image or
a MIRIAD image
"""
loc = file.rfind('.')
ext = '.admit'
if loc < 0:
return file ... | 12cf941054cdd1783f83095aa2e0bf1f3a9d980d | 3,605,573 |
import torch
def zeros(shape, dtype=None, device = None):
"""
Creates a tensor with all elements set to zero.
Parameters
----------
shape : A list of integers
a tuple of integers, or a 1-D Tensor of type int32.
dtype : tensor
The DType of an element in the resulting Tensor
... | e8e7b18a1f0d2999152504536709388440c56f1a | 3,605,574 |
def _convert_timedelta_to_auto_off(full_time: timedelta) -> str:
"""Convert timedelta object for auto-shutdown to hexadecimal.
Args:
full_time: timedelta object represnting the auto-shutdown time.
Return:
Hexadecimal represntation of the full_time argument.
Raises:
aioswitcher.erros... | 987fd0fca7acf1e108ecafd1c1cb29cb814f3434 | 3,605,577 |
import functools
def output_validates_with_args(**kwargs_validators):
"""Decorator to validate output.
The validator can take the arguments of the decorated
function as its arguments.
"""
def decorator(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
obj = f... | b948f6e3a470e037ccf4aff97f793ee357dd36c1 | 3,605,578 |
def seed_target_indices(seeds, targets):
"""Generate indices parameter for seed based connectivity analysis.
Parameters
----------
seeds : array of int | int
Seed indices.
targets : array of int | int
Indices of signals for which to compute connectivity.
Returns
-------
... | 22eb5527d7dd769a67fc299d84de2457af5d938b | 3,605,579 |
import random
def chapter_uid_generator() -> str:
"""Random number generator for Mastroka chapter UIDs."""
return str(random.choice(range(int(1E18), int(1E19)))) | 024ea43a93d3e94576324364375542338b859d13 | 3,605,581 |
def _send_tiddler_revisions(environ, start_response, tiddler):
"""
Push the list of tiddler revisions out the network.
"""
store = environ['tiddlyweb.store']
tmp_bag = Bag('tmp', tmpbag=True, revbag=True)
try:
for revision in store.list_tiddler_revisions(tiddler):
tmp_tiddle... | d78b5a6e3a466b7c722dba5e2d09ca744888c53f | 3,605,583 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.