content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def compute_length(of_this):
"""
Of_this is a dict of listlikes. This function computes the length of that object, which is the length of all of the listlikes, which
are assumed to be equal. This also implicitly checks for the lengths to be equal, which is necessary for Message/TensorMessage.
"""
le... | 4f8e2b3b17ba6bed29e5636de504d05a028304d8 | 75,403 |
import socket
def client(
host: str,
port: str,
use_sctp: bool = False,
ipv6: bool = False,
buffer_size: int = 4096,
timeout: float = 5.0
) -> int:
"""Main program to run client for remote shell execution
:param host: Server name or ip address
:type host: str
:param port: Port on which server listens, c... | 196de595f6d6573c6bc1a2b2209688060b246cdc | 75,404 |
def count_within(values, intervals):
"""Count number of values within each interval
Args:
values (n-list of nb)
intervals (m-list of 2-nb-tuple)
Return:
(m-np.ndarray) count for each interval
"""
rvals = np.reshape(values, [-1, 1])
intervals_m = np.array(intervals)
... | 7a673cab7249a74a72bbf3033d6eb5867872fb7d | 75,406 |
def gamma_approx(mean, variance):
"""
Returns alpha and beta of a gamma distribution for a given mean and variance
"""
return (mean ** 2) / variance, mean / variance | 8103a69d807c39c95c1604d48f16ec74761234c4 | 75,407 |
def get_blog_post_from_model(blog_post_model):
"""Returns a blog post domain object given a blog post model loaded
from the datastore.
Args:
blog_post_model: BlogPostModel. The blog post model loaded from the
datastore.
Returns:
BlogPost. A blog post domain object correspon... | d4737128615a8228d4a19097d2d22cc4cea5859f | 75,408 |
def update_performance_log() -> Table:
""" Returns a table with Deephaven update performance data.
Returns
a Table
Raises:
DHError
"""
try:
return Table(j_table=_JTableLoggers.updatePerformanceLog())
except Exception as e:
raise DHError(e, "failed to obtain the ... | 70ad2be3c459b765f6bf6042c58b4770d0a03a5d | 75,409 |
from typing import Set
def _count_empty(addresses: Set[str], wallet_index: WalletIndex) -> int:
""" Count how many of the addresses given are empty (have no outputs)."""
return sum(1 for addr in addresses if wallet_index.is_address_empty(addr)) | 0966816d35931895c609ce7eb6dfe39051280eb9 | 75,410 |
from typing import Dict
def get_infd_kwargs(scores: pd.DataFrame, sample_kwargs: Dict) -> Dict:
"""Get a dictionary of keyword arguments to arviz.from_cmdstanpy.
:param scores: pandas dataframe whose rows represent
measurements. Must be the same as was used for `get_stan_input`.
:param x_cols: list ... | 462af295a0e4a1d1220c6c8a006eb8c753dca3f3 | 75,411 |
def cropRect(rect, cropTop, cropBottom, cropLeft, cropRight):
"""
Crops a rectangle by the specified number of pixels on each side.
The input rectangle and return value are both a tuple of (x,y,w,h).
"""
# Unpack the rectangle
x, y, w, h = rect
# Crop by the specified value
x += cropLeft
... | f226d25b146b894455bdbc80acc011a94ab07287 | 75,412 |
async def get_client_information(event: classmethod, bot):
"""Get Client Information
Get client from user if logins.py client information was not edited.
:param event: The event builder class or instance to be used.
:param bot: Bot to use Telethon.
:return: client
"""
logger.info('Replyin... | fcf96d93da84dc2c4c1330aa4e9e4fd4a930dda4 | 75,413 |
def public_coverage_filter(data):
"""
Filters for the public health insurance prediction task; focus on low income Americans, and those not eligible for Medicare
"""
df = data
df = df[df['AGEP'] < 65]
df = df[df['PINCP'] <= 30000]
return df | e8a579437fe484a738deefe6b32defaf405b5a58 | 75,414 |
def decrypt_aes_gcm_data(key, tag, plain_data, data):
"""
Decrypts a ciphertext and checks the tag with aes gcm.
:param key: the 32 byte decryption key
:param tag: the authentication tag
:param plain_data: the plaint data to be authenticated
:param data: the ciphertext
:return: plaintext (th... | 226a70fafe239e72bb3b6a6b1852850b12eea0ee | 75,415 |
def encoder(inputs,
embd_size,
dropout_rate,
num_banks,
num_highway_net_blocks,
is_training=True,
scope='encoder',
reuse=None):
"""
:param inputs: A 3d tensor with shape of [N, T_x, E], with dtype of int32. Encoder inputs.
:... | ac0982c895e59791a5c4d2d58bd628ae4fdd9a9c | 75,416 |
def make_Adj_sparse(rows, cols=0, dtype=np.float32, **kwargs):
"""Construct adjacency matrix for a periodic hexagonal
lattice of dimensions rows x cols.
Returns a `scipy.sparse.csr_matrix` object."""
# Check if square
if cols == 0:
cols = rows
# Initialize neighbor indices
n = ro... | 6f2461dca2d1580eb5aa8729ea76fe45bc84cdbb | 75,417 |
import multiprocessing
def get(dsk, keys, optimizations=[], num_workers=None,
func_loads=None, func_dumps=None, **kwargs):
""" Multiprocessed get function appropriate for Bags
Parameters
----------
dsk: dict
dask graph
keys: object or list
Desired results from graph
o... | 2885b72f5eb88a00bb9e56cdc2b13f50656e761c | 75,418 |
def check_contrast(image, fraction_threshold=0.20, lower_percentile=1,
upper_percentile=99, method='linear'):
"""Detemine if an image is low contrast.
Parameters
----------
image : array-like
The image under test.
fraction_threshold : float, optional
The low contr... | 6b495564af9d258e677c7735eb331864b92fc6eb | 75,419 |
def guard_vars(expr):
"""Whereas pomagma.compiler follows the variable naming convention defined
in pomagma.compiler.signature.is_var(), pomagma.analyst.validate and the
puddle editor require VAR guarded variables."""
if expr.name == 'VAR':
return expr
elif expr.is_var():
return VAR(... | c139bfe1e6e0cb0c8d9f10768992fd50c74dbb39 | 75,420 |
def get_snippet(soup):
"""obtain snippet from soup
:param soup: parsed html by BeautifulSoup
:return: snippet_list
"""
tags = soup.find_all("div", {"class": "gs_rs"})
snippet_list = [tags[i].text for i in range(len(tags))]
return snippet_list | 8955aa6eee837f6b1473b8de2d02083d35c3b46e | 75,421 |
def PrintRoster(request, activity_key, order_by='user'):
"""Displays the print roster page for a particular activity.
Args:
request: The view functions request object.
activity_key: The key of the activity to show the roster page for.
order_by: String. Sort order to be applied for the models.UserRegist... | 6595da753763b437e4b8c88301d652e8dbcba0da | 75,422 |
def create_and_setup_user(
user_input: UserRegistration,
auth_manager: AuthOperations,
project_manager: ProjectOperations,
technical_user: bool = False,
) -> User:
"""Create a new user and setup default project and permissions.
Args:
user_input (UserRegistration): Information required f... | 3603a46f412203e22dc1566cb7859dceb568d8a3 | 75,423 |
def test_all(system, lyap_reps=20, **opt_params):
"""
Tests a set of hyperparameters for continue and random predictions and derivative fit, as well as Lyapunov exponent.
Returns, in order:
Continue vptime
Random vptime
Lyapunov exponent
Continue deriv fit
Random deri... | 03286b7f834b91d7cc4b0add928b2b6aa2e7c689 | 75,424 |
def create_synthetic_lowmass_mock_with_satellites(
mock, healpix_mock, synthetic_dict):
"""
"""
mstar_max = min(10**8., 10.**(np.log10(np.max(synthetic_dict['mpeak']))+1))
mock_sample_mask = mock['obs_sm'] < mstar_max
num_sample = np.count_nonzero(mock_sample_mask)
selection_indices = np... | bac78757fd1348390e18aad71e81ac874a6e30aa | 75,425 |
def serving_input_fn(params):
"""
サービング時の入力形式を定義します
推論用の入力データ形式の定義を行います(これはAPIサーバにデプロイしない場合も必要です)
以下では、入力データは、キーをimageとし、浮動小数型のテンソルであることを定義しています
[None, 28, 28, 1]は、データの形状を示しています
TensorFlowで扱われるデータは全て Tensor (テンソル) です
この場合、imageテンソルはランク4のテンソルで、プログラム上では4次元配列で表現されます
各次元の長さは、None ... | 293ec93123a9c6e4ba3919277578b1297809e7d6 | 75,426 |
def initialize_model(ckpt_path, mapping_csv_path, model_factory=Defaults.create):
"""
Initialize the new model from a reference checkpoint.
"""
# Load the reference checkpoint
ckpt = tfc.train.NewCheckpointReader(ckpt_path)
# Get the source -> destination mapping
with open(mapping_csv_path,... | 9e2d3f7a73ca3fb9cd40eb40cba3e527485d8ae9 | 75,427 |
def read_xml(action, filename, **kw):
"""Wrapper around the base read_xml() that pipes warnings
into the given action.
Also handles errors and returns false if the file is invalid.
"""
try:
return convert.read_xml(filename, warnfunc=action.message, **kw)
except convert.InvalidResourceEr... | f24efb8dbd78f42e5895791f0e576de305ad51c9 | 75,428 |
def normalize_shape_name(name):
"""Normalize shape names.
Strip terminal Shape and replaces '_' by spaces and add spaces between
'aA' sequences.
"""
if name.endswith('Shape'):
name = name[:-5] + '\0'
return _normalize(name) | 28c2df501f92dc2044a5c5741d9e9590ee66f727 | 75,429 |
import torch
def to_tensor_variable(array, requires_grad=False, dtype=torch.float32):
"""Convert array to Tensor to the "best" available device."""
return torch.tensor(
array, requires_grad=requires_grad, dtype=dtype, device=device
) | 93aace2da92f3f386a98ec56c5f7b3cd006adfc4 | 75,430 |
def SpatialRepeatNDNode(name, upsample_factor, **kwargs):
"""
same as RepeatNDNode, but assumes first 2 axes will not be upsampled
"""
return RepeatNDNode(name,
upsample_factor=(1, 1) + upsample_factor,
**kwargs) | 1e812c527cef656d558fc19768326616c22769b7 | 75,431 |
def assign_properties(params, props=None, use=True, **kwargs):
"""
Assigns properties from input and deals with missing parameters
Available kwargs (output keys) come from BERV_OUTKEYS()
:param params:
:param props:
:param kwargs:
:keyword berv:
:keyword bjd:
:keyword bervmax:
... | 1c1d4b10e4e3f7a5d5fb13f47ff706edc2664eeb | 75,432 |
import yaml
def read_config(file_name="config.yaml"):
"""Read configurations.
Args:
file_name (str): file name
Returns:
configs (dict): dictionary of configurations
"""
with open(file_name, 'r') as f:
config = yaml.safe_load(f)
return config | 51faf47b4c28d1cbf80631d743d9087430efb148 | 75,433 |
import torch
def create_attack_effects_dataset():
"""Create a training dataset for the "attack - resolve attack effects" subphase.
Returns:
(List[(str, world_state or attack effect tuple)],
List[(str, world_state or attack effect tuple)]): Tuple of training and evaluation data.
"""
#... | c9602ea27d7e0a80af9c92e4bf13f9cb63fcb9d4 | 75,434 |
def batch_delta(conf: BlockConfig) -> DataFrame:
"""Write delta data down to some location.
:param str Path: location to write to
:param str Mode: the mode to write with such as append or overwrite
:param list[str] PartitionBy.Columns=: partition the delta table on one or multiple columns
:param bo... | 05fb9028e88a05767b57892cd890726489934e54 | 75,436 |
import re
import urllib
def find_next_link(soup):
"""Identify and return a link to the next page"""
maybe_link = None
# Various link texts in builtin serials
if WHICH_SERIAL in ('T5D', 'Unsong'):
if soup.find('a', {'rel': 'next'}) is not None: # find by 'rel'='next'
maybe_link =... | b63b9b6b6886f76325cfa29ac54e1252ce0703fc | 75,438 |
import joblib
import tqdm
def get_min_ess(samples, method='bulk'):
"""get_min_ess
Parameters
----------
samples : np.array
(n_chains, n_samples, n_dim)
Returns
-------
"""
if samples.ndim == 1:
samples = samples[np.newaixs, :, np.newaxis]
elif samples.ndim == 2:
... | b2fa1e7319ab75734097b2d895e8c6092efab639 | 75,439 |
def filter_dual_selection_aromatic(sele1_atoms, sele2_atoms, aromatic1_index, aromatic2_index):
"""
Filter out aromatic interactions that are not between selection 1 and selection 2
Parameters
----------
sele1_atoms: list
List of atom label strings for all atoms in selection 1
sele2_at... | b1cb590510e45b0bfb5386e1514f24911156d01b | 75,440 |
def create_loader(
args, filenames, tokenizer, dataset_cls,
shuffle=False):
"""
Creates a generator that iterates through the
dataset.
"""
special_ids = tokenizer.convert_tokens_to_ids([
SP1, SP2, tokenizer.bos_token,
tokenizer.eos_token, HST, RSP
])
# distr... | 631e6028d285f9c9824c2884fd2c03c4ea758e73 | 75,441 |
from click.testing import CliRunner
def cli_runner():
"""click - cli testing"""
runner = CliRunner()
return runner | b0e5a99d59553654f9fab33fadb792f3356422ae | 75,442 |
def rmse(y_obs, y_pred):
"""Computes root mean square error."""
return np.sqrt(np.mean((y_obs.squeeze() - y_pred.squeeze()) ** 2)) | 49330efb8883ea03776c406c52e46dd0532db009 | 75,443 |
def run_sim_rand_TT(N,**kwargs):
"""
Runs one simulation for MINIMUM ACTIVATION TRANSITION control.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
**kwargs
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1) Bounds - must be a (2,2) list with each row in ascending order. Default is given by Tension_Bounds.
2) InitialAng... | faeca2261874503f03dede16bf634b7ec73b9479 | 75,445 |
def determine_parllelism(num_tiles):
"""
Try to stay at a maximum of 140 tiles per partition; But don't go over 128 partitions.
Also, don't go below the default of 8
"""
num_partitions = max(min(num_tiles / 140, 128), 8)
return num_partitions | b448ba9493eee015dec0d4d1a1c208b3df76aa34 | 75,446 |
async def get_token(value: str, user: User = Depends(current_user)):
"""Returns token details by string value"""
_, token = user.get_token(value)
if token is None:
raise HTTPException(404, f"Token with value {value} does not exist")
return token | 896d203180b30b21ed5795ea3ed525262f07377c | 75,447 |
def comma_nonempty_list(pr:Parse) -> Parse:
"""construct parser for comma-separated list"""
return Parse.separated_nonempty_list(pr,next_value(',')) | c14c703a08761e228a7f958b4d942103ac05ca4a | 75,448 |
def ROIsearch(data, center, r, indicator):
"""
This equation screens all fibers, leaving only the fibers that pass through the ROI.
:param data: The original line_data which stores all the fiber.
:param center: The center coordinates of the ROI.
:param r: The radius of ROI.
:par... | 1bfa8d4695e8ad86ccadfcf5f957c4a8aa4baf40 | 75,449 |
def profile(func):
"""
A simple function profiling decorator.
"""
def wrap(*args, **kwargs):
global pr
pr.enable()
result = func(*args, **kwargs)
pr.disable()
pr.print_stats(sort="tottime")
return result
return wrap | a8e0bafef8dd459123bd247039220838fc191001 | 75,450 |
def video_grains(src_id=None,
flow_id=None,
creation_timestamp=None,
origin_timestamp=None,
sync_timestamp=None,
rate=DONOTSET,
duration=DONOTSET,
format=None,
width=None,
... | e4325025d27c163a6ab70aedfea6031261cb5d44 | 75,451 |
import jsonschema
def validate_args(conf):
"""Validate arguments based on configuration"""
try:
jsonschema.validate(conf, config.CONF_SCHEMA)
except jsonschema.ValidationError as err:
log.error("Invalid Guardduty configuration: %s", str(err))
return False
return True | 709fa76637d08d17a04310f64e824fdf4e949e4a | 75,452 |
from typing import Dict
def server_option_changed(
old_options: Dict[str, ConfigOption], new_options: Dict[str, ConfigOption]
) -> bool:
"""Return True if and only if an option in the server section differs
between old_options and new_options."""
for opt_name in old_options:
if not opt_name.st... | 5e9be8bb44cc69bc1eaff40449df0a1359809e72 | 75,453 |
import json
def get_port_info(port):
"""
Returns information about a specific port and its risk levels
"""
with open(ROOT_DIR + FUNC_PATH + "port_security.json", "r+") as prt:
port_info = json.load(prt)
if port in port_info["ports"].keys():
return port_info["ports"][port]
... | 2ebfa8c45b25b034bebf9ce379e5e77a99e52232 | 75,454 |
def pa():
"""positions + actions"""
return FilterObsByIndex(CartPoleSwingUpVarLenFullEnv(), indices_to_keep=[0, 2, 3, 6]) | 6caf4fe90bf0ce98906489b88645f2f466fa9257 | 75,455 |
def _Run(args, max_messages, return_immediately=True):
"""Pulls messages from a subscription."""
client = subscriptions.SubscriptionsClient()
subscription_ref = args.CONCEPTS.subscription.Parse()
pull_response = client.Pull(subscription_ref, max_messages,
return_immediately)
if... | c2a507a93d136c0dd369af95cf36da72f23d599d | 75,456 |
def apim_backup(client, resource_group_name, name, backup_name, storage_account_name,
storage_account_container, storage_account_key):
"""back up an API Management service to the configured storage account """
parameters = ApiManagementServiceBackupRestoreParameters(
storage_account=stor... | 5e4aa437cace25e0a706f0af930e817a9a41156b | 75,457 |
def parse_root(root, attribs):
"""[summary]
Arguments:
root {[type]} -- [description]
attribs {[type]} -- [description]
Returns:
[type] -- [description]
"""
rows = []
for i, node in enumerate(root):
node_attribs_dict = parse_one_node(node, attribs)
rows.... | 91da74cec91380d904f4b09962dad4d5fa063a7d | 75,458 |
def no_numbers(data: str):
"""
Checks whether data contain numbers.
:param data: text line to be checked
:return: True if the line does not contain any numbers
"""
numbers = "0123456789"
for c in data:
if c in numbers:
return False
return True | d6f0f306c980da2985d906fa0eaee96d2f598e7b | 75,459 |
def Isolated_stars(pos,Tmag,flux,Median, Distance = 7, Aperture=3, Mag = 16):
"""
Find isolated stars in the scene.
"""
#pos, Tmag = sd.Get_PS1(tpf,magnitude_limit=18)
pos_shift = pos + 0.5
ind = ((Distance//2< pos_shift[:,0]) & (pos_shift[:,0]< flux.shape[1]-Distance//2) &
(Dist... | 044c2bd8c885c148b4901f662c81431fc9aab7c8 | 75,461 |
def get_bgp_neighbor_capabilities(
device, neighbor_address, address_family, vrf, output=None
):
""" Get neighbor capabilities
Args:
vrf ('str') : VRF name
device ('obg') : Device object
output ('dict') : Parsed output
... | ee0994c6cba9a095d6a046bcb535b7f15b15e002 | 75,462 |
def get_b16_config():
"""Returns the ViT-B/16 configuration."""
config = ml_collections.ConfigDict()
config.name = 'ViT-B_16'
config.half_precision = True
config.encoder = ml_collections.ConfigDict()
config.encoder.patches = ml_collections.ConfigDict({'size': (16, 16)})
config.encoder.hidden_size = 768
... | 9ef5fb1e74a77fcf9e364030d9ccc9eef3686ea6 | 75,463 |
def get_template_include_key(template_name, prefix=None):
""" Get a valid element class name, we'll stick to ascii letters, numbers and hyphens.
NB class names cannot start with a hyphen
"""
digest = int(hash_function(template_name).hexdigest(),16)
hash = base36.from_decimal(digest)
if prefi... | 5ad7dd4fd65238b5179fb4e97b7006f4d84973e4 | 75,465 |
def estimate_skew_angle(raw):
"""
估计图像文字角度
"""
raw = resize_im(raw, scale=600, max_scale=900)
image = raw - amin(raw)
image = image / amax(image)
m = interpolation.zoom(image, 0.5)
m = filters.percentile_filter(m, 80, size=(20, 2))
m = filters.percentile_filter(m, 80, size=(2, 20))
... | f6a5e797a4f129fed54799fc7e9dd8a18a8b17d9 | 75,467 |
import copy
def climate_radio_thermostat_ct100_mode_and_setpoint_on_different_endpoints_fixture(
client,
climate_radio_thermostat_ct100_mode_and_setpoint_on_different_endpoints_state,
):
"""Mock a climate device with mode and setpoint on differenet endpoints node."""
node = Node(
client,
... | 7e4b6a14993c5aec0eea093849ccfa42321c0487 | 75,468 |
def collect_model_translations(model_opts, fields=None):
"""
:param model_opts:
:param fields: list of field_name
:return: iterator
"""
model = model_opts['model']
qs = model.objects
if hasattr(model_opts['opts'], 'get_queryset'):
qs = model_opts['opts'].get_queryset()
qs = f... | bdf3329250a6a32a50020e762f8e751d32f7a496 | 75,469 |
def bers_per_snr_nn(spa_nn, input_llr, target, codewords_per_snr_in_batch, batch_size):
"""
Bit error rates from the neural network decoder change during training depending on the state of the neural network.
Therefore they need to be calculated every epoch for training and test dataset.
The input are t... | 5a772d0250c15eade5a56357adeb7b1f431ca6b0 | 75,470 |
def rootsumsquares(a):
"""
Calculates the square root of the sum of the squares of a vector (no mean).
:a: (array or list of floats) vector
:returns: (float) rms without the mean part of a
"""
return np.sqrt(np.sum(np.power(a,2))) | 7c0e1c06b51aa4e7b85a0a84b0bc9bf2c043a01d | 75,471 |
def get_serializer(instance, plugin=None, model=None, *args, **kwargs):
"""
:param instance: model instance or queryset
:param plugin: plugin instance that is used to get serializer for
:param model: plugin model we build serializer for
:param kwargs: kwargs like many and other
:return:
"""
... | 494aa1e0ad958d80ea2dc7d0cfc24520dce65951 | 75,472 |
import random
import string
def crack(ciphertext, *fitness_functions, ntrials=30, nswaps=3000):
"""Break ``ciphertext`` using hill climbing.
Note:
Currently ntrails and nswaps default to magic numbers.
Generally the trend is, the longer the text, the lower the number of trials
you nee... | 6f2d12c31fb4557e28d6b40bd7aedc18774a81ee | 75,473 |
def get_class(name, engine, schema=None):
"""
"""
metadata = sa.MetaData(engine, schema=schema)
metadata.reflect(engine, only=[name])
Base = automap_base(metadata=metadata)
Base.prepare()
return Base.classes[name] | 964f1ec4f9913f93f878db24de30e1b34ad3843b | 75,474 |
def _get_vacuum_device_pause():
"""Return a vacuum device in pause."""
device = mock.MagicMock(spec=Dyson360Eye)
device.name = "Device_Vacuum"
device.state = mock.MagicMock()
device.state.state = Dyson360EyeMode.FULL_CLEAN_PAUSED
device.state.battery_level = 40
device.state.power_mode = Powe... | 45acbf9da52af365803c6a1a98e568cb82a801dc | 75,475 |
def subsample_fourier(x, k, normalize=False, aa_filter=False):
"""
Periodization in Fourier space. This corresponds to a subsampling in physical space.
Parameters
----------
x : array
Input data (2D or 3D arrays depending of a potential batch dimension).
k : int
DESCRIPTION.
... | 25d0dbe1764267289e04c27e00163baff08895bb | 75,476 |
def splinter_webdriver():
"""Use Chrome, which is simpler to launch in headless mode.
Firefox needs the Gecko driver to be manually installed first.
Moreover, as of 22/07/2018, Firefox in headless mode is not yet
available in python:3.6-alpine3.7 (version 52).
"""
return 'chrome' | 6586567f423c12475b2a084d9945667bc34636bc | 75,477 |
def normalize_answer(s):
"""Lower text and remove extra whitespace."""
def remove_articles(text):
return re_art.sub(' ', text)
# def remove_punc(text):
# return re_punc.sub(' ', text) # convert punctuation to spaces
def white_space_fix(text):
return ' '.join(text.split())
... | 21a9522584697049fee829c82bba9958642e6a24 | 75,478 |
def EncoderConfig() -> hyperparams.Params:
"""Returns Params for configuring one `DualEncoder` modality."""
p = hyperparams.Params()
p.Define(
'input_features', '',
'Feature(s) from the input batch to feed to the encoder. The structure '
'of this field determines the number and structure of the ... | fdeb0885733fbc8eee004852da3e66c5b102017b | 75,480 |
def lung_capacity(mass):
"""Caclulate lung capacity
Args
----
mass: float
Mass of animal
Return
------
volume: float
Lung volume of animal
References
----------
Kooyman, G.L., Sinnett, E.E., 1979. Mechanical properties of the harbor
porpoise lung, Phocoena ... | 75bddd298ad7df69cda6c78e2353ee4cef22865a | 75,482 |
def get_forcing_variants(variants):
"""If a condition is forcing, a variant will be picked
when meeting the condition."""
forcing_variants = []
for variant in variants:
if 'conditions' in variant:
if evaluate_conditions(variant['conditions'], case_attrs):
for conditi... | 94911c15ceeacf6f028503eb19538f5fece34ac1 | 75,483 |
from typing import Tuple
def popStep(header:Header) -> Tuple[Step, Header]:
"""Returns first Step in header, along with a new Header
containing the remaining Step's"""
step = peekStep(header)
nh = Header(header.encoding, header.steps[1:])
return (step, nh) | 76b697a1c1108fb73e7282e1619d5904bfa0778c | 75,484 |
def polynomial(X,grad):
"""
Computes each power of X's values from 0 to grad
and then normalizes them.
"""
poly = PolynomialFeatures(grad)
X_pol = poly.fit_transform(X)
X_pol[:,1:], mu, sigma = normalizar(X_pol[:,1:])
return X_pol, mu, sigma | ef84206a66bb6b849df0eb2c8b60f524078ceed1 | 75,485 |
from typing import Optional
def make_local_att_mask_from_breakpoints(
att_breakpoints: tf.Tensor,
local_radius: int,
use_starting_breakpoints: bool = False,
name: Optional[Text] = None) -> tf.Tensor:
"""Makes local self-attention mask from attention breakpoints.
Each attention breakpoint marks th... | b51dd444c6b1b1445fdab662d466e2a831cc1ed7 | 75,486 |
def get_population_by_age(cache_dir: PathType = DEFAULT_CACHE_DIR) -> pd.DataFrame:
"""
Returns a DataFrame with "age" as index and two columns:
"value" (absolute counts) and "percentage" (<=1.0)
"""
data_proxy = RemoteFolderProxy(folder_url=BASE_URL, local_path=cache_dir)
path = data_proxy.get(... | 433c9924237181114c2aef9f014c0f0993111a0a | 75,488 |
def correlation_calculator(x_points: list[float], y_points: list[float]) -> float:
"""Return a correlation of the association between the x and y variables
We can use this to judge the association between our x and y variables to determine if
we can even use linear regression. Linear regression assumes tha... | 3fa697a15ff86511cff2a1b37b532f3d14caf7d8 | 75,489 |
async def database_feeds(db):
"""Get database metrics pertaining to feeds"""
metrics = {
"database_feeds_count_total": await db.feeds.count(),
"database_feeds_status_error_total": 0,
"database_feeds_status_unreachable_total": 0,
"database_feeds_status_inaccessible_total": 0,
... | c7ebbda9acc37edafb22103395904c2863379cf6 | 75,490 |
def save_serial_connect(issue, serialno=None):
"""
it save pair info serial no. and issue name
"""
#doc = frappe.get_doc("Product Issues", "howno")
if (serialno != None):
if (frappe.db.count("Product Issues", filters={"issue":issue})==0):
... | c73a1bef06f67eaeefa7156bad66953bbb0ca3c3 | 75,491 |
def match_samplename(samplename, pppb_mapping):
"""translate samplename to pppb id
treat badly behaved samplenames and duplicates"""
# correct common mistakes
samplename = samplename.upper().replace(
'__', '_'
).replace(
'_PC3_170220_CP', '_PC3_170220_CPP'
)
# badly placed "P... | 2f557f0717ef189bfdb7d5984bbef0a3e23e6de7 | 75,492 |
import math
def count_ctdd(aa_set, sequence):
"""
helper function for ctdd encoding
:param aa_set:
:param sequence:
:return:
"""
number = 0
for aa in sequence:
if aa in aa_set:
number = number + 1
cutoffNums = [1, math.floor(0.25 * number), math.floor(0.50 * num... | bc4f55855794d073397b471652e8dbab18520d1b | 75,493 |
def completed_request(request_id):
"""
Mark the request as completed
:param request_id:
:return:
"""
current_request = query(Request).filter_by(id=request_id).first()
current_request.is_active = False
session.commit()
return get_requests() | 7f7db7de1b5fa636681b093fb4a7e4363dfd5423 | 75,494 |
def LSV_main(ui,config_data=None):
"""
This function is connect to 'CA' button in the Experiment Type window
Parameters
------
ui : the Ui_Mainwindow object
Return
------
CA: the Ui_ca object
"""
LSV,LSV_window = ui.show_LSVwindow()
grid = QGridLayout()
LSV.plot_area.... | e48f6d5c4105210279d64b8ef14e3f379d81b5e3 | 75,495 |
import hashlib
def request_fingerprint(request, include_headers=None):
"""
Use hash function to compress the request into a fingerprint
:param request: scrapy.Request
:param include_headers: http header, default none
:return: a 40-character string which include 0~f
"""
if include_headers:
... | 4a3758e61d06f0fbb86a6eaef9248fbcaa8f26b9 | 75,496 |
def generate_where_in_clause(field_name, feature_list):
"""
Args:
field_name (str): Name of column to query
feature_list (list): List of values to generate IN clause
Returns:
string e.g. `WHERE name IN ('a' ,'b', 'c')`
"""
# Build up 'IN' clause for searching
where_str = f"... | d00179cfa6a9841b00195b99863d7b37f60c45e4 | 75,497 |
def set_username(strategy, details, user, social, *args, **kwargs):
"""This pipeline function can be used to set UserProfile.has_username_set = True
Normally not used if the auto-generated username is ugly
"""
if not user:
return None
response = None
if hasattr(user, 'profile'):
... | 1c217a8c0b75e2acb38c06b8f9cefdf70e272e91 | 75,498 |
def svn_client_url_from_path(*args):
"""svn_client_url_from_path(char url, char path_or_url, apr_pool_t pool) -> svn_error_t"""
return apply(_client.svn_client_url_from_path, args) | 9aa753b38d24480fc144540b0d96bb49eb64dda5 | 75,501 |
from scipy.stats import chi2
import numpy as np
def wave_signif(Y,dt,scale1,sigtest=-1,lag1=-1,siglvl=-1,dof=-1,mother=-1,param=-1):
"""
This function is the translation of wave_signif.m by Torrence and Compo
use scipy function "chi2" instead of chisquare_inv
The following is the original comment in wave_signif... | 5d35fec5dd69596c73cccaf4c27358f6d03c3e37 | 75,502 |
from typing import Sequence
def create_component(
name: str,
classes: Sequence[str] = (),
*,
rawtext: str = "",
children: Sequence[nodes.Node] = (),
**attributes,
) -> nodes.container:
"""Create a container node for a design component."""
node = nodes.container(
rawtext, is_div... | 3c4b36d28bd854d48ff84c9bb7ce39370c463d97 | 75,503 |
import torch
def merge_classes(classes, num_elements, predictions, labels, verbose=False):
""" Merge the predictions based on the imagenet tree
- classes: an array of size [num_classes] that contains strings with wordnet synset name
- num_elements: an array of size [num_classes], the number of data sampl... | 92e1100d1fc73795bfc39d9ae9ab9ee5ac75cb6a | 75,504 |
def parse_weather(weather_data_raw):
"""parse the useful weather data from dict of the openweathermap.org json data.
returns another, slimmed down dict with the chosen elements"""
parsed_weather = {}
parsed_weather['sunrise'] = dt.fromtimestamp(weather_data_raw.get("city").get("sunrise")).time()
pa... | 6c2dc744412d5fd8f45eab2071365024b4eeea7b | 75,505 |
def remove_punctuation(text):
"""
This function takes strings containing self defined punctuations and returns
strings with punctuations removed.
Input(string): one tweet, contains punctuations in the self-defined list
Output(string): one tweet, self-defined punctuations removed
"""
translat... | 65539c5b39330807337c17d3ea55a0fc91d23e88 | 75,506 |
def issue_comment_add_reaction(
repo, issueid, commentid, username=None, namespace=None
):
"""Add a reaction to a comment of an issue"""
repo = flask.g.repo
issue = pagure.lib.query.search_issues(
flask.g.session, repo, issueid=issueid
)
if not issue or issue.project != repo:
f... | 68aefa8a5eacbf17af0a1414d39a61269609129b | 75,507 |
def __resize_stretch(cv2_img, to_shape):
"""
Resizes the image to the given size, ignoring aspect ratio.
:param cv2_img: The image to resize.
:param to_shape: The desired shape.
:return: A new, resized cv2 image.
"""
to_width, to_height = to_shape[0], to_shape[1]
# Resize the image
... | a73384fa954fca989799c1f3379ff37a588716fc | 75,508 |
from typing import Optional
from typing import Union
from typing import Any
from typing import Dict
import copy
def get_parameter_value_and_validate_return_type(
domain: Optional[Domain] = None,
parameter_reference: Optional[Union[Any, str]] = None,
expected_return_type: Optional[Union[type, tuple]] = Non... | 42deb7dc27ac4eb2f0ad21519315aff7139f59b2 | 75,509 |
def por(a1, a2, fmt=None):
"""Bitwise OR"""
return c2repr(_inconv(a1) | _inconv(a2), fmt) | 59bd6c468a94ba1d2b5d128fb907d55c22382720 | 75,510 |
import requests
def get_wait_time(token):
"""
The item in entries schema:
{
u'waitTime': {
u'status': u'Down', # or u'Operating'
u'postedWaitMinutes': 5,
u'fastPass': {
u'available': True,
u'endTime':... | d3915ee70c83b6eae0f2b491c99010bf2ee79754 | 75,511 |
def get_genome_operon_labels(operon_context):
"""For each genome, label it based on whether the operon is found."""
# Make an empty dict
output = dict()
# If "Show All Genes" was selected
if operon_context == "ALL":
# Then fill in a "None" value for each genome
return output
... | cab0752de195b45603d43df0bb968d0323563671 | 75,512 |
def _get_integer_from_tag(e, tag):
"""This convenience function returns an integer value for a particular
tag in element e. For example, if element e represents
<note><duration>2</duration></note>, _get_integer_from_tag(e,
'duration') will return 2
"""
d = e.find(tag)
return int(d.text) if ... | d984dce64c922893e1680e30483e92014cb82f87 | 75,513 |
from datetime import datetime
def format_datetime(timestamp):
"""Format a timestamp for display."""
return datetime.utcfromtimestamp(timestamp).strftime('%Y-%m-%d @ %H:%M') | f841d74e381f4524a7fc428feb4111eb5f282538 | 75,514 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.