content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
import torch
def gaussian_kernel1d(
kernel_size: int, sigma: float, device: torch.device, dtype: torch.dtype
):
"""1D Gaussian kernel."""
khalf = (kernel_size - 1) / 2.0
x = torch.linspace(-khalf, khalf, steps=kernel_size, dtype=dtype, device=device)
pdf = torch.exp(-0.5 * (x / sigma).pow(2))
... | f76fc18500160510f162e93bb68803a36ce4633a | 54,489 |
def interrupt() -> int:
"""interrupt hparams
"""
return 2 | 6ba8b856ae968283db38a12222bced4217f83868 | 54,490 |
def fmtquant(quant, *args, **kwargs):
"""Give python Quantity object (or UncertainQuantity) and any
arguments that fmtuncert takes.
Additional arguments:
units: Set True to append units (will make parentheses around
values). Formats as tex formula if `tex=True` is set.
... | 510f60189255bb81fd1b883f3c0e6b31598a9058 | 54,491 |
def remove_claims(claim_id, summary=None, revision=None, mediawiki_api_url=None, login=None, allow_anonymous=False, user_agent=None):
"""
Delete an item
:param claim_id: One GUID or several (pipe-separated) GUIDs identifying the claims to be removed. All claims must belong to the same entity.
:type clai... | b19c9dccff2526807e6bd83206a03e1ef0752c75 | 54,492 |
def encrypt_file(filepath):
"""Encrypt file contents to base64.
:param filepath: the path of the file.
"""
try:
# if it starts with ~
# os.path.expanduser
with open(filepath) as inf:
file_contents = inf.read()
return file_contents.encode('base64')
exce... | 6107418061dd26a5bb21253c376796bdec673783 | 54,493 |
def flex_add_argument(f):
"""Make the add_argument accept (and ignore) the widget option."""
def f_decorated(*args, **kwargs):
kwargs.pop('widget', None)
return f(*args, **kwargs)
return f_decorated | 2a93e5af569fcf0ec51f469f0b074379d3d663ff | 54,494 |
async def healthcheck_handler(_):
"""Demonstrates a simple healthcheck example.
"""
data = {"status": "ok"}
return healthcheck_response(data) | 12e6a14f9a593799d2fadaac05b80e500f1db769 | 54,495 |
def readMember(request, id=id):
"""メンバー読取"""
template = loader.get_template('webapp1/members/read.html')
# -------------------------
# 1
# 1. host1/webapp1/templates/webapp1/members/read.html を取得
# -----------... | bc52b62c618f0b02185c8afd0ae6f934498baa43 | 54,496 |
import numpy
def GQSignal_fetch_bootstrap_singal_day(start,
end,
frequence='day',
market_type=QA.MARKET_TYPE.STOCK_CN,
portfolio='myportfolio',
... | e418114f4c862e39026427823e7a48e70ec8cda2 | 54,497 |
def param(name, *args, **kwargs):
"""
A wrapper for `tf.Variable` which enables parameter sharing in models.
Creates and returns theano shared variables similarly to `tf.Variable`,
except if you try to create a param with the same name as a
previously-created one, `param(...)` will just retur... | 95d3a1011a808a326802399fbf0ea94f885491f0 | 54,498 |
def Bulk_emails():
"""批次寄信"""
users = [
{"name": "xxxxxxxxxx", "email": "xxxxxxxxxx"},
{"name": "xxxxxxxxxx", "email": "xxxxxxxxxx"},
{"name": "xxxxxxxxxx", "email": "xxxxxxxxxx"},
{"name": "xxxxxxxxxx", "email": "xxxxxxxxxx"},
{"name": "xxxxxxxxxx", "email": "xxxxxxxxxx"... | 4032c17a63a9f4e4ef4c628a0c726359b2c7ec77 | 54,500 |
def model2():
"""Build a convnet with dropout and batch normalisation."""
input = layers.Input(shape=input_shape[1:], dtype=np.float)
x = layers.Conv1D(10, 5, activation='relu', name='CONV_1')(input)
x = layers.Conv1D(10, 5, activation='relu', name='CONV_2')(x)
x = layers.BatchNormalization()(x)
... | 5f60618cd5f9a7f9597d4ae9e066ed08411331a1 | 54,501 |
def in_subnet(cidr, addrs=None):
"""
Returns True if host is within specified subnet, otherwise False
"""
for address in addrs:
if ip_in_subnet(address, cidr):
return True
return False | 6a454bbbf2ce75584d094fe815c8464676efb45f | 54,502 |
from typing import AnyStr
import secrets
def constant_time_compare(val1: AnyStr, val2: AnyStr) -> bool:
"""Return True if the two strings are equal, False otherwise."""
return secrets.compare_digest(
encoding.force_bytes(val1), encoding.force_bytes(val2)
) | d28e1881f3da840b863b11ee5a12c549cb9de037 | 54,503 |
def make_company_node(c: dict) -> Node:
"""Create new Company node for dict
"""
all_attributes = c.get('all_attributes', {})
return Node('Company',
name=c['name'],
company_number=c['company_number'],
federal_state=all_attributes.get('federal_state'),
... | 3fbf35b3133f8eb7e865e6e703de061ed7e72c15 | 54,504 |
def problem_reciprocal_exponential(x):
"""Return recrprocal exponential function."""
return np.exp(-x) | 070e39a1d116907d2ce29527f28e02d57aca3208 | 54,505 |
import datetime
from azure.cli.core._session import VERSIONS
def get_cached_latest_versions(versions=None):
""" Get the latest versions from a cached file"""
if not versions:
versions = _get_local_versions()
if VERSIONS[_VERSION_UPDATE_TIME]:
version_update_time = datetime.datetime.strpt... | 7ec17fe7768295d7108bc857d252378300bb8ee0 | 54,506 |
def get_time(raw_time):
"""
Get treated time value from the raw provided time.
# 2020/09/05T05:21:48z
# 2020-09-05T05:21:48z
# dtr = dt.replace("/","-")[:-1]
:param raw_time: <string>
:return treated_time: <datetime>
"""
treated_time = raw_time.replace("/", "-")
return treate... | cccdfc8710b63c2f273fa0e8c638c5fc6e66a1b8 | 54,507 |
import math
def noise_floor(nf=1, bandwidth=1, noise_temp=290):
"""
Calculate noise floor of a receiver.
:param nf: Noise figure in dB
:param bandwidth: bandwidth in Hz
:param noise_temp: noise temperature in Kelvin
"""
return (
10 * math.log10(KBOLTZMAN * noise_temp * 1000) + nf ... | 2c951b40f9526b9d3b247614d4af9679efc2983e | 54,509 |
def get_round_from_jitemid(jitemid, cursor):
"""Take a jitemid, return a round."""
round_jitemid_mapping = { (0, 'br negative one') }
# if jitemid is a key in the dictionary:
# return the value
# otherwise just return "UNKNOWN ROUND"
return round | 9242e098d31312c3181377d5bb8f4dfaf33c29ca | 54,510 |
import six
def _ConvertInteger(value):
"""Convert an integer.
Args:
value: A scalar value to convert.
Returns:
The integer value.
Raises:
ParseError: If an integer couldn't be consumed.
"""
if isinstance(value, float) and not value.is_integer():
raise ParseError('Couldn\'t parse integer... | d5ca07d28827729df1bac9f1d446c623804fb4ba | 54,512 |
import logging
def to_segments(data, num=32):
"""
These code is taken from:
https://github.com/rajanjitenpatel/C3D_feature_extraction/blob/b5894fa06d43aa62b3b64e85b07feb0853e7011a/extract_C3D_feature.py#L805
:param data: list of features of a certain video
:return: list of 32 segments
"""
... | 378da87dbe710ed4e27580e6fd166c14afeab605 | 54,513 |
async def discord_has_token(discord_id: int, db: AsyncSession = Depends(get_db_session)):
"""Return if a user has a valid token"""
profile = await discord_users.get_profile_from_discord_id(discord_id)
if not profile:
return DestinyHasTokenModel(token=False, value=None)
no_token = await discord_... | 575f87a27ecee04b9a411db24d182f64570c4309 | 54,515 |
def tokenize_text(text):
"""
Tokenizes and tags a given text.
Args:
text (str): Text to process.
Returns:
List(Tuple[str, str]): List of word-tag pairs.
"""
nltk.download('punkt')
nltk.download('averaged_perceptron_tagger')
tokens = nltk.word_tokenize(text)
tagged =... | d61a696a0886a8aadc4aa9b202cbc246fb393816 | 54,517 |
import torch
def kl_loss_diag(mean, logvar):
"""
KL divergence of normal distributions with diagonal covariance and standard multivariate normal.
:param mean1: mean of distribution 1
:param logvar1: logarithm of the covariance diagonal of distribution 1
:return: KL divergence of the given distrib... | e8cedc4ccebc120a4367f9ce52ac96210beb0b5f | 54,518 |
def randomize(df, seed=None):
"""Develop a randomization function that randomizes all of a dataframe's cells
then returns that randomized dataframe. This function also accepts a random
seed for reproducible randomization"""
df = df.copy()
columns = df.columns
df = shuffle(df[columns], random_st... | 1ddb9623732ff16ce464b3b0fee4728c34a1e152 | 54,519 |
def add_class(add, class_):
"""Add to a CSS class attribute.
The string `add` will be added to the classes already in `class_`, with
a space if needed. `class_` can be None::
>>> add_class("foo", None)
'foo'
>>> add_class("foo", "bar")
'bar foo'
Returns the amended cl... | b5f12ea7a5c573b65ebbd84d987a5de5090e33d0 | 54,520 |
def get_model(point_cloud, is_training,num_classes,normal = False,bn_decay=None,bn=True,
num_keypoints = 192,k = 16,nsample = 32):
""" Classification PointNet, input is BxNx3, output BxNUM_CLASSES """
b = point_cloud.get_shape()[0].value
n = point_cloud.get_shape()[1].value
end_points = ... | c8334171394f4d3e872ef1e9d86af75225e86a47 | 54,521 |
import _random
def preview_synthetic_training_data(data,
target,
backgrounds=None,
verbose=True,
**kwargs):
"""
A utility function to visualize the synthetically gene... | cbcd15c732d6a6ed8fa29d584c497d20bf28f19e | 54,522 |
def guessColorName(nameMe):
"""Return a tuple (distance, guessed human-name of a color)."""
return min(colors, key=lambda x: distance(nameMe, x)) | b1562865c665ff453f309675cc31bb049e88cbbb | 54,523 |
import re
def to_lower_camel_case(str_to_convert):
"""
This function will convert any string with spaces or underscores to lower camel case string
:param str_to_convert: target string
:return: converted string
"""
if type(str_to_convert) is not str:
raise TypeError("The method only tak... | 8bfd591fcbfcff51b463596266cba1403f2d6153 | 54,524 |
def ordinal_suffix(n):
"""Return the ordinal suffix for a positive integer
>>> ordinal_suffix(0)
''
>>> ordinal_suffix(1)
'st'
>>> ordinal_suffix(2)
'nd'
>>> ordinal_suffix(3)
'rd'
>>> ordinal_suffix(4)
'th'
>>> ordinal_suffix(11)
'th'
>>> ordinal_suffix(12)
'th'
>>> ordinal_suffix(13)
... | 53617737aaf28c2d239301358f01d1b0cea9f6cb | 54,525 |
def sentence_to_token_ids(sentence, vocabulary, max_sequence_length):
"""Convert a string to a list of integers representing token-ids."""
words = sentence.strip().split()
if len(words) > max_sequence_length:
words = words[:max_sequence_length]
return [vocabulary.get(w, UNK_ID) for w in words] | 77ab881e8da7400a1db388e4db393e39b2aaab8f | 54,526 |
def _collect_facts(resource):
"""Transfrom cluster information to dict."""
facts = {
'identifier' : resource['ClusterIdentifier'],
'create_time' : resource['ClusterCreateTime'],
'status' : resource['ClusterStatus'],
'username' : resource['MasterUs... | a881451ac409288b93160d4cec4b27a3547fe3f9 | 54,527 |
def leave_one_in(feature_groups):
"""For each group, return a copy of just that group
Args:
feature_groups (list) The feature groups to apply the strategy to
Returns: A list of feature dicts
"""
return feature_groups | 5933925d909b6777f916b6bc585734dd768477b3 | 54,530 |
import queue
def push(ui, repo, patch=None, **opts):
"""push the next patch onto the stack
By default, abort if the working directory contains uncommitted
changes. With --keep-changes, abort only if the uncommitted files
overlap with patched files. With -f/--force, backup and patch over
uncommitt... | 9c37243b75038c23faec50b774efed6af9bad1ed | 54,531 |
def disable() -> dict:
"""Disables log domain, prevents further log entries from being reported to the client."""
return {"method": "Log.disable", "params": {}} | f5be0972e43d24fc4b69fbeb2c13850d68af52bf | 54,532 |
def repeat_each_element(element: tf.Tensor, number_of_repeats: int) -> tf.data.Dataset:
"""
A dataset mappable function which repeats the elements a given number of times.
:param element: The element to map to to repeat.
:param number_of_repeats: The number of times to repeat the element.
:return: ... | d2bc479a5b2eced6a3c906e14ce964fd4d0c3d84 | 54,533 |
def ncc(I, J):
"""
Code comes from:
Unsupervised Learning for Fast Probabilistic Diffeomorphic Registration
Adrian V. Dalca, Guha Balakrishnan, John Guttag, Mert R. Sabuncu
MICCAI 2018.
"""
eps = 1e-5
# assumes I, J are sized [batch_size, *vol_shape, nb_feats]
ndims = len(I... | fb29e1381ab0d8d3ca0521792d4d67d82d5e2b32 | 54,535 |
def _get_subtopics(
corpus, dictionary, num_topics, num_words, depth, passes=10
):
"""The recursive function"""
ldamodel = models.ldamodel.LdaModel(
corpus,
num_topics=num_topics,
id2word=dictionary,
passes=passes
)
lda_output = {}
topics = ldamodel.ge... | 1b509e77b0b95a6ef55c2963ed5df3c62b59f3ee | 54,537 |
def normalizeimage(image, depth=256, verbose=False):
"""Normalize image to chosen bit depth"""
if verbose:
print 'Normalizing image from [' + str(numpy.min(image)) + ':' + str(
numpy.max(image)) + '] to',
normalizedimage = ((image - numpy.min(image)) * (depth / (numpy.max(
image)... | bddbb1bb1538e6ef47dfb88fbf394fe10cec0388 | 54,538 |
def _strftime(d):
"""
Format a date the way Atom likes it (RFC3339?)
"""
return d.strftime('%Y-%m-%dT%H:%M:%SZ%z') | 1eebf1bff9c68ba4649f1377f16b4b9feb737f01 | 54,539 |
from typing import Union
from typing import List
def _extract_process_nodes(cube: Union[dict, DataCube], process_id: str) -> List[dict]:
"""Extract process node(s) from a data cube or flat graph presentation by process_id"""
if isinstance(cube, DataCube):
cube = cube.flat_graph()
return [d for d i... | 353eeaaf36d26fe8f460246d22327f4032fd10f8 | 54,541 |
import imp
import marshal
def read_pyc(filename):
"""
Read the code inside a bytecode compiled file if the MAGIC number is
compatible
Returns:
a code object
"""
data = read_file(filename, 'rb')
if not is_gae and data[:4] != imp.get_magic():
raise SystemError('compiled code... | 660f352b25467f12b8db1d80fb4140dc679c9b94 | 54,542 |
def gravity_and_floor(x, y, floor, g=1, scale=100):
"""
A hard wall at the bottom of the view and a linear downward potential.
Note: y increases in the downward direction.
"""
v = np.zeros((len(y), len(x)))
v += g*np.abs(y[:,None]-floor)
v[y>floor] = scale
return v | fdaa202d92813a383b7061506e6737a7e96476b5 | 54,543 |
def scan(a, dim=0, op=BINARYOP.ADD, inclusive_scan=True):
"""
Generalized scan of an array.
Parameters
----------
a : af.Array
Multi dimensional arrayfire array.
dim : optional: int. default: 0
Dimension along which the scan is performed.
op : optional: af.BINARYOP. def... | d1697420593e1fb82d93a333d6afd23df233b3f9 | 54,545 |
def get_centor(feature, centors):
"""
迭代计算聚类中心
:param node: 待判断数据[r,g,b]
:param centors: init[cen1,cen2...]
:param classes: [[node of class1],[node of class2],......[node of classk]]
:return: cens=[cen1,cen2...]
"""
k = len(centors)
# 建立k个类别数据的空集合
classes = [[] for _ in range(k)]... | e0dd6e62f76a3aad0f01fd87f0da6b697a49431b | 54,546 |
def food(request):
"""Show food.
"""
tracker = init_tracker(request)
tracker.track_page_view("http://0.0.0.0:8000/food", "food_page")
food = Food.objects.filter(owner=request.user).order_by('date_added')
is_empty = True
for f in food:
if f.quantity > 0:
is_empty = False
... | 0fbc0677375548d0560b61a325ee5da74cfdb69f | 54,547 |
from ..plot_utils import make_3d_axis, Frame
def plot_basis(ax=None, R=None, p=np.zeros(3), s=1.0, ax_s=1,
strict_check=True, **kwargs):
"""Plot basis of a rotation matrix.
Parameters
----------
ax : Matplotlib 3d axis, optional (default: None)
If the axis is None, a new 3d axi... | f53a5edf1f33050a7dfb9a3f8f4ef4f01a25b6f4 | 54,548 |
def slicify(index, length=-1):
"""
Takes an index as an instance of a list, a tuple, an np.ndarray, an int, or
anything else. In the case of a list, a tuple, or a np.ndarray return a
slice if possible, else return an np.ndarray. In the case of an int, return
slice(int, int+1). In the case of anythin... | 2885163f9affc7c3d886e3ba3a070dd3f6287136 | 54,549 |
def run_async_asyncio(func, *args, **kwargs):
"""
Runs an Async Function in a Sync Call using asyncio
in sync calls
"""
if not iscoroutinefunction(func):
func = AsyncFunction(func)
coro = func(*args, **kwargs)
return asyncio_run(coro) | 4f746a538579013090b64dc45d5204988e0ca60a | 54,550 |
from typing import Iterable
from typing import Callable
def get_combined_revision(functions: Iterable[Callable]) -> forge.Revision:
"""Combine the parameters of all revisions into a single revision"""
params = {}
for func in functions:
params.update(forge.copy(func).signature.parameters)
retur... | 643128e545fc4a6f54d3d2314d62c986ea7971b6 | 54,551 |
import collections
def merge(d, u):
"""
Recursively updates a dictionary.
Example: merge({"a": {"b": 1, "c": 2}}, {"a": {"b": 3}}) = {"a": {"b": 3, "c": 2}}
"""
for k, v in u.items():
if isinstance(v, collections.Mapping):
r = merge(d.get(k, {}), v)
d[k] = r
... | d96d95fd7a236429fa5c278c800832205e073cd4 | 54,553 |
def _numba_i0(x):
"""
computes i0 to 15 digits
"""
if x < 0:
x = -x
if x <= 8.0:
y = x/2.0 - 2.0
return np.exp(x)*_numba_chbevl(y, i0_lt8)
else:
y = 32.0/x - 2.0
return np.exp(x)*_numba_chbevl(y, i0_gt8)/np.sqrt(x) | fded0baf18e8fca5b5463a7ecf633a510ee629fe | 54,554 |
def parse_args(parser):
"""
Parse commandline arguments.
"""
parser.add_argument('--waveglow', type=str, required=True,
help='Full path to the WaveGlow model checkpoint file')
parser.add_argument('-o', '--output', type=str, required=True,
help='Directo... | f0333da61342bd40055894330aa7e0e0eadf434a | 54,555 |
import math
def track_day_test(year, month, day, hour, lat, lon, elevdlim=-2.5):
"""
Given date, time, lat and lon calculate if the sun elevation is > elevdlim.
If so return daytime is True
This is the "day" test used by tracking QC to decide whether an SST measurement is night or day.
Th... | 2496099eab7ed970236d59c69949ce1ef4f93374 | 54,556 |
def arn_has_slash(arn):
"""Given an ARN, determine if the ARN has a stash in it. Just useful for the hacky methods for
parsing ARN namespaces. See
http://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html for more details on ARN namespacing."""
if arn.count("/") > 0:
return True
... | a3c36eba79bc572ae5389aea9c0ef0a0924cc7b3 | 54,557 |
from typing import Callable
from typing import List
def calculate_gradient(f: Callable, x: List[float]) -> np.array:
"""Return the gradient of a function at a given point
Args:
f (Callable): function in consideration
x (List[float]): point at which gradient is evaluated
Returns:
... | cf9866f21006e5ad3c7af8b5328a8224caae8c05 | 54,558 |
import typing
def keccak_224(data: typing.Optional[bytes] = None) -> Keccak:
"""Returns a 224-bit keccak hash object"""
return Keccak(c=448, r=1152, n=224, name='keccak_224', data=data) | e34482d3fe4d4a3ad9976ad7647b6409f8a7768e | 54,560 |
def decr_id(id, id_remove):
"""Decrement a single id, with the aim of closing the gap at
id_remove. The logic used is similar to that incr_id_after.
"""
k = len(id_remove)
if len(id) >= k and id[:k-1] == id_remove[:k-1] and id[k-1] > id_remove[k-1]:
return id[:k-1] + (id[k-1] - 1,) + id... | 51f9a2254e1736a4e6014a8714789186ee4a3c63 | 54,561 |
from typing import Dict
def get_ctf_json(json: Dict) -> Dict:
"""
Get ctf in rawsec json.
Parameters
----------
json: Dict
rawsec json.
Returns
-------
Dict
ctf dict.
"""
return json["ctf_platforms"] if "ctf_platforms" in json else {} | 3ef14283c2468a41685c43051823807b7e23d561 | 54,562 |
from pesummary.core.plots.plot import _make_corner_plot
def _make_extrinsic_corner_plot(samples, latex_labels, **kwargs):
"""Generate the corner plots for a given approximant
Parameters
----------
opts: argparse
argument parser object to hold all information from the command line
samples:... | be3a9303a95f5eac4d693e70970d269ebf7663d1 | 54,563 |
import io
def GetOperationError(error):
"""Returns a ready-to-print string representation from the operation error.
Args:
error: operation error object
Returns:
A ready-to-print string representation of the error.
"""
error_message = io.StringIO()
resource_printer.Print(error, 'yaml', out=error_... | 65df8d8861212c381dc0e234e83250ec6f577bb5 | 54,564 |
import logging
def hogbom_clean(dirty, psf,
gamma=0.1,
threshold="default",
niter="default"):
"""
Performs Hogbom Clean on the ``dirty`` image given the ``psf``.
Parameters
----------
dirty : np.ndarray
float64 dirty image of shape (ny, ... | f5d920e12707ecdb197b442606401c1d90e8f887 | 54,565 |
def to_cartisian(r, theta):
"""
Take two numbers or np arrays and return cartisian representation
of the comblex number(s) r*exp(i*theta)
Return:
tuple (x, y)
"""
x = r*np.cos(theta)
y = r*np.sin(theta)
return (x, y) | de507866eb912f93a14639fc4157326b21a9196d | 54,567 |
def _get_team_(client, jwt, project_id):
"""Get team and return response."""
headers = ss_client_auth_header(jwt)
response = client.get(TEAM_API.replace(':project_id', project_id),
headers=headers, content_type='application/json')
return response | 67de2be6391a99209a08d92a6150ffd69a61847b | 54,568 |
def counted ( f ):
"""create 'counted' function to know number of function calls
Example
-------
>>> fun = ...
>>> func = counted ( fun ) ## use as function
>>> @counted
>>> def fun2 ( ... ) : return ...
"""
def wrapped ( *args, **kwargs ):
wrapped.calls += 1
... | 75f8e297910c049b551f38b440d99b21c6c74caf | 54,569 |
def get_latex_permutations(rows, cols, tarray, title):
"""
Creates a latex table as a string.
The string can be cut and paste into the dissertation.
:param rows: number of rows in the board.
:param cols: number of columns in the board.
:param tarray: 2D array of the table contents.
:para... | 261bb367a948731748441d10afd4dcee793624b5 | 54,570 |
import logging
def load(file, collapsed=True, index=None):
"""Loads Laue diffraction data."""
if file['stacked'] is True:
files = loadstack(file)
if file['ext'] == 'h5':
vals = loadh5files2(files, file['h5']['key'], file['frame'])
else:
if file['ext'] == 'h5':
... | be2820949555d79fc76e261c587ee229459b6901 | 54,571 |
def format_map_to_vector(feature_lists: list, start: int, end: int):
"""
Convert map into vector
:param feature_lists: list of features, whose elements are maps.
:param start: starting element within list
:param end: ending element within list
:return: vector (list) of selected features
"""
... | a593c3cf12d154e924955f3fcf20dc616c2771ac | 54,572 |
def tree_subtract_mean(oks: PyTree) -> PyTree:
"""
subtract the mean with MPI along axis 0 of every leaf
"""
return jax.tree_map(partial(subtract_mean, axis=0), oks) | 9eed40b488799a44583503118fd419bc530a3e90 | 54,573 |
def patch_expsets_otherprocessedfiles_for_queried_files(connection, **kwargs):
""" Update the Higlass Items from Experiment Set Other Processed Files (aka Supplementary Files).
Args:
connection: The connection to Fourfront.
**kwargs, which may include:
called_by(opti... | 86f113d7f7dd92f9fdfa356ccaca7aeebdc6dea9 | 54,574 |
def selector(possibilities, names):
""" Print a selector of all possibilities, and validate the choice against the "names" list """
# Print all possibilities
for i in range(len(possibilities)):
print(f'({i +1}) {possibilities[i]}')
names.append(str(i + 1))
skip_lines(1)
# Ask a user... | 6cec0f732d8161b46899db82a7171cc30be681fa | 54,576 |
def splinit(fun, data, i, s, smax, par, x0, n0, u, v, x, y, x1, x2,
L, l, xmin, fmi, ipar, level, ichild, f, xbest, fbest, stop):
"""
splits box # par at level s according to the initialization list
in the ith coordinate and inserts its children and their parameters
in the list
"""
n... | 962fd2168ed0c16667dab8fad031bbebf41fb7d3 | 54,577 |
def handle_effect_results(permutation_result):
"""Takes in output from multiprocess_permutation function and converts to
a better formatted dataframe.
Parameters
----------
permutation_result : list
output from multiprocess_permutation
Returns
-------
permutation_df : pd.DataFr... | 564362c5db1916ff2dbb33cd253da5270edb7201 | 54,578 |
def get_one_carrot_input():
"""
Obtains pre-defined testing base astar that is assured not to fail
"""
args = g08.get_args()
args.a_estrella = True
args.vision = 2
args.zanahorias = 2
args.tablero_inicial = "_generated_inputs_/4x4(1).txt"
result = g08.get_result(algorithm="AStar", ar... | 27ebd29c4d9ec6b01a1abb070b96d9e4c9413ee9 | 54,579 |
def canvas_pull ( canvas ,
ratio = 0.80 ,
left_margin = 0.14 ,
right_margin = 0.05 ,
bottom_margin = 0.14 ,
top_margin = 0.05 ,
hSpacing = 0.0 ,
vSpacing ... | 03b765901eb276ecdabf70a849ac9383882f1630 | 54,580 |
def soft_threshold(X, thresh):
"""Proximal mapping of l1-norm results in soft-thresholding. Therefore, it is required
for the optimisation of the GFGL or IFGL.
Parameters
----------
X : ndarray
input data of arbitrary shape
thresh : float
threshold value
Returns
-------... | acf2b4db26bf821a58b5a29ab31a907325068bb8 | 54,581 |
def _to_ffmpeg_time(n):
""" Format number of seconds to time expected by FFMPEG.
n: int
Time in seconds to format.
returns: Formatted time in FFMPEG format.
"""
m, s = divmod(n, 60)
h, m = divmod(m, 60)
return '%d:%02d:%09.6f' % (h, m, s) | 64808a801dd4008ef61df305efa936ee1e9f5c5b | 54,583 |
def compute_similarity(network, feature_matrix):
"""
Builds a weighted graph, where each edge (u, v, sim) is constructed by
computing the Jaccard similarity (sim) of the attributes of nodes u and v.
For the sake efficiency, a vectorized implementation is used
:param network: The network
:param f... | 324b417aa7c439050147931dacb21ec61b2243b1 | 54,584 |
def vxxxxx(p, vmass, nhel, nsv):
"""
Defines a vector wavefunction. nhel=4 is for checking BRST.
Input momenta have shape (num events, 4).
Parameters
----------
p: tf.Tensor, vector boson four-momenta of shape=(None,4)
vmass: tf.Tensor, boson mass of shape=()
nhel: tf.Tensor... | 795bf250ac512416fac79601ba8bc9be692eeb38 | 54,585 |
from typing import List
from typing import Dict
def find_properties_object(path: List[str], field: str, properties) -> Dict[str, Dict]:
"""
This function is trying to look for a nested "properties" node under the current JSON node to
identify all nested objects.
@param path JSON path traversed so far... | 748399f8b8fcb6d04535059557ce1f9c9a02cffa | 54,586 |
def get_nodes(lines):
"""
Return node register IDs provided lines from a trace file.
:param lines:
The lines from the trace file to be searched.
"""
nodes = []
for line in lines:
found = re_node_register.search(line)
if found:
node_id = found.group(2)
... | 9faf8b60d734d381e0664a76bca1765620b5c510 | 54,587 |
def are_infinity_coordinates(coordinates_value):
""" To check whether the coordinates are infinite.
Parameters
----------
coordinates_value: np.array, or list
x and y coordinates you want to check.
Returns
----------
bool
Are coordinates infi... | 5958790c666e550870c149019cc57480145ba6be | 54,589 |
import json
def read_cam_from_json(path):
"""generates a Camera object from a json file"""
with open(path) as f:
config = json.load(f)
intrinsic = config['intrinsic']
coefficients = [intrinsic['k1'], intrinsic['k2'], intrinsic['k3'], intrinsic['k4']]
cam = Camera(
rotation=SciRot... | eae61d7d4757cf3df602c7f5bb16a6d3488f6ba1 | 54,592 |
def get_angle_encoding_model(theta, neural_data, ang_bin_edges, speed=None, min_speed=None, max_speed=None,
data_type='spikes', n_xval=5):
"""
:param theta: array n_samps of angles in radians
:param neural_data: array n_units x n_samps of firing rates
:param ang_bin_edges: b... | bec04c6a42562bbaec5f25a541ebb60797e78221 | 54,593 |
import logging
import requests
def uninstall_callback():
"""Hipchat will hit this endpoint when the integration has been uninstalled by the end user."""
redirect_url = request.args.get('redirect_url')
installable_url = request.args.get('installable_url')
logging.info("Getting installable info from %s... | affed9a5e69b62502d7459924c820c227e34ec52 | 54,595 |
import pathlib
import re
def normalized_uri(root_dir):
""" Attempt to make an LSP rootUri from a ContentsManager root_dir
Special care must be taken around windows paths: the canonical form of
windows drives and UNC paths is lower case
"""
root_uri = pathlib.Path(root_dir).expanduser().re... | 230091cad5dedbe14c2e7b0f6e726e640fd63495 | 54,596 |
from typing import Dict
from typing import Any
import importlib
def _serialize(selector: str, class_name: str, values: Dict[str, Any]):
"""Serializes message using the selector and defined class name."""
package_name = _find_package_name(selector)
class_object = getattr(importlib.import_module(package_nam... | c31c62f6c5626f947ea4ddc75606102eb7fd8769 | 54,597 |
import json
def download_prs(source_url, source, credentials):
"""
INPUT:
source_url: the root url for the GitHub API
source: the team and repo '<team>/<repo>' to retrieve prs from
OUTPUT: retrieved prs sorted by their number if request was successful. False otherwise
"""
url = sou... | 4994e84f9cf429b3ac0297ef132663b2f4c3eebe | 54,598 |
def calc_q_max_FC(region, mode, A_HCZ, R_type):
"""ファンコンベクターの最大能力
Args:
region(int): 省エネルギー地域区分
mode(str): 運転モード 'い', 'ろ', 'は'
A_HCZ(float): 暖冷房区画の床面積
R_type(string): 居室の形式
Returns:
ndarray: ファンコンベクターの最大能力
"""
# 付録Mに定める放熱器の最大能力 q_max_rad に等しいものとする
return appendix... | fbf70067293eba693cfeff7e0ceeab15884bb360 | 54,600 |
def _pop_funclist(f):
"""_pop_funclist(f) -> list or None
Evaluates and returns a list constant defined at the beginning
of a function. If the function doesn't begin with a list,
or the list refers to parameters or other locals, a None is returned.
The returned list is removed from the function cod... | 8e5865215de527feef95820a5fa2b59c549bb9ac | 54,601 |
def levenshtein_message_distance(m1, m2):
""" Use python-levenshtein package to calculate edit distance """
return levenshtein.distance(m1,m2) | 0e0bf202b74c5004481c07bcf3f816b48114ac01 | 54,602 |
def gen_task1() -> np.ndarray:
"""Task 1: return constant symbol."""
seq = rand_syms()
return np.concatenate(([1], seq, [2])) | 7be0ba92565f6af30dede310130492c9fbbd9fa2 | 54,603 |
def read_pfam_output(pfam_out_file):
"""Read the output of PFAM scan."""
cols = ["seq_id", "alignment_start", "alignment_end", "envelope_start",
"envelope_end", "hmm_acc", "hmm_name", "type", "hmm_start",
"hmm_end", "hmm_length", "bit_score", "E-value", "significance",
"clan"... | 2568db3f47a11d7795ad1d990ae36aa9edc3441c | 54,604 |
def merge_consecutive_timestamps(timestamps):
"""
Merges consecutive timestamps in a list if they're less than 2 seconds apart
Example: [(0,5), (5,10), (20,30)] gets combined into [(0,10),[20,30]
"""
result = []
i = 0
while i < len(timestamps):
(start, end) = timestamps[i]
#... | 9ec3817dd62771d7269892ae590a160ea581fa53 | 54,605 |
import torch
def PadToCentered(tensor: torch.Tensor, length: int, dimension: int, fill=0.0)-> torch.Tensor:
"""
Pads a tensor along the indicated dimension to a particular length, embedding
the initial tensor in the center.
:param tensor: the tensor to pad
:param length: How long the tensor will... | 3cf22413fc9fc3106d746359ba565f07f494bf2c | 54,606 |
def _compute_cp(obs_result, obs_norm, infos, expert_plot=False):
"""Compute the closure phases array (across the cube) and averaged cp using
the normalized bispectrum (see _normalize_all_obs()). Note that for the CP, the
extracted quantities are computed after the normalisation."""
bs = obs_norm["bs"]
... | f03cabef21dd60000d54aeaf90207731416108cb | 54,607 |
def add_sampledata_times(samples, sites_time):
"""
Return a tsinfer.SampleData file with estimated times associated with sites.
Ensures that each site's time is at least as old as the oldest historic sample
carrying a derived allele at that site.
:param tsinfer.formats.SampleData samples: A tsinfer... | 6eb5ae3f2ecb4f3d9c6d2cfc666f73ea287ad4c5 | 54,608 |
def convert_uint16_to_array(value):
""" Convert a number into an array of 2 bytes (LSB). """
return [
(value >> 0 & 0xFF),
(value >> 8 & 0xFF)
] | ac851a650be9ac37a96e26ffcf8c00483a580be0 | 54,609 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.