content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def annotate_heatmap(im, data=None, valfmt="{x:.2f}",
textcolors=["white", "white"],
threshold=None, **textkw):
"""
A function to annotate a heatmap.
Arguments:
im : The AxesImage to be labeled.
Optional arguments:
data : Data used... | 36febdab90f9a243bab02739ad2ad62cee3d1d21 | 54,400 |
def build_attention_mask_3d_causal(source_mask, target_mask):
"""
Returns a 3D joint attention mask for Megatron given two 2D masks
:param source_mask - True for non-masked, else masked [batch, src length]
:param target_mask - True for non-masked, else masked [batch, tgt length]
"""
causal_mask ... | 145014389519267eac49f287c260cac5c920d3c7 | 54,401 |
def get_run_list(filter_=None, page=1, page_size=25):
"""Get a list of runs
The `filter` parameter takes a list of filters to apply in the form of:
{name}{operator}{value}
where:
- `name` is any valid column in the database
- `operator` is one of `=`, `!`, `>`, `<`, `)`, `(`, `~`, `*... | 2178112de82e527d77ab31c6965b95cdcec68ef5 | 54,402 |
def split_timesteps(inputs):
"""Split the input matrix from (batch, timesteps, input_dim) to a step list ([[batch, input_dim], ..., ])."""
timesteps = inputs.get_shape()[1].value
feature_dims = inputs.get_shape()[2].value
inputs = tf.transpose(inputs, [1, 0, 2])
inputs = tf.reshape(inputs, [-1, feat... | bfe26243aa1b9443e39c6e377cb5dec2cdf17560 | 54,403 |
import torch
def get_all_dists(x, y):
"""Get L2 distance of x from each item in y."""
return torch.sqrt(torch.sum(torch.pow(x - y, 2), 1)) | 9c54cdd1887b71e872b240e87cf12cc5df9abb1e | 54,404 |
def get_xml_tail(full_xml_ordered_dict):
"""Get xml tail"""
xml_tail = get_rpc_tail(full_xml_ordered_dict)
return xml_tail | 6edc992eac813117275d223385f777b80016c3d1 | 54,405 |
def IPRange(Range, range_temp, language):
"""
IP range string to IPNetwork type
Args:
Range: IP range string
range_temp: range_temp filename
language: language
Returns:
an array of IP range in IPNetwork type
"""
myranges_now = open(range_temp).read().rsplit()
... | e01ecbdb3a8701d8fd70d3e5a37dafd45fcfd5dd | 54,406 |
def api_get_user_modelling_units_results(userModellingUnitId, period, divider):
"""
{
"doc": {
"title": "user modelling units results help",
"body": "<p> Obtain the user modelling units results </p>"
},
"GET": {
"label": "Obtain the user modelling unit... | 04e7e57b3946a0e7a420fef9b23a4878b1f378ff | 54,407 |
def test_writer_precision_nano_fail():
"""if writer is not set to nano, supplying this timestamp should be truncated"""
ts, pkt = (Decimal('1454725786.010203045'), b'foo')
writer.writepkt(pkt, ts=ts) # noqa
return [(1454725786.010203, pkt)] | 3b170e10b1b49f9c56a4ce7f4716777aafd32dc0 | 54,408 |
def _get_suggestions_index(name):
"""Returns suggestions index name for a regular index name."""
return f'df_suggestions_{name}' | 4cd2294e89f05dfbefe65ff4604c43818880d6c9 | 54,409 |
import imp
import os
def get_controllers(controller_path=CONTROLLERS_PATH, nested=None):
"""
Return a list of controllers
"""
controllers = {}
parent_mod = 'fts3rest.controllers'
if nested:
parent_mod += '.' + nested
imp.load_source(parent_mod, os.path.join(controller_path, '__init... | 63ba76b62b36e6d7c4eb346c7974e4e793c248c6 | 54,410 |
def draw_rois(
im,
notebook_url="localhost:8888",
table_height=100,
crosshair_tool_alpha=0.5,
color="white",
fill_alpha=0.1,
vertex_color="red",
vertex_size=10,
cmap=None,
frame_height=400,
frame_width=None,
length_units="pixels",
interpixel_distance=1.0,
x_range=... | 3b054e5b0e6fc4449029d8cb7fe56dd823301c57 | 54,411 |
def boxplot(data1, data2=None, width=0.75, whiskers=1.5, axesAdjust=True, axes=None):
""" boxplot(*args, width=0.75, whiskers=1.5, axesAdjust=True, axes=None)
Create a box and whisker plot and returns a BoxPlot wobject that can
be used to change the appearance of the boxes (such as color).
If ... | 9e5b3ef14fcf78ec6e8ef1001b9f5b29e9c8586c | 54,412 |
from pathlib import Path
import os
def get_contacts_df(config: GetContactsConfig, pdb_name: str) -> pd.DataFrame:
"""
Reads GetContact File and returns it as a pd.DataFrame
:param config: GetContactsConfig object
:type config: GetContactsConfig
:param pdb_name: Name of PDB file. Contacts files ar... | dcea1ed899066604f7b2054b1389b9bad6739141 | 54,413 |
import json
def add_config(request):
"""
新增配置
:param request:
:return:
"""
account = request.session["now_account"]
if request.is_ajax():
testconfig_info = json.loads(request.body.decode('utf-8'))
msg = config_info_logic(**testconfig_info)
return HttpResponse(get_aj... | 719318e36a9b3f398470dae39b9127fcd88b20c4 | 54,414 |
def get_scene_index(glTF, name):
"""
Return the scene index in the glTF array.
"""
if glTF.get('scenes') is None:
return -1
index = 0
for scene in glTF['scenes']:
if scene['name'] == name:
return index
index += 1
return -1 | 357365ea60ea89630d942b13d0c3a26b49889488 | 54,415 |
def wifi_toggle_state(ad, new_state=None):
"""Toggles the state of wifi.
Args:
ad: An AndroidDevice object.
new_state: Wifi state to set to. If None, opposite of the current state.
Returns:
True if the toggle was successful, False otherwise.
"""
# Check if the new_state is ... | 0aa2ce4a02be1ad78707dd165d8bfa5652063eb7 | 54,416 |
def _preprocess_include(include):
"""
A utility function for processing the `include` input
Parameters
----------
include : numpy.ndarray
A list of (zero-based) indices corresponding to the dimensions in `T` that
must be included in the constrained multidimensional motif search.
... | 81498282d06e156569559705ca54131a2ce22f78 | 54,417 |
def get_storage(path=None, options=None):
"""
Get the specified storage configured with options.
:param path: Path in Python dot style to module containing the storage
class. If empty settings.DBBACKUP_STORAGE will be used.
:type path: ``str``
:param options: Parameters for config... | 4f91d193c53aaff49d95e5ae2fd2c1cb386bda60 | 54,418 |
def _find_channels(action, bone, channel_type):
"""
:param action:
:param bone:
:param channel_type:
"""
result = []
if len(action.groups):
group_index = -1
for index, group in enumerate(action.groups):
if group.name == bone.name:
group_index =... | a74f8a87664a1cca681abe94d34e6fe7f046dc25 | 54,419 |
import argparse
def parse_waveglow_args(parent, add_help=False):
"""
Parse commandline arguments.
"""
parser = argparse.ArgumentParser(parents=[parent], add_help=add_help)
# misc parameters
parser.add_argument('--n-mel-channels', default=80, type=int,
help='Number ... | e532021eb2c7225e87765cbbc60b862b03def6e6 | 54,420 |
def _ord_to_str(ordinal, weights):
"""Reverse function of _str_to_ord."""
chars = []
for weight in weights:
if ordinal == 0:
return "".join(chars)
ordinal -= 1
index, ordinal = divmod(ordinal, weight)
chars.append(_ALPHABET[index])
return "".join(chars) | 33283d4e09ddaccbf1bff3f92904313d6c18de6c | 54,421 |
def aws(flox: Flox, args, **kwargs):
"""awscli command wrapper with session credentials provider"""
command_name = next(iter(args), None)
if command_name == "console":
args = list(args)
with EmptyContext(flox, console, args[1:], allow_interspersed_args=True, ignore_unknown_options=True) as ... | eba7e1151c69be603d56930b35b392f1205f9864 | 54,422 |
def is_inactive_link(node_status_at_link):
"""Find links that are inactive.
A link is inactive if it connects two boundary nodes or one of
its nodes is closed.
Parameters
----------
node_status_at_link : ndarray of int, shape `(n_links, 2)`
Node status a link tail and head.
Return... | fcf9a318029968da714c76adc6f1a981b99479dc | 54,423 |
import subprocess
def run_cmd(cmdlist):
""" reusable function for running shell commands"""
try:
stdout = subprocess.check_output(cmdlist)
except subprocess.CalledProcessError:
pass
else:
if stdout:
return stdout | 42aa13afe224b017ec54264a5cab0a4beaa1dff0 | 54,424 |
def found_value(gpio_value):
"""checks if the gpio value entered in command line is supported and return the corresponding value"""
if gpio_value in common.gpio_supported_values:
if common.gpio_supported_values[gpio_value] == 0 or common.gpio_supported_values[gpio_value] == 1:
return common.... | 533f25138a724bc7ab355f30d365524b5f4db4e2 | 54,425 |
def scrape_html_table(bs_table, f = lambda tags_list, index : list( map(lambda tag: tag.string, tags_list) )):
"""
Returns a nested list based on the contents of the table
html = \"\"\"<table class="formulario">
<tr>
<td class="very important stuff">Hotel</td>
<td>Trivago</t... | 3639a9691f25333c59ec2a4613123ad3b568d7bd | 54,426 |
def calculate_immediate_post_dominators(nodes, _pdom, _spdom):
""" Calculate immediate post dominators for all nodes.
Do this by choosing n from spdom(x) such that pdom(n) == spdom(x).
"""
_ipdom = {}
for node in nodes:
if _spdom[node]:
for x in _spdom[node]:
i... | 17fb44a47a440c8c93f58262132ab0f65a9566a5 | 54,427 |
import stat
import glob
import os
def valid_dotfile_permissions():
"""Return a dictionary of all valid dotfiles, mapped to """
"""their octal permissions."""
permissions = dict()
ST_MODE = stat.ST_MODE
for elem in recurse_valid_dotfiles(this_directory()):
for file in glob(elem+'*'):
... | 4638fe7dda66fb3c65ea776e0bbd32b77c183a9c | 54,428 |
from typing import Dict
def validate_runner_claims(claims: Dict):
""" Validate claims required for runner to function"""
runner_metadata_schema = RunnerMetadataSchema(unknown=EXCLUDE)
return runner_metadata_schema.load(claims) | e02a3101cc03a0858716dff71a87d21c416d918b | 54,429 |
def repay_margin(order_id, amount):
"""
:param order_id:
:param amount:
:return:
"""
params = {"order-id": order_id,
"amount": amount}
url = "/v1/margin/orders/{0}/repay".format(order_id)
return api_key_post(params, url) | da47b9d24d5ea8d713afa8149c05fa500b655067 | 54,430 |
def clinvar_track(build, chrom):
"""Return a dictionary consisting in the clinVar snvs track
Accepts:
build(str): "37" or "38"
chrom(str)
Returns:
clinvar_track(dict)
"""
clinvar_track = {
"name": "ClinVar",
"type": "annotation",
"sourceType": "file... | fb7d090fce2a4c9f23f0347ddb59d613e9c41876 | 54,431 |
import random
def calc_batch_loss(batch, teacher_forcing=1):
"""
Calculate the loss for given batch of data
:param batch: batch of data.
:param teacher_forcing: (float, default=1) rate of teacher forcing
:return: loss tensor
"""
x, x_len = batch.text
data = x[:-1].clone()
target = ... | 2d3d7d4b946c59bef9720e814a827db65836234d | 54,432 |
import click
def attach(config, model):
"""
Attach to model and show creation logs.
MODEL may be specified by name or ID, but ID is preferred.
"""
models = config.trainml.run(config.trainml.client.models.list())
found = search_by_id_name(model, models)
if None is found:
raise cli... | 075f76a5bdbfd102f7d83d80837d72c8ca78202f | 54,433 |
import torch
def cg_solve(f_Ax, b, cg_iters=10, callback=None, verbose=False, residual_tol=1e-10, x_init=None):
"""
Goal: Solve Ax=b equivalent to minimizing f(x) = 1/2 x^T A x - x^T b
Assumption: A is PSD, no damping term is used here (must be damped externally in f_Ax)
Algorithm template from wikipe... | 89cbff54d1107abb02ddfb5c095d12af7744f2bb | 54,434 |
def parang (hourangle, declination, latitude):
"""Calculate the parallactic angle of a sky position.
This computes the parallactic angle of a sky position expressed in terms
of an hour angle and declination. Arguments:
hourangle
The hour angle of the location on the sky.
declination
Th... | 09c4df4119e1b91dfa25372d9746e5fc0b7561fa | 54,435 |
def dataset(params):
"""
The input batch generator.
"""
with tf.name_scope("dataset"):
def sample():
input_mean = tf.constant(params.input_mean, dtype=tf.float32)
input_stddev = tf.constant(params.input_stddev, dtype=tf.float32)
count = len(params.input_mean)
... | c2a9c20261fd82bc5498bddb7b843394428eeddf | 54,436 |
def frac_diff_ffd(data: pd.Series, d: float, threshold=1e-5, parallel=False):
"""
Fractionally Differentiated Features Fixed Window
:param data: data
:param d: difference coefficient
:param threshold: threshold
:param parallel: run in parallel
"""
if isinstance(data.index, pd.MultiIndex)... | 31f0f796547a1447d1545255ffe32202ca25927a | 54,437 |
import argparse
import os
def _get_args():
"""Parse command-line arguments."""
parser = argparse.ArgumentParser(prog="nix-server")
parser.add_argument("--version", action="version", version=__version__)
parser.add_argument("--port", type=int,
default=int(os.getenv("PORT", 5000)... | 9547303770b92df65ec8428334f0bc4d5f8b3f5c | 54,438 |
def SetIamPolicy(taxonomy_id, policy):
"""Sets IAM policy, for a given taxonomy.
Args:
taxonomy_id: Id of the taxonomy.
policy: An IamPolicy message.
Returns:
An IamPolicy message.
"""
messages = utils.GetMessagesModule()
return _GetService().SetIamPolicy(
messages.DatapolTaxonomyStoresD... | 6f4e82d009700c008a71e4c2fc40dd3524e41743 | 54,439 |
def format_committer(input_row: dict) -> tuple:
"""Format a committer row form commit input_row."""
return format_contributor(input_row, CONTRIBUTOR_TYPE_COMMITTER) | a091492fab2a0305972eb9d19e69b7ad46be601d | 54,440 |
async def about(request):
"""Renders the About page."""
return templates.TemplateResponse("about.html", {"request": request}) | af066e26770c1b08f63254ba9122e1fa633d84e5 | 54,441 |
def investigateTreesAndAlignments(d, srcSIndex, tgtSIndex):
"""
Return the parse trees and word alignments for this
pair of source sentence and target sentence indices
"""
src = d.sentence(srcSIndex)
tgt = d.highlight(tgtSIndex)
# get matchList, and trim so it is only leaf nodes
ma... | f70b935ee5c97259f7e62a9196df829871e8219a | 54,442 |
def build_faces(structure, template, vertex_list, target, fill_uncompleted='border'):
"""
Creates the faces
:param structure: row[]: column[]; cell[]: vertex: int - inner mesh structure
:param template: RFTemplate - template
:param vertex_list: VertexData[] - created vertex
:param target: RFTarg... | 484bcb29c94213b00716be7e93e519d13952441b | 54,443 |
import struct
def read(filename, include_fourcc=False):
"""Reads a LAB container and returns all stored files.
:param filename: Path to the LAB to read
:return: List of LAB entry tuples [(str, bytes), ..., ] where the tuple represents (name, data) of the entry
"""
# Utility function for reading n... | 316b115a47e6acbf39a8d21edac3320e27f5b12c | 54,444 |
def gf_sub_const(f, a, p):
"""Returns f - a where f in GF(p)[x] and a in GF(p). """
if not f:
a = -a % p
else:
a = (f[-1] - a) % p
if len(f) > 1:
return f[:-1] + [a]
if not a:
return []
else:
return [a] | 93d4c8611aac77d1cf1da891ca8e72db5612b28a | 54,445 |
def replace_jax_res_net_block_vars_to_tf(
jax_initial_vars: NestedMap) -> NestedMap:
"""Replaces the JAX ResNetBlock vars to TF compatible vars.
Args:
jax_initial_vars: JAX ResNetBlock vars.
Returns:
tf_initial_vars which is TF compatible with ResNetBlock.
"""
tf_initial_vars = jax_initial_vars.... | 20c8cfec6cad1aa3639902af5cee43f6453f4e34 | 54,446 |
import re
def install_transproteomic_pipeline(env):
"""
"""
## version should be of form X.X.X-codename
default_version = "4.6.1-occupy"
version = env.get("tool_version", default_version)
version_parts = re.match("(\d\.\d)\.(\d)-(.*)", version)
major_version = version_parts.group(1)
re... | 27146ce5105ef9da4d95c6f63112fcdfff813c6d | 54,447 |
import os
def run(xconfig):
"""
Implements --ssonly mode
"""
global monjer, config
config = xconfig
# Check input filename
if not config.run['infile']:
failwith(ER.OPT_MISSING, "option infile required (-i/--infile)")
else:
if not os.path.exists(config.run['infile']):
... | 4047c87d35567bb4185273b776330eef3c75dd55 | 54,448 |
def assemble_SHCNN_blocks(inputs, config, dropout_prob, hw, mw, lw, hw2, mw2, lw2, h2m, m2l):
"""
Definition of all the layers according to config
:param inputs: dictionary of inputs with keys [points, neighbors, pools, upsamples, features, batches, labels]
:param config:
:param dropout_prob:
:r... | 9cc79ee44e4f3adc4bd0bbff2a4066531fc7f789 | 54,449 |
import torch
def sample_with_temperature(logits, sampling_temp, keep_topk, keep_topp):
"""Select next tokens randomly from the top k possible next tokens.
Samples from a categorical distribution over the ``keep_topk`` words using
the category probabilities ``logits / sampling_temp``.
Args:
l... | aa2dcf6e6584923a7e1ac8c091d5c832c6bf7b5e | 54,450 |
import torch
def get_mask_from_lengths(lengths):
"""Constructs binary mask from a 1D torch tensor of input lengths
Args:
lengths (torch.tensor): 1D tensor
Returns:
mask (torch.tensor): num_sequences x max_length x 1 binary tensor
"""
max_len = torch.max(lengths).item()
ids = t... | 508f7425b03fc3a0b52be45bcb5632150b809bfb | 54,451 |
import random
import requests
import sys
def get_resp(url):
"""Get webpage response as an lxml.html.HtmlElement object."""
try:
headers = {'User-Agent': random.choice(USER_AGENTS)}
try:
request = requests.get(url, headers=headers, proxies=get_proxies())
except MissingSchema... | 096283a08f9cd48d61b3f6c89ea1251b111ac609 | 54,452 |
def fixed_ro_bci_edge_small_angle(ascentlat, lat_fixed_ro_ann=None,
burg_num=None, ross_num=None, delta_v=None,
height=HEIGHT_TROPO, grav=GRAV_EARTH,
rot_rate=ROT_RATE_EARTH, radius=RAD_EARTH):
"""Small-angle solut... | 6873656f5f88a51ac0ba6108aa0ffe3c429a0cf3 | 54,453 |
def veclength(vec):
"""Returns the length of the given vector(s).
Multiple vectors may be passed in, with a shape of ``(n, 3)``.
"""
vec = np.array(vec, copy=False).reshape(-1, 3)
return np.sqrt(np.einsum('ij,ij->i', vec, vec)) | cfad654c1364217a5620ae360817cd97d697f6d0 | 54,454 |
from typing import List
def get_guardian(day: date, holiday_list: List[List[date]]) -> str:
"""Get the guardian for a day, according to the holidays."""
if is_father_day(day):
return "B"
if is_mother_day(day):
return "L"
if day_is_holiday(day, holiday_list):
return get_guardian... | d99debe9dbfad6ed3e3a6036c7885e0f00684a16 | 54,455 |
def add_two_polynomials(polynomial_1: list, polynomial_2: list) -> list:
"""
This function expects two `polynomials` and returns a `polynomial` that contains
their `sum`.
:param polynomial_1: First polynomial
:param polynomial_2: Second polynomial
:return: A polynomial representing the sum of t... | e2fed8be5f35f1c306b78b69c608f90668aeb2f1 | 54,456 |
import torch
def mediane(x, y=None):
"""
Computes the median
"""
if (isinstance(x, np.ndarray)):
x = torch.from_numpy(x)
if (isinstance(y, np.ndarray)):
y = torch.from_numpy(y)
dxx = distances(x)
if y == None:
return dxx.median()
dyy = distances(y)
dxy... | d622d9fd54e26abb124b3f675e510f779c5b6ea0 | 54,457 |
import torch
def train_loop(model, epochs, loss_fn, train_dl, valid_dl, use_gpu=False, lr=0.01):
"""
Loop between training and validation cycles through n epochs
:param model: pytorch model
:param epochs: number of epochs
:param loss_fn: loss function
:param train_dl: pytorch dataloder on top ... | fafaa8ee5cccffe07b237bcc64efc1b5ac29d7af | 54,458 |
import functools
def ajax_required(fn):
"""
Placed on a view, this decorator will raise
:class:`django.http.Http404` if the incoming request is not an HTTP
POST or if the header `HTTP_X_REQUESTED_WITH` is not set.
"""
@functools.wraps(fn)
def wrapper(request, *args, **kwargs):
if ... | 9171a146fa499414ca3fceed2e3ee3c022aaae3a | 54,459 |
from typing import List
from typing import Tuple
import torch
from typing import Dict
import time
import itertools
import tqdm
def read_images(data_packs: List[matchzoo.DataPack],
fat_pth_file: str, max_len_images: int, side, image_dim: int = 2048) -> Tuple[torch.Tensor, Dict, Dict]:
"""
- Pru... | a91048ad9f81d3e645d8b220148f42cd4496e391 | 54,460 |
from pathlib import Path
import os
def find_song(json_data, filename, source, lyrics, rename, info, link, art, artist_art, preview):
"""Actually do things with the data found."""
# How many errors
errors = 0
# Fill song data
song_data = SongData()
# Get stuff from the rest of the sources, fir... | d629fdd75aebd53381dc1a151c86993eb7fdff2d | 54,461 |
import torch
def mmd_gaussian(samples1, samples2, sigma=10.0):
"""
MMD constraint with Gaussian Kernel support matching in BEAR
This code was stolen from: https://github.com/aviralkumar2907/BEAR/blob/master/algos.py
sigma is set to 10.0 for hopper, cheetah and 20 for walker/ant
"""
# Batch x ... | 9b81c1e4d2999e89521d935d5950121bb2d4608f | 54,462 |
def DefaultKeyWriter(key_name):
"""This key writer rewrites keys as lower camel case.
Expects that the input is formed by '_' delimited words.
Args:
key_name: Name of the key to serialize.
Returns:
Key name in lower camel-cased form.
"""
return ToLowerCamelCase(key_name) | c7ed1bda0ce5ccc1e061ce4b1e39fe06c59ed53f | 54,463 |
from typing import List
from typing import Dict
from typing import Any
from typing import Optional
import os
def get_server_info(
chains: List[Chain], chain_names: List[str]
) -> List[Dict[str, Any]]:
"""
Get the server info for a set of chains.
Args:
chains: A list of the chains to search.
... | 754d280ead79c8a132e683b01daedcc850834c11 | 54,464 |
def get_random_orthonormal_vector(base_vector: ParameterVector) -> ParameterVector:
"""Helper function to generate a random orthogonal vector with respect to
a provided base vector."""
random_vector = np.random.normal(size=base_vector.shape)
new_vector = (
random_vector
- np.dot(random_v... | cf111f088d13a14f4cabc9eeb0e16a62bdc26aaf | 54,465 |
def PUtilVisCompare (in1UV, in2UV, err):
"""
Compares the visibilites in *in1UV* with those in *in2UV*.
* return: RMS ( real, imaginary differences / amplitude of *inUV2* )
* in1UV = Numerator Python UV object. Possible infoList parameter printRat
scalar float if given and >0.0 then tell a... | de362477189c9760185972e693199bf9684febac | 54,466 |
def normalize(vec: DSList):
"""
Normalize the input vector.
:param vec: DSList
:return: DSList
"""
norm_ = norm(vec)
return smul(1/norm_, vec) | 1011bd68f91d780ecd984e7bfd6ba0e9c786415a | 54,467 |
import os
from typing import Callable
import functools
def name_asm_file(module_path):
"""
A decorator to put on top of tests which create asm, obj, and exe files.
Usually, you should pass `__file__` in as the module path.
EX:
@name_asm_file(__file__)
def test_my_feature():
... | 4669e130162c880a6686dae4ea7fb607af34be4e | 54,468 |
def distro_name_errors(distro_name):
"""Returns a list of errors in the distro name. Empty list means distro name
is valid."""
errors = []
if len(distro_name) == 0:
errors.append(
"distro name cannot be zero length")
if distro_name.startswith(defaults['catalog_prev_distro_pref... | 905da831ac82605295db81f3a54e41d2a76800a7 | 54,469 |
from math import sqrt
def prime_def(num):
"""
Поиск максимального простого делителея числа
:param num:
:return:
"""
prime_set = set(range(1, num + 1))
#print(prime_set)
for i in range (2, int(sqrt(num))):
if i in prime_set:
prime_set -= set(range(2*i, num + 1, i))
... | 619a4310dd9540e8354143fa2871ceddb78b4237 | 54,470 |
def dict_from_two_lists(keys: list, values: list):
"""Creates a dictionary from a list of keys and a list of values.
Examples:
>>> keys = ('bztar', 'gztar', 'tar', 'xztar', 'zip')\n
>>> values = ('.tbz2', '.tgz', '.tar', '.txz', '.zip')\n
>>> newdict = dict_from_two_lists(keys, values)\... | 3865a8e5a890dc00e69ea3feafc161f8617697ff | 54,471 |
def hashable_index(tuple_idx):
"""Return an hashable representation of a tuple of slice object
We add this because the slice object in python is not hashable.
Parameters
----------
tuple_idx : tuple
A tuple of slice/int objects
Returns
-------
ret : tuple
A hashable re... | e83d4db426053cc64f9ffda3b938bb85395e4741 | 54,472 |
def add_new_entry():
"""
Add IP details for the current user in Airtable
:return: True
"""
table.create(build_data_new())
return True | 54ab17dfaeaf8c1dc46885341d1db67e8c2981a3 | 54,473 |
def open_clean_bands(band_path,
crop_extent,
valid_range=None):
"""Open and mask a single landsat band using a pixel_qa layer.
Parameters
-----------
band_path : string
A path to the array to be opened
crop_extent : GeoDataFrame
A shapefile ... | 5d90c5018de05889914c54278defdfae35657d4c | 54,474 |
def encode_single_dataframe(dataframe: pd.DataFrame, f, types: dict=None, column_order: list=None,
bigendian: bool=False, properties: dict=None):
"""
:param dataframe: A pandas dataframe to encode
:param f: A file-like object to write the encoded data to
:param columns: A dic... | 23e96b89b67f4cbad9e2e1eb6a55c32eb9f46d3f | 54,475 |
from typing import Dict
def rms_combine(signals, weights = None, days = 1024, max_leverage = 5, join = 'outer', method = 'ffill'):
"""
>>> dt1 = drange(2000,2020, '1b')
>>> sig1 = pd.DataFrame(ewmxo(np.random.normal(0,1,(len(dt1),10)), 18, 54, vol = 30) , dt1)
>>> sig2 = pd.DataFrame(ewmxo(np.random.n... | 34b2dd5819dcd28c99cb4b5716b3a455747e8014 | 54,476 |
def get_output_type(name: str) -> OutputType:
"""Fetches a previously registered OutputType by name"""
if name in OUTPUT_TYPES:
return OUTPUT_TYPES[name]
else:
raise ValueError('The output type %s is unknown' % name) | 65f4f91fb28c39576241f72bb385442301a89407 | 54,477 |
def prepare_for_parsing(multinet):
"""
Compute layout for a hairball visualization
Args:
param1 (obj): multilayer object
Returns:
tuple: (names, prepared network)
"""
layers = defaultdict(list)
for node in multinet.nodes(data=True):
try:
layers[node[0... | b0e97223bcd832c69d1e76ee722e934a8d27f852 | 54,478 |
import typing
def peek(nbytes=0) -> typing.Generator[_Action, Buffer, bytes]:
"""Read output without consuming it.
Read but **does not** consume data from the protocol input.
This is a *non-blocking* primitive, if less data than requested is available,
less data is returned. It is meant to be used i... | c3112858d8f37122d2c81f5f3c2cbafb853056a7 | 54,479 |
import os
import json
import math
def load_dataset(dataset='single_person'):
"""
Load train- and testset from subfolder 'dataset'.
Download dataset: https://www.kaggle.com/ahmetfurkandemr/mask-datasets-v1/data
and: https://www.kaggle.com/shreyashwaghe/medical-mask-dataset
Run png_to_hdf5.py
:p... | dd39ff3ab2a148c5539828f866739abcdb575e21 | 54,480 |
def get_func_prototype_from_man(func):
"""
Parse "man func" output and return the function prototype.
:param func: function name
:returns the function prototype as a string. If not found, returns empty string.
"""
if func in g_prototype_db:
return g_prototype_db[func]
man_output = ge... | f79888d6d79332b536007ab1c9c9a6939819fe7b | 54,481 |
from typing import Tuple
from typing import List
from typing import Dict
from typing import Any
import torch
def train_gcn(
dgl_tuple: Tuple[List[DGLHeteroGraph], dict], params: Dict[str, Any]
) -> Model:
"""
Trains a GCN model
"""
epochs: int = params["epochs"]
hidden_features: int = params["... | 4b52af7666f2fffd73e4c495002bea5183027b6d | 54,482 |
from typing import List
from typing import Union
from typing import Any
from typing import Type
def check_tied_units(
all_t2_units: List[T2Compute],
first_pass_config: Union[FirstPassConfig, dict[str,Any]]
) -> None:
"""
:raises: ValueError if tied t2 units are present in t2_units but the requred t2 units ar... | 4b10b864e120a4f91e4c43b486a1a37f40f16b91 | 54,483 |
import os
def get_sas_generator_host() -> str:
"""
Gets env variable for SAS generator url
:retrurn sas url
"""
# TODO handle KeyError
return os.environ['SAS_GENERATOR_HOST'] | 12ba994339fad67d15d71f6f309c750aea03c268 | 54,484 |
def create_procgen_env(config, instance_seed, instance):
""" Creates a procgen environment and applies recommended wrappers. """
procgen_args = {k[8:]: v for k, v in vars(config).items() if k.startswith('procgen_')}
procgen_args['start_level'] += 300_000*instance
env = gym.make(f'procgen:procgen-{config... | d1bef874fe6b39ef4ae1495594329d6dbdab1705 | 54,485 |
def dedupe(items: list, only_neighbors: bool = False) -> list:
"""
Deduplicate a list while keeping order
If only_neighbors is True, dedupe will only check neighboring values
"""
ret = []
for item in items:
if (only_neighbors and ret and ret[-1] != item) or item not in ret:
... | 2313667f10f1480cb82e63dcfd33f986ccabfd75 | 54,486 |
import os
import json
def process_night_lights(country):
"""
Clip the nightlights layer to the chosen country boundary and place in
desired country folder.
Parameters
----------
country : string
Three digit ISO country code.
"""
iso3 = country['iso3']
folder = os.path.jo... | ec8f4fd625b079a32bc66b5d1267ab508ec177b8 | 54,487 |
from typing import Union
from typing import Tuple
from typing import Optional
def major7(
base: Union[int, str, Tone, Note],
duration: Union[Tuple[int, int], Signature, None] = None,
velocity: Optional[float] = None
) -> Tuple[Note, Note, Note, Note]:
"""
Generates Major Seventh chord.... | 73c98ee43960e9815eee25f20c0e98c662a940f6 | 54,488 |
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 |
import argparse
def parse_args():
"""
Obtain the simulation options from the input arguments
Return a tuple with the following elements:
* config_file: Relative location of the simulation configuration file
* show_plot: If true, plots shall be generated after the simulation
* from_file: If tr... | 1efa48f0917145efb0428e86002a19e83d83755a | 54,499 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.