content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def normalize_http_url(url):
"""
Strip http schema, port number and path from a url
:param url: the url to normalize
:return: normalized url
"""
parsed = urlparse(url)
netloc = parsed.netloc
return netloc.split(':')[0] if netloc else url | d514f72c787399e0253ecabab2d236a9ab75f816 | 56,300 |
def loop_until_choice_is_correct(msg_prompt: str, valid_choices: dict) -> str:
"""
Loop until a valid value is provided, which must match a key from
`valid_choices`.
Args:
msg_prompt (str): Prompt to display to the user to enter a choice.
valid_choices (dict, optional): Keys are valid c... | bb05f1d11b14611ffcada93629382bfb8a447fad | 56,301 |
import os
def _get_cflags(files, v=0):
""" Collect CFLAGS from pkgconfigs. """
cflags = []
def add_variants(f):
for lang in ['', ' -x c++']:
for i in range(len(_stdinc) + 1):
cflags.append(' '.join([lang, f] + _stdinc[:i]))
for pc in filter(lambda pkg: pkg.endswith('.pc'), files):
ste... | 87d0185fa5c3b7aae015c8916560b7f23632eafe | 56,302 |
from email.header import decode_header
def emailHeader(header):
"""
Takes an email header and decodes it if it has been MIME-encoded.
:param header: The email header to be decoded
:return: The decoded header returned as a string
"""
dh = decode_header(header) # Returns a list of 2-... | 50df52dbd52d2ee02c3870e96ff77d9ccd38a844 | 56,303 |
import argparse
import sys
def parse_args(args):
"""Parse command-line arguments.
Parameters
----------
args : list of strings
command-line arguments.
Returns
-------
options : :class:`argparse.ArgumentParser`
Command line arguments.
"""
parser = argparse.Argumen... | f0c29be28a5a49422ee5bea7bb294cb0cb3a45fa | 56,304 |
import os
def get_transformers(name):
"""Download pretrained transformer models.
Args:
name (str): the name of the pretrained models. options are ``["bert-base-cased",
"bert-base-uncased", "gpt2-medium"]``.
Returns:
(str): directory of the downloaded model.
"""
data_d... | 35114b957a075bad020a2699d46eaa1cd35cac46 | 56,305 |
def get_hash(string_value, algorithm):
"""
Create hash for the given string and algorithm
"""
if not isinstance(string_value, str) and not algorithm:
return string_value
hash_object = HASH_ALGO.get(algorithm)(string_value.encode())
if not hash_object:
return string_value
hex_... | 26031c2335b515b7e413fac47c9a9452b40fe188 | 56,306 |
import threading
import os
def get_default_connection():
"""Return the default datastore connection.
dataset defaults to helper.get_dataset_from_env(), host to
os.getenv('DATASTORE_HOST'), and credentials to
helper.get_credentials_from_env().
Use set_options to override defaults.
"""
tid = id(threadin... | 1cc6fef12312d97e63c81eb7a5626bd70757d721 | 56,307 |
def middle(t):
"""Returns all but the first and last elements of t.
t: list
returns: new list
"""
return t[0:-1] | c94f0d6575257d7528c0164823944058d794d0ca | 56,308 |
from typing import Tuple
from pathlib import Path
import logging
def save_distplot(df: DataFrame,
output_plot: str,
x_name: str,
title: str,
color: str,
x_label: str = None,
y_label: str = None,
... | fdfa525737499bc42eadacf2a243f9bfae811657 | 56,309 |
def rollout_multiple(
*args,
num_repeats=1,
initial_context=None,
accum_context=True,
**kwargs
):
"""
Do multiple rollouts and concatenate the paths
"""
assert num_repeats >= 1
last_path = rollout(
*args,
accum_context=accum_context,
in... | 285399b40928c552b7755e19180e2f835dd5d272 | 56,310 |
def get_cdf(prc, bg_prc): # , study_id, cdf_df=None):
"""
Specifically for the dictionary data
prc = syn[study_id]['lost']['prc']
bg_prc : which prc to use as bg: 0 = min, 1 = 5% , 2 = 10%, 3 = 15%, 4 = 20%
"""
int_cdf = np.zeros((51, 1))
# if cdf_df is None:
# cdf_df = pd.DataFram... | 38481d3d0d0bd662e837e2dade3fdd0aa7e61c70 | 56,311 |
def joli_string(f):
"""renvoie une jolie chaine de caractèrepour la formule f """
operator = {
'OU': 'u',
'ET': 'n',
'NON': '-',
'IMPL': '=>',
'EQ': '<=>',
'VRAI': 'V',
'FAUX': 'F'
}
n = f.nb_operandes()
if n == 0:
v = f.get_val()
... | bf2160481f444fa690c61750ba286fe1739d9291 | 56,312 |
import time
def generate_proposals(predictor, test_data, imdb, vis=False, thresh=0.):
"""
Generate detections results using RPN.
:param predictor: Predictor
:param test_data: data iterator, must be non-shuffled
:param imdb: image database
:param vis: controls visualization
:param thresh: t... | 240cd3fdcb148cc0a205c71eed7d8a453f8ff16a | 56,313 |
import optparse
import sys
def parse_options():
"""Generate command line options."""
ALLOWED_COMMANDS = ["list-vdis", "clean-vdis", "list-instances",
"clean-instances", "test"]
arg_str = "|".join(ALLOWED_COMMANDS)
parser = optparse.OptionParser("%prog [options] [" + arg_str + ... | 862d6881eb08ae088bfbdbd8b9f4165c5f1dbc47 | 56,314 |
from typing import Callable
def _create_tasks(reader: Callable, assets, threads, *args, **kwargs) -> TaskType:
"""Create Future Tasks."""
tasks: TaskType
if threads and threads > 1:
with futures.ThreadPoolExecutor(max_workers=threads) as executor:
return [
(executor.su... | 7684e46b8e2061a0812b0579d106671949357e0d | 56,315 |
from ..items import HieroClipItem
def clipRegistrationsFromHieroShotItems(hieroShotItems, context, publishSharedClips,
sharedClipTargetEntity, customClipName=None, omitAssetisedClips=True):
"""
@itemUsage hiero.items.HieroClipItem
"""
# This will hold an ItemRegistration for each shot
shotRegistrations... | 99ef325eae1cb1ceed18e33c5356ec4530a1bc18 | 56,316 |
import torch
def sample_init_points(n_vertices, n_points, random_seed=None):
"""
:param n_vertices: 1D np.array
:param n_points:
:param random_seed:
:return:
"""
if random_seed is not None:
rng_state = torch.get_rng_state()
torch.manual_seed(random_seed)
init_points = ... | 4ccfa02292992bc54989eb4cea6d9f7befb7a67b | 56,317 |
def iget_list_column_slice(list_, start=None, stop=None, stride=None):
""" iterator version of get_list_column """
if isinstance(start, slice):
slice_ = start
else:
slice_ = slice(start, stop, stride)
return (row[slice_] for row in list_) | 1c604be6c59d43fb1c2b1b1a3078f5e98105347f | 56,318 |
def create_saver():
""" Restore the moving average version of the learned variables for eval. """
variable_averages = tf.train.ExponentialMovingAverage(FLAGS.moving_average_decay)
variables_to_restore = variable_averages.variables_to_restore()
return tf.train.Saver(variables_to_restore) | 3002c2f91fe482ef243a35563118fbf607ac8afc | 56,319 |
async def hashtag_info(sessionid: str = Form(...),
name: str = Form(...),
clients: ClientStorage = Depends(get_clients)) -> Hashtag:
"""Return Hashtag info (id, name, picture)
"""
cl = clients.get(sessionid)
return cl.hashtag_info(name) | d59e375e9eeb1c8a6b636632bdf6be60c2f58a58 | 56,320 |
def config_dict(gps_dict):
"""A test configuration based on a dictionary"""
cfg = config.Configuration("dictionary")
cfg.update_from_dict(gps_dict, section="gps")
return cfg | bc1f5119713980914c05e51adfc586415bae08b3 | 56,321 |
def compute_contract_address(address: Address, nonce: Uint) -> Address:
"""
Computes address of the new account that needs to be created.
Parameters
----------
address :
The address of the account that wants to create the new account.
nonce :
The transaction count of the account... | 6cee979e8fc325b2ea2d96adce9a8c13c8090619 | 56,322 |
def single_plot(fig_num: int, ax_prop: dict, arr_A: list, arr_B: list, filenames_db: list, marker: str, mark_size: float,
bsf: bool, rev: bool, shrink: bool, xlab: str, ylab: str,
title: str, filename: str, extra_line: list = None, mdpi: int = 400) -> int:
"""
Args:
:par... | 440ea0e406ed4deb6f8e7798305f93070bd14429 | 56,323 |
def _wrapper(args=None):
# type: (Optional[List[str]]) -> int
"""Central wrapper for all old entrypoints.
Historically pip has had several entrypoints defined. Because of issues
arising from PATH, sys.path, multiple Pythons, their interactions, and most
of them having a pip installed, users suffer ... | cca1faed560e8622fd6627bc7bd0897d2d0bce6e | 56,324 |
import random
def assign_read_kmers_to_contigs(reads_filename, kmer_ii, kmer_size):
"""
Given a set of reads and k-mer length, assign k-mer counts to the contigs.
"""
contig_counts = defaultdict(int)
pf = SeqIO.ParseFastQ(reads_filename)
#tuple = pf.getNextReadSeq()
kmer = None
conti... | e573f7d87f6ce4e523a6e29f10725d6cd003c6c1 | 56,325 |
def Base64EncodeConditional(input_text):
"""
Values which can be
:param input_text:
:return:
"""
if not isinstance(input_text, str):
raise Exception("input_text should not be %s", type(input_text))
if r_cgi_vars_char_set.search(input_text) and not input_text.startswith(base64_prefi... | 0f225f8ef33c67c51a2ca508488a5e56921b36ab | 56,326 |
def _generate_widget_parameters(bot_name, user_photo, size, corner_radius, access_write):
"""
Generate common widget embed code parameters.
"""
user_photo_bool = str(user_photo).lower()
data_telegram_login = 'data-telegram-login="{}" '.format(bot_name)
data_size = 'data-size="{}" '.format(size)... | 97132676a5e7218b1224e9be0fff4e178157c4ca | 56,327 |
def application_instance(db_session, pyramid_request):
"""Return the ApplicationInstance that the test OAuth2Token's belong to."""
application_instance = ApplicationInstance(
consumer_key=pyramid_request.lti_user.oauth_consumer_key,
shared_secret="test_shared_secret",
lms_url="test_lms_u... | 59036cde4b8a40f534c0a1faf21a704c73379148 | 56,328 |
def eval_loss(model, mode, orig_img, adv, lab, autoencoder, c_start, kappa,
gamma, beta, to_optimize=True):
"""
Compute the loss function component for the network to find either
pertinent positives (PP) or pertinent negatives (PN).
Input:
- model : nn model
- mode ... | ddecfdb08ddcb104826732561b935780cbb0f733 | 56,329 |
def docstring_parameter(*sub):
""" Decorator to add strings to a doc string."""
def dec(obj):
obj.__doc__ = obj.__doc__.format(*sub)
return obj
return dec | 56181279d4999008df792873fd3bf411dff9d2c7 | 56,330 |
def GetDisplayPosition(config_name, type_order=CONFIG_TYPE_DUMP_ORDER):
"""Given a config_name, return display position specified by suffix_order.
Args:
config_name: Name of config to look up.
type_order: A tuple/list of config types in the order they are to be
displayed.
Returns:
If... | 5016f8f85136043e5190ddb30e1279be6417178e | 56,331 |
import os
def main_csv(args):
"""
Args.
-----
- url : str, API Endpoint
- token : str, Authentication Token
- file_path : str, path to CSV file
Returns.
--------
- pd.DataFrame
"""
# Get Token
def _get_auth_token():
url = os.path.join(args.url_base, "... | e96e41588fe11b6a6ed05efa07150ca270b0e6d5 | 56,332 |
def stack_percentage_bar(results, horizontal=False):
"""\
results : pandas.DataFrame
results.index is the name of each sample.
results.columns is the label of each category
horizontal: bool
If the figure should be horizontal.
"""
# the following modules should been loade... | c1409f29d4b708e3c64f9bda81642870c34f1840 | 56,333 |
from typing import Tuple
def mincresample(img: MincAtom,
xfm: XfmAtom, # TODO: update to handler?
like: MincAtom,
invert: bool = False,
interpolation: Interpolation = None,
extra_flags: Tuple[str] = (),
new_name_wo_... | c519a440e251f1e3c8084565d381aec4671a3954 | 56,334 |
def repunctuate_character(letters, punctuation):
"""Apply the recorded punctuation to a character. The letters must be
an iterator of base characters."""
if punctuation == 'UPPER':
return next(letters).upper()
elif punctuation == 'LOWER':
return next(letters).lower()
else:
re... | 92cd8b30466e19a8ce1278f0b81440399c7f809c | 56,335 |
def get_tree_coords(tree):
"""Takes Phylo tree object and populates it with coordinates
that can be used to plot the tree from scratch"""
for _i, i in enumerate(tree.get_terminals()):
i.y = _i
i.x = tree.distance(i)
for i in reversed(tree.get_nonterminals()):
_ = i.clades
... | debd0a995dddab8a0287a3d553a0edeacef5e777 | 56,336 |
def cluster_scale_out(base, cluster_id, count=None,
expected_status='SUCCEEDED', wait_timeout=None):
"""Utility function that scale out cluster."""
params = {
'scale_out': {
'count': count
}
}
res = base.client.trigger_action('clusters', cluster_id, par... | 62030d1ed0cded0fbdff675203b91c8093ef46f3 | 56,337 |
def category_view(slug, page):
"""List latest topics in the category."""
board_id = h.get_board_id()
user = g.user
h.require_board_access(board_id, user.id)
category = board_category_query_service.find_category_by_slug(
board_id, slug
)
if category is None:
abort(404)
... | 003391b0822f2f5ad64320be93cb055df6904d87 | 56,338 |
def square_loss(labels, predictions):
""" Square loss function
Args:
labels (array[float]): 1-d array of labels
predictions (array[float]): 1-d array of predictions
Returns:
float: square loss
"""
loss = 0
for l, p in zip(labels, predictions):
loss = loss + (l - ... | 888e0945fd7cbbbb4f56a98334b932d3117c5db9 | 56,339 |
def association_consistency(document, dictHeaderPosition, desiredColumns, newRuleList):
"""
This function performs a per tuple check to see if the desired columns satisty the consistency rules provided by the user
Args:
document(RDD): the document to analyze
dictHeaderPosition(dict): prelim... | c14993f57136176cc535d54650f24bf49dde0df9 | 56,340 |
def count_per_group_nb(group_arr):
"""Return count per group."""
result = np.empty(group_arr.shape[0], dtype=np.int_)
j = 0
prev_group = -1
run_count = 0
for i in range(group_arr.shape[0]):
cur_group = group_arr[i]
if cur_group < prev_group:
raise ValueError("group_ar... | 618bb79a766410846a4cc1e43982be36bcd24bdf | 56,341 |
from re import S
def roots_quadratic(f):
"""Returns a list of roots of a quadratic polynomial. If the domain is ZZ
then the roots will be sorted with negatives coming before positives.
The ordering will be the same for any numerical coefficients as long as
the assumptions tested are correct, otherwise... | 5f86db9a0b5c72335e4f71a916233a33d2a3e6d2 | 56,342 |
import torch
def _index(tensor_3d, tensor_2d):
"""This function is used to index a 3d tensors using a 2d tensor"""
x, y, z = tensor_3d.size()
t = tensor_3d.reshape(x * y, z)
tt = tensor_2d.reshape(x * y)
v = t[torch.arange(x * y), tt]
v = v.reshape(x, y)
return v | f2316f49a77fc094277a221318f9c0ede18da688 | 56,343 |
def apply_shifts_dft(src_freq, shifts, diffphase, is_freq=True, border_nan=True):
"""
adapted from SIMA (https://github.com/losonczylab) and the
scikit-image (http://scikit-image.org/) package.
Unless otherwise specified by LICENSE.txt files in individual
directories, all code is
Copyright (C... | 68891234071f789b0f46b78a04fe3e67b35130ce | 56,344 |
from typing import Counter
def count_friends(users):
""" Count how often each friend is followed.
Args:
users: a list of user dicts
Returns:
a Counter object mapping each friend to the number of candidates who follow them.
Counter documentation: https://docs.python.org/dev/library/... | 0b4f5d556bdf45eaa737119dd645d24b9df58e36 | 56,345 |
def search(pattern, string):
"""Scan through string looking for a match to the pattern, returning true
or None if no match was found."""
return Regex(pattern).search(string) | 6a5721bff7388f71875f4b168a73e3415212b92d | 56,346 |
import re
import json
def init_app(app):
"""Initialize Flask_Login LoginManager with our app"""
login_module = get_login_module()
if not login_module:
return
login_manager = flask_login.LoginManager()
login_manager.init_app(app)
# login_manager.session_protection = 'strong'
# pylint: disable=unuse... | 964d561606ca1b5acb2e02392016e50f52fb3f1e | 56,347 |
def other(path=''):
"""a test one with the other login type"""
logged,session = check_logged_in()
print('logged',logged)
print('session',session)
if not logged:
redirect(utils.join('/_login/other',path))
# NOTE: You need to set the redirect to /_login/<route>/ to work around
... | 6cde4f25fd8e3f9a2f93e7f7d1d6be02e211d32b | 56,348 |
def get_hole_degree_radius_w(candidate, circles):
"""Calculate the hole degree of a candidate circle.
Args:
candidate: candidate circle.
circles: sequence of circles.
Returns:
Squared euclidian distance of the candidate to the circles in argument.
Each component of the dist... | 5c705873ac1ab5160444adeb1022c0efd11f43c3 | 56,349 |
from typing import List
from typing import Tuple
def get_pools_with_description() -> List[Tuple[str, str]]:
"""
:return: List of Tuples containing pool name and description
"""
return [(pool, get_description(pool)) for pool in available_word_pools()] | bb4d222340dacbf07b0cee57acda97c62c14f06c | 56,350 |
import os
from pathlib import Path
def pyflowline_create_template_configuration_file(sFilename_json, \
sWorkspace_input, sWorkspace_output, iFlag_standalone_in=None, \
iFlag_use_mesh_dem_in=None, iCase_index_in=None, dResolution_degree_in = None, dResolution_meter_in = None, sDate_in = None, sMesh_ty... | e8338a5935afa63cc0e1bff9897595a58f5f01e2 | 56,351 |
def _tri_coordinates_y(words):
""" gives us a list of ocr points [[top, center, bottom], ...]"""
return [(cord[1], center[1], cord[3])
for center, cord in zip(
image_utils.get_centroids_from_coords([word['coords'] for word in words]),
[word['coords'] for word in words]
... | aa14a2f185f564e6537859a14c33f46bb7687aaf | 56,352 |
def get_horse(id):
"""
Gets information for a specific horse
:param id: Identifier of the horse
:type id: str
:rtype: Horse
"""
horse = Data.get('horse', id)
if horse is None:
return 'Horse Not Found', 404
else:
return Horse.from_dict(horse) | b9d6c14090f1b12909946c3511f58651864ed17c | 56,353 |
import subprocess
import logging
import os
import sys
import signal
def execute_shell(cmd, input='', timeout=None) -> (int, str, str):
"""
:param cmd:
:param input: sent to stdin
:return: returncode, stdout, stderr.
:raise: subprocess.TimeoutExpired (I kill the process!)
"""
proc_stdin = ... | e791ce59b62f28256b49fd7ac8b3bd3d2ae1f2bd | 56,354 |
def fix_rpath(file_path, old_rpath_list, new_libdir):
""" Fix RPath """
to_recheck = 0
cmd = ["install_name_tool"]
for old_rpath in old_rpath_list:
lib_file = os.path.basename(old_rpath)
lib_path = os.path.join(new_libdir, lib_file)
if not os.path.exists(lib_path):
pr... | faf96c6802a4a58dd110a67bc3f70b5bf89f2112 | 56,355 |
import time
def zr_total_dem():
"""
Real Name: b'zr total dem'
Original Eqn: b'(zr agri dem *agri zr dam coef)+(zr agri dev dem (Time)*agri zr dev coef)+zr dom dem\\\\ (Time)+zr Env dem (Time)+zr Ind (Time)+Zr wr dem (Time)'
Units: b'MCM/Month'
Limits: (None, None)
Type: component
b'(Zr A... | 4042f494d98902178357b5b07325db70a58aa9b6 | 56,356 |
from typing import Iterable
def _load(
database_connection_url: str, controllers: Iterable[CRUDController], **kwargs
):
"""
Create all necessary tables and perform the link between models and underlying database connection.
:param database_connection_url: URL formatted as a standard database connecti... | e26e749d827aa041b5d86c9d16faa4f8b9395476 | 56,357 |
def split_set_by_point(coord_array, point):
"""
point_array : array of Coord
point : Coord
Return the array of the points on the left and the right of the point
"""
left = []
right = []
for coord in set(coord_array):
if coord.x < point.x or coord.y < point.y:
left.app... | 6a7ee4387f2bc74fcf06262bc4262351c66b3a1c | 56,358 |
def ldns_resolver_new():
"""LDNS buffer."""
return _ldns.ldns_resolver_new() | 5d6cf276dc77c60c299016c6d215e012973b2a27 | 56,359 |
def replace_group_with_whitespace(match_obj):
"""
:type match_obj: MatchObject
"""
match_start, match_stop = match_obj.span(1)
overall_start, overall_stop = match_obj.span(0)
start_offset = match_start - overall_start
stop_offset = (match_stop-match_start) + start_offset
new_str = '{}... | 93a0328f1e3afae13422d2bbca12d9052f9bfb65 | 56,360 |
def register(ref_img, in_img, cmd=None):
"""Find the 4D affine transform that registers in_img to ref_img
Args:
ref_img -- (type: ndarray) reference image
in_img -- (type: ndarray) input image to be registered
cmd -- (default: None) override default flirt parameters
... | b7f423a24848efbc4f6ca092541c8bd2e04581be | 56,361 |
import numpy
def circle_vs_circle(m):
"""
Process two circles that collide.
"""
n = numpy.subtract(m.b.position.data, m.a.position.data)
r = m.a.radius + m.b.radius
r *= r
if r < (m.a.x - m.b.x) ** 2 + (m.a.y - m.b.y) ** 2:
return False
d = distanceA(m.a.position.data, m.b.po... | 7fd8cd49943c57e2c432ba816896a4d744fa79e3 | 56,362 |
from sys import path
import tqdm
def run(
web_file_path: str, local_path: str = "", humansize: str = "1MB", threads: int = 5
) -> bool:
"""
mdownload
Download file from target system by block compression and multi threads.
eg: mdownload {web_file_path} {local_path=doughnuts/target/site.com/...} ... | 48f5e4374882f591ae408372632f6ed7b43b9ebb | 56,363 |
def get_or_create_family(family):
"""
Return a models.Family object corresponding to the given
Family object. If the given Family has no database id, it will
added to the database; otherwise, the existing item is fetched.
"""
if family is None:
return None
elif family._id is not Non... | f2cd0b1bebe1789590abfebe3d8e94b37e5987f1 | 56,364 |
def generate_repr_code(repr, node, fields):
"""
The CPython implementation is just:
['return self.__class__.__qualname__ + f"(' +
', '.join([f"{f.name}={{self.{f.name}!r}}"
for f in fields]) +
')"'],
The only notable difference h... | 79b374d013d4bbffe8f2c78d94542f9ff5633b43 | 56,365 |
def get_model_time_series(station, fnames, grid_B, mesh_mask, nemo_36=True):
"""Retrieve the density, salinity and temperature time series at a station.
Time series is created from files listed in fnames"""
if nemo_36:
depth_var = 'gdept_0'
depth_var_w = 'gdepw_0'
else:
depth_var... | 5ef35e08c6b713f354b0a8e0640b6073719f239a | 56,366 |
from typing import List
def parse_header(header_string: str, sep: str = ' ') -> List:
"""Parses header data.
Args:
header_string: A string containing header items.
sep: A string containing a delimiter.
Returns:
A list of header items.
"""
header = header_string.strip().s... | b6b31de74d5d3e47695c1e014d5803de2bc6a952 | 56,367 |
def Import_MultiLith_output(mr_raw,dX=0.0001,MajorElements=pd.Series([7.48,8.51],index=['MgO','FeO']),WalterComps=False):
"""Import a 1D melting region object generated by the MultiLith code. Must have been
integrated already.
Returns a pandas dataframe.
Parameters
----------
filename: string... | 33454b0ad3c8a55595cee960ca2628b5b4e0649b | 56,368 |
def listPipelines():
# type: () -> List[String]
"""Will return a list of the available Alarm Notification Pipelines.
Returns:
A list of pipeline names. The list may be empty if no pipelines
exist. Unsaved name changes will not be reflected in the list.
"""
return [] | 929b95bb190f41dc0293443839fcbf9fa82d10b8 | 56,369 |
def calc_rf_ch4(m_0, m_curr, m_bar, n_bar):
"""
Calculate the radiative forcing for CH4 (methane)
Parameters
----------
m_0 : float
Initial ch4 concentration, in ppb
m_curr : float
Current ch4 concentration, in ppb
m_bar : float
Averaged ch4 concentration, in W m... | 6efa23428244d7663568eb453bad1bb325bb9de2 | 56,370 |
def offset(freqs, re0, im0):
"""Complex offset re + j*im.
Freqs vector is ignored, but required for lmfit Model."""
return re0 + 1j * im0 | ae2b373806dee6e50fb61c4945b99f7ef7c9a6f7 | 56,371 |
def build_relative_position(query_size, key_size, bucket_size=-1, max_position=-1):
"""
Build relative position according to the query and key
We assume the absolute position of query \\(P_q\\) is range from (0, query_size) and the absolute position of key
\\(P_k\\) is range from (0, key_size), The rel... | ef4cfc800da617f39c7f2271c2a43f03ef1077d6 | 56,372 |
def implied_volatility_from_a_transformed_rational_guess(price, F, K, T, q):
"""
:param price:
:type price: float
:param F:
:type F: float
:param K:
:type K: float
:param T:
:type T: float
:param q:
:type q: float
:return:
:rtype: float
"""
return implied_vo... | aaf78c637ec7624033ac2594cf52eb4987ad0380 | 56,373 |
def is_kanji(input: str = "") -> bool:
"""Tests if `input` is Kanji (Japanese CJK Ideographs)"""
return (not is_empty(input)) and all(is_char_kanji(char) for char in input) | b43acac43e761afc8d5d02752d23fc0fc3aadb8e | 56,374 |
def after_request(response):
"""Modifies the response object prior to sending it to the client. Used to add CORS headers to the request
Args:
response (response): Flask response object
Returns:
`None`
"""
response.headers.add('Access-Control-Allow-Origin', '*')
response.headers... | 96bf051001b0f9eb4a31f2ce101a23bae39c49c9 | 56,375 |
import re
def split_camel_cased(text):
"""
Split camelCased elements with a space.
:param text: the text to be converted processed.
:type: str
:return: text with all camelCased elements split into different elements
:type: str
"""
return re.sub('(?!^)([A-Z][a-z]+)', r' \1', text) | 6de55ed7d8fc4bc06e0d16d4b327999ad656ceac | 56,376 |
from typing import OrderedDict
def _generate_bufferizers_and_unbufferizers():
"""Generate bufferizers, forced full bufferizers and unbufferizers,
by registering native and torch types, syft objects with custom
bufferize and unbufferize methods, or syft objects with custom
force_bufferize and force_unb... | 895fc30e203c7bbd2f5ec5c28089a3b4e4afc408 | 56,377 |
def div(X,varX, Y,varY):
"""Division with error propagation"""
# Direct algorithm:
# Z = X/Y
# varZ = (varX/X**2 + varY/Y**2) * Z**2
# = (varX + varY * Z**2) / Y**2
# Indirect algorithm to minimize intermediates
Z = X/Y # truediv => Z is a float
varZ = Z**2 # Z is a floa... | 3cdb59a752ef0759f0411cd7d478a3dac204f65f | 56,378 |
def create_information_dict(key):
"""Create a dictionary with the familiar information from the key."""
info = {}
stream = BitStream(bytearray(key))
BRANDS = ('sun', 'moon', 'star', 'planet', 'twin_sun', 'twin_moon',
'twin_star', 'twin_planet')
info["name"] = stream.read('str', 4)
... | 9b2070e8d75cb746850b670c33510ace08e9f027 | 56,379 |
import logging
import requests
def download_remote_sitemap(sitemap_url, session):
"""Download the sitemap of the target website."""
logging.debug("Downloading: %s", sitemap_url)
r = session.get(sitemap_url)
try:
# Raise `requests.exceptions.HTTPError` if 4XX or 5XX status
r.raise_for_s... | 38503cc925cc41aa0f5bbe7f4c0ec5da1a8acca5 | 56,380 |
from bs4 import BeautifulSoup
def get_word_meaning(response, xth):
"""
Parse a HTML document and get a text of xth meaning
from particular tags
By default, xth = 1
"""
dom = BeautifulSoup(response.content, "lxml")
div_element = dom.select_one(".word_num") or None
word_meaning = ""
... | ed19d0d13980541cc89d945b83c5866ca0d7ecb1 | 56,381 |
def finish_job(client, cleanup_job, job_completed_normally, client_outputs, lwr_outputs):
""" Responsible for downloading results from remote server and cleaning up
LWR staging directory (if needed.)
"""
collection_failure_exceptions = []
if job_completed_normally:
output_collector = ClientO... | b6de3e1bd5934b222f91bf11c8bf250c5bfc7620 | 56,382 |
def api_resource(route, method, schema=None):
"""TODO: Docstring for api_resource.
:route: TODO
:method: TODO
:schema: TODO
:returns: TODO
"""
route = config.API_ROOT + route
validator = None
if schema:
validator = cerberus.Validator(schema, purge_unknown=True)
def wrap... | 67fcc41ce240fd74572e0336ecfd077e76151811 | 56,383 |
def get_dict_from_namespace_object(args):
"""Unwrap the namespace object to pull out a dict of values"""
return vars(args) | e1c34c1faff71ae330a44d91a399260fbdc454c6 | 56,384 |
import os
import time
from datetime import datetime
def _is_valid_cache():
"""
Returns if the cache is valid (exists and modified within the interval).
:return: Whether the cache is valid.
:rtype: ``bool``
"""
if not os.path.exists(get_cache_location()):
return False
modified = os.... | 04c95080eca23de84b1a0ccf25758a9d49691461 | 56,385 |
import logging
def check_directory(dir_path, function, *args, **kwargs):
"""Given a directory and a function with a True/False return value,
applies it to all files in directory keeping track of results """
logger = logging.getLogger(__name__)
logger.debug(f"{check_directory.__name__} : Called with '{... | 7c25fcdd3c647faec8e562366a45ab1663349f00 | 56,386 |
import os
def linking_public_product(flist, logger):
"""
link public products to a public Collection
"""
# print("I'm in "+sys._getframe().f_code.co_name)
not_reg = []
for elem in flist:
file_found = findfile(elem+'*', '/mnt/data/aeolus/L1B_L2_Products')
if file_found:
... | 4dd6f902fab59f3ea14b3aa71bc1015a47d4e045 | 56,387 |
import math
import tqdm
import os
import subprocess
def do_work(collection_name, log_verbose, slurm=True, num_exps=-1, slurm_config=None, filter_dict=None):
"""Pull queued experiments from the database and run them.
Parameters
----------
collection_name: str
Name of the collection in the Mong... | 1c84c64b3e1c499a6d2b9af86c15ff3980c28f5c | 56,388 |
from typing import Optional
from typing import Union
from typing import Tuple
def add2d(
x: Tensor,
weight: Tensor,
bias: Optional[Tensor] = None,
stride: Union[int, Tuple[int, int]] = 1,
padding: Union[int, Tuple[int, int]] = 0,
dilation: Union[int, Tuple[int, int]] = 1,
groups: int = 1,
... | ceb7a47170e246326abf089b450a49cfeb718df4 | 56,389 |
def norm3(vec):
""" Third norm """
return builtinnorm(vec) | 2a4513bd2ee3fa138405b56331a3a2a4e5d883aa | 56,390 |
def get_tuple(string, n, as_int = False):
"""
Splits a string into n tuples, ignoring the rest if there are more, and replicating
if there is only one
@param string The string
@param n The number of elements
@param as_int If true, it will cast to int
"""
t = string.split(",")
if len(t) == ... | 59b339c561bccc428f4e2882c369a7dcda86aaff | 56,391 |
def report_func(trnr, epoch, batch, num_batches, start_time, lr, report_stats, enc_output_dict, dec_output_dict, mem_dict):
"""
This is the user-defined batch-level traing progress
report function.
Args:
epoch(int): current epoch count.
batch(int): current batch count.
num_batch... | 4a7a5d9b72e8de759be2ab63be682bdcc5fc4f24 | 56,392 |
def print_filenames_option(dflt=True, **kwargs):
"""Option to tell if filenames should be in the title"""
return bool_option(
"show-fn", "P", "If set, show filenames in title", dflt, **kwargs
) | e9619767a1b43b3dfdf2529ed6eb1ce001ed6ff3 | 56,393 |
def get_qdevice(
run_type: str, wires: int, backend_name: str, config: dict
) -> pnl.device:
"""
Configure a pennylane quantum device object used to construct qnodes.
Args:
run_type: Specifies the mode to run the (hybrid) VQC training: Ideal,
noisy simulation or on real quantu... | 76fa86234e50d9e959ec5e6f5c863cdcacb18ca5 | 56,394 |
def xy_rot(x, y, ang):
"""Rotate (x,y) positions to new coords
Rotate (x,y) values by some angle.
Positive ang values rotate counter-clockwise.
Parameters
-----------
x : float or array
X location values
y : float or array
Y location values
ang : float or arra... | f6d60766d72e259dec0d4803e2a57d3fd650d66c | 56,395 |
from comtypes.automation import VARIANT
def _is_object(obj):
"""This function determines if the argument is a COM object. It
is used in several places to determine whether propputref or
propput setters have to be used."""
# A COM pointer is an 'Object'
if isinstance(obj, POINTER(IUnknown)):
... | a537a4286635c11f63f69e27fd3ad986704586ca | 56,396 |
def ParseDupHit(text):#{{{
"""
Parse a duplication hit
e.g.
1-575(nTM=2) 2-571(nTM=2)
"""
li = []
strs = text.split()
for ss in strs:
strs1 = ss.rstrip(')').split('(nTM=') # ['35-345', '7']
li1 = [int(x) for x in strs1[0].split('-')]
li1.append(int(strs1[1])) #... | d488076fcaf581376730bb404090d16c99137baa | 56,397 |
def timedeltas(
min_value: dt.timedelta = dt.timedelta.min,
max_value: dt.timedelta = dt.timedelta.max,
) -> SearchStrategy[dt.timedelta]:
"""timedeltas(min_value=datetime.timedelta.min, max_value=datetime.timedelta.max)
A strategy for timedeltas between ``min_value`` and ``max_value``.
Examples f... | 4d9820ada721d1998d39ccd0ae7dcd4b01d685ce | 56,398 |
def discover_flm():
"""
Scan your local network for the address of your FLM
Returns
-------
str
"""
zeroconf = Zeroconf()
listener = _MyListener()
browser = ServiceBrowser(zeroconf, "_mqtt._tcp.local.", listener)
for _ in range(100):
if _flm is None:
sleep(1)... | 33f986675d40e0a8d800db4decfb50070ae4eb9e | 56,399 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.