content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def _get_rnn_cell(mode, num_layers, input_size, hidden_size,
dropout, weight_dropout,
var_drop_in, var_drop_state, var_drop_out,
skip_connection, proj_size=None, cell_clip=None, proj_clip=None):
"""create rnn cell given specs
Parameters
----------
m... | 05e17f105a847a07bfd8ffae2c704606d8ce3f56 | 58,900 |
def parametrize_tir(cashflows,
days_to_flows,
day_count_base=365):
"""
Return the function for a net present value with a discount rate as the only variable for a set of time-determined cashflows.
Defines a function using a particular trick found at stackov... | b44a51da1df3fa68681d3febb98fe2b857cf173c | 58,901 |
def fn_init(Kernel, Ker_weights, range, device):
"""
this function simply set the args for our main 'fn' function.
"""
def fn_with_specified_args(inputs, val):
return rkhs_fn(inputs, val, Kernel, Ker_weights, range, device)
return fn_with_specified_args | ce0e8b21b0d4f9f03a74009ef344e22ca5f3466d | 58,902 |
def show(tr: TraceLike, fix_width=False):
"""show a trace"""
get_value = lambda v: v if isinstance(v, Tensor) else v.value
ten_show = lambda v: tensor_utils.show(get_value(v), fix_width=fix_width)
return "{" + "; ".join([f"'{k}'-➢{ten_show(v)}" for k, v in tr.items()]) + "}" | f5e4ed26b57e978a4dc8047821a4f4ea97216862 | 58,903 |
def describeTreeProductions(tree, links, offset=0):
"""
Write out the PCFG node productions
"""
s = "%s ->" % tree.node
for ch in tree:
s += " %s" % ch.node
return s | 8f0ec7db35316684441863c8475b6089da0c7e98 | 58,904 |
def orlib_load_instance(instance_name, reader, formulation):
"""
Parameters
----------
instance_name: str
Name of instance file
reader: function (file) -> params: tuple
Takes a file-like object and returns the read parameters
formulation: function (params: tuple) -> scip.model
... | aad7d6c2bc0a67e351946ba87e71ca31613f71db | 58,905 |
from re import T
def correlation(i, kn=4, kp=4):
"""Feature selection based on pairwise correlation
Args:
i (int): index of the country we are modeling
tao (float): critical value (default = 0.4)
Returns:
JH (array): An array with the regressors (incl. self)
"""
corr_i = ... | e6cb33bed38dd12ec06d1266ecde52485ada7541 | 58,906 |
def bumped(repo, subset, x):
"""``bumped()``
Mutable changesets marked as successors of public changesets.
Only non-public and non-obsolete changesets can be `bumped`.
"""
# i18n: "bumped" is a keyword
getargs(x, 0, 0, _("bumped takes no arguments"))
bumped = obsmod.getrevs(repo, 'bumped')
... | 80b2bce462d7feb6815741ecf68b0c2196899d55 | 58,907 |
def discovery_info_from_headers_and_request(
info_with_req: CaseInsensitiveDict,
) -> dict[str, str]:
"""Convert headers and description to discovery_info."""
info = {DISCOVERY_MAPPING.get(k.lower(), k): v for k, v in info_with_req.items()}
if ATTR_UPNP_UDN not in info and ATTR_SSDP_USN in info:
... | fbe8f135c032615b27e84a06f56562266b85b86f | 58,908 |
def findH(g_h, cs, Q, S, rh):
"""
Calculates discharge difference for a given height of water.
The minimum of this function is the height of water with a prescribed
discharge.
Parameters
----------
g_h : guess height [m]
cs : cross-section
Q : discharge [m^3/s]
S : slope
rh : roughness height (z_0) [m]
Re... | 692ee492334c467f0dfb2a5438710e5594438106 | 58,909 |
def nextditem(s):
"""Tries to guess the next item on the sequence 's' by using a table of
divisions. This method will fail if the sequence doesn't provide
enough information, and will assume that the latest sequence should
remain constant"""
ds = getdivs(s)
r = ds[-1][-1]
for i in r... | 12f2208e493f8de1bfaec053d54c725306e480aa | 58,910 |
import os
import shutil
def import_petab_problem(
petab_problem: petab.Problem,
model_output_dir: str = None,
model_name: str = None,
force_compile: bool = False,
**kwargs) -> 'amici.Model':
"""
Import model from petab problem.
:param petab_problem:
A petab... | 26f03cc73cec410735ca1a8fe4b6053a0fc735f0 | 58,911 |
import subprocess
import os
def determineRevision(dir_path):
"""
Determine the revision of the given directory in a version control system.
"""
# Check for SVN repository
try:
svnProcess = subprocess.Popen(
["svnversion", "--committed", dir_path],
env={"LANG": "C"},... | 26dff39d5c80b56d914235c1036bcdcccae1a207 | 58,912 |
from typing import Optional
import itertools
def ensure_sequence_of_iterables(obj, length: Optional[int] = None):
"""Ensure that ``obj`` behaves like a (nested) sequence of iterables.
If length is provided and the object is already a sequence of iterables,
a ValueError will be raised if ``len(obj) != len... | b073c6a287d5068fd292ee969bac6725aed4747d | 58,913 |
def eval_shift_distance(shift, reg_matches):
"""
Compute the distance in characters a match has been shifted over.
"reg_matches" is the set of regular matches as returned by find_regular_matches().
The distance is defined as the number of characters between the shifted match
and the closest regula... | aceb705d0f89cacb6f7738667e6dfaf803bed85c | 58,914 |
import unittest
def require_tf(test_case):
"""
Decorator marking a test that requires TensorFlow, graphviz and pydot.
These tests are skipped when TensorFlow, graphviz and pydot are installed.
"""
if not is_tf_available() or not is_pydot_available() or not is_graphviz_available():
return... | df3dac459eba4d6350cb292085ae4e69d2baef9e | 58,915 |
from re import DEBUG
import time
import os
def write_line(raw_line, inverter_addr, discovery):
"""Parse the values returned by the inverter and write them to file"""
# Find the start token
start_index = raw_line.find('*')
if start_index == -1:
if DEBUG:
print("Could not find the st... | b96dd44ccdd550b0177c11babed6051d0164a308 | 58,916 |
def get_common_basename(paths):
""" Return common "basename" (or "suffix"; is the last component of path)
in list "paths". Or return None if all elements in paths do not share a common last
component. Generate an error if any path ends with a slash."""
if len(paths) == 0:
return None
# get... | e2189244ef556038caea24ba6aa85792f34868db | 58,917 |
def get_recent_safe_block(time, sta, chan, margin_seconds=10, preferred_len_seconds=120, min_len_seconds=60, arrival_window_seconds=1200):
""" Get a block of time preceding the specified time, and ending at least margin_seconds before that time, for which waveform data exists, and during which there are no recorded... | c7aa93b7c978f90d19baca20a16f0a32a8dad16d | 58,918 |
def f_punct(w_list):
"""
:param w_list: word list to be processed
:return: w_list with punct and number filter out
"""
return [word for word in w_list if word.isalpha()] | 7cf7c4b812fffa6b7c77a96b53995366519232c5 | 58,919 |
from typing import Optional
from typing import Union
from typing import Tuple
import torch
def max_mpc(
x: MPCTensor,
dim: Optional[Union[int, Tuple[int]]] = None,
keepdim=False,
) -> Union[MPCTensor, Tuple[MPCTensor, MPCTensor]]:
"""Compute the maximum value for an MPCTensor.
Args:
x (MP... | 278bfd975ca816712c0cf4f80c91d577c14abe8b | 58,920 |
def even(n: int) -> bool:
"""
Check that given number is even.
>>> [(n, even(n)) for n in range(5)]
[(0, True), (1, False), (2, True), (3, False), (4, True)]
"""
return n % 2 == 0 | b96403b1b250560b29aafc253aaa1883f4018002 | 58,921 |
def is_owner(org):
"""
Function for checking if a user's org has ownership rights
SINCE WE ARE KEEPING ACCESS CONTROL SIMPLE, WE ARE DEFAULTING THIS TO TRUE
:param str org: An organization
:return bool: whether the organization matches the current user or the group of admins
"""
return True
... | ba326c4524cd30038e5a8a1f88aa6b8f80b9a57f | 58,922 |
import sys
import logging
import traceback
def main():
"""
Entry point for command 'impact-vastart'.
"""
args = parser.parse_args(sys.argv[2:])
if args.verbosity == 1:
logging.getLogger().setLevel(logging.INFO)
elif args.verbosity > 1:
logging.getLogger().setLevel(logging.DEBU... | 294e0de22f28625983f6cace0f93cf18cb4ffe93 | 58,923 |
import argparse
def set_args():
"""设置训练模型所需参数"""
parser = argparse.ArgumentParser()
parser.add_argument('--device', default='0', type=str, help='')
parser.add_argument('--train_file_path', default='task_data/train_defect_diagnosis.json', type=str, help='')
parser.add_argument('--dev_file_path', de... | 0201e6c575d79fcf785ccfa8c15e442261b30f5d | 58,924 |
def linear_model_loss_regularized_dx_lp(w, x, y, reg_coeff, norm_type):
"""Penalize by ||dL/dx||."""
loss_and_dloss_dx_f = jax.value_and_grad(linear_model_loss, argnums=1)
loss, dloss_dx = loss_and_dloss_dx_f(w, x, y)
reg = norm_f(dloss_dx, norm_type)
return loss + reg_coeff * reg | c307eca6bec9d8788937a46301d0ed729b31ffe0 | 58,925 |
def cross_covariance(y, ym, z, zm, b):
"""
Computes the cross-covariance matrix between the rows of matrix `y` with those of matrix
`z`. The method of Overlap Batch Mean (OBM) is employed with blocks of size `b`.
"""
Sy = _SumOfDeviationsPerBlock(y, ym, b)
Sz = _SumOfDeviationsPerBlock(z, zm, b... | 35ea390be9aff91e5b2531dbba3087b9044beef7 | 58,926 |
import requests
def get_facilities_from_ridb(latitude: float, longitude: float, radius: int):
"""
Calls RIDB API with a location and search radius, and returns campground names and RDIB
facility ID strings.
:param latitude: Latitude of coordinate to center the search around
:param longitude: Long... | c3c52c0ba9dc2caa1986a0d410726b1f01957e6e | 58,927 |
def api_get_logs(log_type, num_lines):
"""API to return the logs of appropriate type and logging window based on
user selection.
Args:
log_type (str): Log type attribute name pointing to the log file location.
Defined in the constants file.
num_lines (int): Number... | 35eb306cbc0ec74e72b3298f7e1473711c1cb9da | 58,928 |
import sys
import re
def collect_local_modules(module_name, hooks_module='.hooks'):
"""collect_local_modules."""
if getattr(sys, 'frozen', False) or not IS_DEBUG:
return
def is_invaild_module_name(name):
return not is_string(name) or \
re.match(r'^(\.[a-zA-Z0-9_-]{1,}){1,}$',... | 4199a596efc551fc4282d5bdc4e42dc40a7cfb60 | 58,929 |
import random
def sample_contact_points(contact_points, num_samples, get_idx=False):
"""Sampling contact points for the specified number
Parameters
----------
contact_points : list[list[list[float], list[float]]]
num_samples : int
Returns
-------
contact_points : list[list[list[float... | 688d45a3653dae0ebb2a9261ced47684645d3d2d | 58,930 |
import logging
def get_messages_from_folder(folder, message_id, **kwargs):
"""Return list of messages matching message id in the given folder."""
_logger = kwargs.get("logger") or logging
message_id = check_message_id_format(message_id)
# We want to use filter WITHOUT conditional QuerySet queries... ... | 485e56e658d66f9bea3b8afca7862d9fe916f737 | 58,931 |
def IsUUID(uuid: str) -> bool:
"""Verifies a string has the following valid RFC UUID format:
'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx'.
Args:
uuid (str):
value that needs to be verified.
Return:
(boolean): true or false to if the value is valid.
"""
if len(uuid) ... | d6f948115076b8b995ce2c2d25015f875e254bf1 | 58,932 |
from astropy.io import fits
def ref_from_image(input_image, reffile_lookup):
"""
Return a list of reference filenames, as defined in the primary
header of the given input image, necessary for calibration.
Parameters
----------
input_image : str
FITS image to extract info from.
re... | 2e1898b47a1a41580e8fcb975963837d2a954a91 | 58,933 |
def shufflelr(x, width, dataset='mpii'):
"""
flip coords
"""
if dataset == 'mpii':
matchedParts = (
[0,5], [1,4], [2,3],
[10,15], [11,14], [12,13]
)
elif dataset == 'h36m':
matchedParts = (
[1,4], [2,5], [3,6],
[11,14], ... | 869e255230b9d0b56c070d2e4e9ac8257cab4842 | 58,934 |
def _compute_hal9000_md5(observable: Observable) -> str:
"""Given an Observable, return the hexdigest of the MD5 computation used for hal9000."""
md5_hasher = md5()
md5_hasher.update(observable.type.encode('utf-8', errors='ignore'))
md5_hasher.update(observable.value.encode('utf-8', errors='ignore'))
... | 4b9c84e792a6ddda2e36a659612d08d8c8041e40 | 58,935 |
import json
def get_context():
""" Retreive the URL parameters from the current request context """
args = request.args
int_or_none = lambda x: int(x) if x is not None else None
dict_or_none = lambda x: json.loads(x) if x is not None else None
try:
context = RequestContext(
i... | a72c921943da281aefda1bd8ebd8c0d56ad7643f | 58,936 |
def log_decoding_CanonLog3(
clog3: FloatingOrArrayLike,
bit_depth: Integer = 10,
in_normalised_code_value: Boolean = True,
out_reflection: Boolean = True,
) -> FloatingOrNDArray:
"""
Defines the *Canon Log 3* log decoding curve / electro-optical transfer
function.
Parameters
-------... | 66a1dffa9fe25763b1cefd15a6eb76c91d65f338 | 58,937 |
def line_intersection(A, B, C, D):
"""Assumes line segments AB vs. CD actually cross (must determine this
separately), where points A - D have fields 'x' and 'y' e.g. a Point2D
object.
Uses algorithm from:
http://www.bryceboe.com/2006/10/23/line-segment-intersection-algorithm/
and
http://pa... | 992996c805fe8623f50181dd265509cfd6b5ade8 | 58,938 |
def get_project_list_from_layout(request, layout_id):
""" Return project ids, names and get-branch-list url """
if request.method != 'GET':
return res.get_only_get_allowed({})
layout = BluesteelLayoutEntry.objects.filter(id=layout_id).first()
if layout is None:
return res.get_response(4... | 8fa4c3c63fa117f16eb800b214cddfb50662637e | 58,939 |
def percent_yield(actual_yield, theoretical_yield):
"""Finds theoretical_yield\n
actual_yield:\n\tThe yield given in the equation\n
theoretical_yield:\n\tThis yield can be calculated with the theoretical_yield() function"""
yielded = (actual_yield / theoretical_yield) * 100
return yielded | ceef481ebae8be223bdb9b9c1f2c8a0c8713fcca | 58,940 |
def name_propagation_inside_basic_block(ctx: FrozenBuildContext, instructions: list[Instruction]) -> tuple[list[Instruction], bool]:
"""
```
x = L.message1
M.print_flush(y)
```
⇓
```
M.print_flush(L.message1)
```
"""
basic_blocks, _cfg = _make_control_flow_graph(instructions)... | e7f9cf1c5ec66a00f64e681bdb58d5e6c16f861a | 58,941 |
def is_na(value):
"""
Return True if value is None or NaN
"""
return value is None or is_nan(value) | 90e23e7aeea018dc69f11e97fd4ae290ddb7d282 | 58,942 |
def url_auth_split(url):
"""extract authentication information from the given URL
>>> url_auth_split('/path/to.git') == ('file:///path/to.git', None, None)
True
>>> result = ('ssh://git.example.com:2222/path/to.git', None, None)
>>> url_auth_split('ssh://git.example.com:2222/path/to.git') == result... | d9bf66bbff7f09556509b9580e510204f903964c | 58,943 |
def read_block(f, offset, length, delimiter=None):
""" Read a block of bytes from a file
Parameters
----------
fn: string
Path to filename on HDFS
offset: int
Byte offset to start read
length: int
Number of bytes to read
delimiter: bytes (optional)
Ensure rea... | 739197fc090a05c7bfcdccd5e71bf3bc2dcc0814 | 58,944 |
from typing import Union
import os
from pathlib import Path
def make_db_path(in_path: Union[str, os.PathLike, Path]) -> str:
"""
Returns the provided path resolved and as a String so APSW can understand it.
Peewee (or APSW) seems to not follow the `os.PathLike`-Protocol.
Args:
in_path (Union... | 9b34f8cc5de51d5b115b7829463e08465fcaeb62 | 58,945 |
import subprocess
def subprocess_cmd(cmd):
"""execute a subprocess
@param cmd: command to be executed
@type cmd: string
@return: result of the command
@rtype : string
@raise e: None
"""
try:
process = subprocess.Popen(cmd, stdout=subprocess.PIPE, shell=True)
pr... | 938417bb288de3720058da674038c0320c1e9021 | 58,946 |
def iou_from_mask(pred, gt):
"""
Compute intersection over the union.
Args:
pred: Predicted mask
gt: Ground truth mask
"""
pred = pred.astype(np.bool)
gt = gt.astype(np.bool)
true_negatives = np.count_nonzero(np.logical_and(np.logical_not(gt), np.logical_not(pred)))
fals... | ca8ba563a26fb150d9d12035c8ac0689b5035739 | 58,947 |
def md5file(filename):
"""
Re-implementation of md5sum in python. Return the hex digest of a file
without loading it all into memory.
By Nick Craig-Wood <nick@craig-wood.com>
"""
fh = open(filename)
digest = md5.new()
while 1:
buf = fh.read(4096)
if buf == "":
... | 8fd464a1d6bb3625764a06eb23a66d5223f63e58 | 58,948 |
def contains_all_required_firewalls(firewall, topology):
"""
Check that the list of firewall settings contains all necessary firewall settings
"""
for src, row in enumerate(topology):
for dest, col in enumerate(row):
if src == dest:
continue
if col == 1 an... | a4dbbb5833909e816c5b7568cf75da68c06d9e4c | 58,949 |
def truncation(parent_population, child_population, parents_scores,
children_scores, elitism_rate):
"""Selects next generation using elitism truncation selection for
single objective.
This function implements truncation selection while ensuring elitism
to select a specific number of memb... | 373ca6ad168a606995cf3c78cd8732c37642abfd | 58,950 |
def locations__search(request):
"""
Renders the locations page, after a search has been made.
Behaviour will vary, depending on the number of results, if there are errors...
"""
context = {'from_search': True, 'geolocation': request.session.get('geolocation'),
'location_error'... | 2a096dbc2da2d6756182b0df90e1dc4f852c7537 | 58,951 |
def latest_object_or_none(model_class, field_name=None):
"""Identical to Model.latest, except instead of throwing exceptions,
this returns None.
"""
try:
return model_class.objects.latest(field_name)
except (model_class.DoesNotExist, model_class.MultipleObjectsReturned):
return None | d71d6c6a58b7ba4d5a5ffe262353c56752bd486c | 58,952 |
def _get_upload_headers(first_byte, file_size, chunk_size):
"""Prepare the string for the POST request's headers."""
content_range = 'bytes ' + \
str(first_byte) + \
'-' + \
str(first_byte + chunk_size - 1) + \
'/' + \
str(file_size)
return {'Content-Range': content... | 3ccfec747ce8f8f31b97489005b1ac421f7c9024 | 58,953 |
from typing import List
def get_timers_matching_utterance(
utterance: str, timers: List[CountdownTimer], regex_path: str
) -> List[CountdownTimer]:
"""Match timers to an utterance that matched a timer intent."""
matcher = TimerMatcher(utterance, timers, regex_path)
matcher.match()
return matcher.... | cded1b8d7b41373cc03cc110902f7a8a09c89488 | 58,954 |
import logging
import uuid
def load_data():
"""
read mnist data from file
x (60000, 28, 28)
y (60000,)
split each record into leader_part and follower_part
and allocate example_id for each record
"""
logging.info("Load mnist_x.npy and mnist_y.npy")
x = np.load('mnist_x.npy')
y... | 9a3d46d276a883eb3270cc1a97caa250fcb77053 | 58,955 |
def dict_equal(dictionary, other_dictionary):
"""Compare two dict with :class:`numpy.ndarray` value handling.
Comparison is made in two parts:
* We first check that both dict have the same keys.
* If they do we then compare each value pair and lazily return ``False`` if any comparison fails.
Note:... | 043892e324d2a4e9893db79af97765c3f9f2e19f | 58,956 |
def get_Wiener(ase_obj):
"""
Example crystal structure descriptor:
https://en.wikipedia.org/wiki/Wiener_index
defined per a unit cell
"""
return np.sum(ase_obj.get_all_distances()) * 0.5 | 5a6d20990f84d0c907417f583a317e4d34f9cee4 | 58,957 |
import copy
def init_param_cont(args):
"""
init_param_cont(args)
Initializes parameter containers.
Returns args:
- in the following nametuples: analyspar, sesspar, stimpar, autocorr,
permpar, quantpar, roigrppar, tcurvpar
- in the following dic... | fa4f38d0a1da7f1ca51e4e1358ca12a05374f1f6 | 58,958 |
from typing import Optional
def _box_as_indexlike(
dt_array: ArrayLike, utc: Optional[bool] = None, name: Label = None
) -> Index:
"""
Properly boxes the ndarray of datetimes to DatetimeIndex
if it is possible or to generic Index instead
Parameters
----------
dt_array: 1-d array
A... | c7c84833b4135bb5f26d13954509b0c0f412e27f | 58,959 |
from typing import Iterable
import pandas
import numpy
def categorical_encode_series_to_sparse_csc_matrix(
series: Iterable, reduced_rank: bool = False
) -> spsparse.csc_matrix:
"""
Categorically encode (via dummy encoding) a `series` as a sparse matrix.
Args:
series: The iterable which shoul... | 75ccc95055ac091581c8b05f4cc5c92c27deef14 | 58,960 |
def setup_arg_parser():
"""
Sets up argument parser for python scripts.
Returns:
arg_parser (ArgumentParser): Argument parser updated with probabilistic detectron args.
"""
arg_parser = default_argument_parser()
arg_parser.add_argument(
"--dataset-dir",
type=str,
... | 52d3384b6cb853f841cfad7cf0c2755933488dae | 58,961 |
def SegmentConst_get_decorator_type_name():
"""SegmentConst_get_decorator_type_name() -> std::string"""
return _RMF.SegmentConst_get_decorator_type_name() | 1c357834fd4f0406616b8e46cb98c1f0957f5549 | 58,962 |
def write(sec):
"""Write MT section for MF5
Parameters
----------
sec : `sandy.utils.Section`
dictionary with MT section for MF5
Returns
-------
`str`
section content in a single string
"""
text = write_cont(sec["ZA"], sec["AWR"], 0, 0, len(sec["PDISTR"]), 0... | cb03c9dc5672d69f94921f58991c1f6259705a2b | 58,963 |
def emissions(run_start_year, run_end_year, dt, rcp, add_start = 0,
add_end = 0, c_add = 0, ch4_add = 0, n2o_add = 0):
"""
Take annual emissions from a RCP scenario and return
emissions by specified start date, end date, and time step
"""
run_years = run_end_year - run_start_year + 1 ... | 046ea1c9e154920b30b8436deb648d6ee66b626b | 58,964 |
def cv2_fn_wrapper(cv2_fn, mat, *args, **kwargs):
"""" A wrapper for cv2 functions
Data in channel first format are adjusted to channel last format for
cv2 functions
"""
mat_shape = mat.shape
x_size = mat_shape[-2]
y_size = mat_shape[-1]
_mat = mat.reshape((-1, x_size, y_size)... | 5ed5f1c40383d0fe0c0a6f6fd39f0d22616a8307 | 58,965 |
import os
def build_ipc_uri(service_id: str) -> str:
"""Build ipc uri for the given service."""
return f"ipc://{os.path.join(user_cache_dir('npc-engine'), service_id)}" | 71adc037ca99ebe536fa91219c84bf36ea41064d | 58,966 |
def initial_time():
"""
Real Name: INITIAL TIME
Original Eqn: 0
Units: Day
Limits: (None, None)
Type: constant
Subs: None
The initial time for the simulation.
"""
return 0 | 322f4472123f27400d507f8b4e7dc2262bd1c348 | 58,967 |
import shutil
def slay_the_weaker(dic, key, value):
"""Delete the less-up-to-date directory by the same name, if any.
Parameters:
dic -- Dictionary of absolute paths minus version numbers to
version numbers
key -- String representing the absolute path minus version number
... | e2acbf423c8c71f7c48ef8fbb96758b186a5f3ee | 58,968 |
def render_template(filename, **context):
""" Render mail template. Returns rendered text """
return jinja_env.get_template(filename).render(**context) | 8ab1e06b7626d5de06a6f814a40cc394cffe1469 | 58,969 |
from typing import Union
from operator import is_
def has_text(expected: Union[Matcher, str]):
"""
Test if ``WebElement`` instance has text.
:param expected: expected text
:return: ``Matcher`` instance
"""
return HasText(is_(expected)) | dfd9968f5ee16d80c6bf701922cc362960ad1208 | 58,970 |
def plot_hate_speech(
df: pd.DataFrame, title: str = None, height: int = 300, label_col: str = "label"
) -> Figure:
"""
Show the percentage of estimated hate speech sentences.
Args:
df (pd.DataFrame):
Dataframe with the outputs of a hate speech model.
title (str):
... | c6c3098a7b30e58722820a1eefbdfbec5ce46328 | 58,971 |
from typing import OrderedDict
def clean_weights(weights: OrderedDict, portfolio, first_prices, latest_prices):
"""Remove low weights as not significant contributors to portfolio performance"""
sum_of_weights = sum(map(lambda t: t[1], weights.items()))
assert sum_of_weights - 1.0 < 1e-6
cw = OrderedDi... | eb7cb0861852cb57e986e0bb8647026bd445287c | 58,972 |
import matplotlib.pyplot as plt
import numpy
import os
def run_convergence(setup, ref_list, do_export=False, save_plot=False, **options):
"""Runs test for a list of refinements and computes error convergence rate"""
l2_err = []
for r in ref_list:
l2_err.append(run(setup, r, do_export=do_export, **... | 45a8d7ea1120a824b5c73882bf586906e3946653 | 58,973 |
import matplotlib.pyplot as plt
def showContactMap(enm, *args, **kwargs):
"""Show Kirchhoff matrix using :func:`~matplotlib.pyplot.spy`."""
if not isinstance(enm, GNMBase):
raise TypeError('model argument must be an ENM instance')
kirchhoff = enm.getKirchhoff()
if kirchhoff is None:
L... | 5f70aabc7c7aee2595e8b9f864c32c03917f01a2 | 58,974 |
def helper_find_anagrams(s, n, anagrams_list):
"""
:param s: stands for the input word
:param n: n is a counter for the number of anagrams
:param anagrams_list: to collect all anagrams we want
:return: n, anagrams_list
"""
# first to get the list of each characters of the input word 's'
... | f379f8323c974f63096b25a21c181bf5aa5fb9c4 | 58,975 |
def get_metadata_values( file, metadata ):
"""
Gets metadata values from a file path.
:param file: The file path to search.
:param metadata: Metadata from the file name is turned into MultiIndex columns.
+ If list, use standard keywords to include in index [ 'sample' ]
+ If Dictionary, ... | b3d10ccc802ca453f63d6a5728341f42174f985d | 58,976 |
def posECIfromECEF(posECEF_, second):
"""
Args:
posECEF_ (np.array 3x1) : position in ECEF coordinate [m, m, m]
second (double) : time from reference time [s]
Return:
(np.array 3x1) : position in ECI coordinate [m, m, m]
"""
return np.matmul(dcmECEF2ECI(second), posECEF_) | a14717ed6a431cd0ba84781c6141070509f05cd5 | 58,977 |
def get_prediction(url,topics_count=10):
""" Send an url to xplr and gets the result of the prediction
as labelled topics, extracted content and words)
:param url: the url to be predicted
:param topics_count: number of topics expected
:returns: a tuple (title, topics) where title is extracted
b... | 81d2ca151c77c526ce3a9cdcc8ba1b3aaf67df02 | 58,978 |
def startup(name):
"""
Start Traffic Server on the local node.
.. code-block:: yaml
startup_ats:
trafficserver.startup
"""
ret = {"name": name, "changes": {}, "result": None, "comment": ""}
if __opts__["test"]:
ret["comment"] = "Starting up local node"
return... | 19d6c1ce478b94d926bbb2c789083f7840e086f8 | 58,979 |
def calc_ma(datas, ma_list):
"""
根据 ma_list 计算 ma 数值
calc
:param datas: dataframe
:param ma_list: string list
:return:
"""
try:
for ma in ma_list:
datas['ma%d' % ma] = ta.SMA(datas['close'].values, ma)
except Exception as e:
print(e)
return datas | ff469f73adfbf014b844f01ed504f31d138e9c78 | 58,980 |
def split_args(arguments):
"""
","구분자로 split
리턴: list
"""
try:
return arguments.split(",")
except UserDefinedException as e:
raise UserDefinedException(f"[-] split_args Error split: {e}") | 7d451cc2078d7fecce9a3cf27fb0fa3d55271a2b | 58,981 |
def Data(Objectid):
"""
Parameters
----------
Objectid : String, ZTF ID
Takes in ZTF object id and makes a dataframe of it's lightcurve data
Returns
-------
DataFrame with lightcurve data
"""
Supernovadf = pd.DataFrame(columns = ["mjd", "band", "magnitude", "error", ... | 6733c624f35fde4e65dc9dd4da445209442d627a | 58,982 |
def init_line_complex(p):
"""
initialize 1D complex on the line
Input:
p - number of 0-simplices
Will add (p-1) 1-simplices
"""
f = d.Filtration()
for i in range(p-1):
c = d.closure([d.Simplex([i, i+1])], 1)
for j in c:
f.append(j)
return f | 2f53a2f2bc1156adea0f22b6a6d999d90c65d0fc | 58,983 |
from datetime import datetime
def prettify_time(time_string: str) -> str:
"""Fix timestamps to a better format."""
if time_string:
parsed = datetime.strptime(time_string, "%Y-%m-%dT%H:%M:%S.%fZ")
return datetime.strftime(parsed, "%Y-%m-%d %H:%M:%S")
else:
return 'N/A' | f40a0dc1f26bea8001d823ab38a3f1cd0000050a | 58,984 |
def format_uptime(uptime_in_seconds):
"""Format number of seconds into human-readable string.
:param uptime_in_seconds: The server uptime in seconds.
:returns: A human-readable string representing the uptime.
>>> uptime = format_uptime('56892')
>>> print(uptime)
15 hours 48 min 12 sec
"""
... | a6a4544b6754113d0c5ed13a18838770448be6a8 | 58,985 |
def load_lines(file_name,
fields=["lineID", "characterID", "movieID", "character", "text"],
delimiter=" +++$+++ "):
"""
Args:
file_name (str): file to load
fields (set<str>): fields to extract
delimiter (str): delimiter string
Return:
dict<dict<s... | b18d8a84c143cd5a53516b7dc465ba1ef7d72e26 | 58,986 |
def string_camelcase(string):
""" Convert a word to its CamelCase version and remove invalid chars
>>> string_camelcase('lost-pound')
'LostPound'
>>> string_camelcase('missing_images')
'MissingImages'
"""
return CAMELCASE_INVALID_CHARS.sub('', string.title()) | c41b07d5285e9cdf78be107f2b2407f9ba6c266d | 58,987 |
from nltk.tokenize import word_tokenize
from typing import DefaultDict
import torch
from typing import Optional
from typing import Tuple
from typing import List
def prepare_untagged_data(
data_path: str,
word_to_ix: DefaultDict[str, int],
device: torch.device,
tokenizer: Optional[BertT... | 7baecfc656d0ed21e5d94a5b309e39d40f76e587 | 58,988 |
def chunker(arrays, chunk_size):
"""Split the arrays into equally sized chunks
:param arrays: (N * L np.array) arrays of sentences
:param chunk_size: (int) size of the chunks
:return chunks: (list) list of the chunks, numpy arrays"""
chunks = []
# sentence length
sent_len = len(arrays[0])... | 42a6867464e32d59a50927e8e88d067fc86f4fa1 | 58,989 |
from typing import Optional
def standardization(data: Optional[list or np.array], decimals: None or int = None):
"""
对一系列数据进行标准化处理,常用的方法是z-score标准化,处理后数据均值为0,标准差为1。
Args:
data (list or np.array): 需要被标准化的数据。
decimals (None or int): 归一化后,数值保留的精度(小数位数),默认为None,不开启
Returns:
np.ar... | c2009603ff120640c704a7fd26a24acfbd86ef64 | 58,990 |
def scale(img):
"""
scaling
"""
img = (img - np.array([123.68, 116.779, 103.939])) / np.array([58.393, 57.12, 57.375]) # img = (img - tf.constant([123.68, 116.779, 103.939])) / tf.constant([58.393, 57.12, 57.375])
return img | 8240ae4ae9653cf75d91256f8281dfcc84cee88b | 58,991 |
def set_pos(g, gtype='bipartite', **kwargs):
"""
Sets the position of nodes for plots in resultdisp.graph using a graphical tool.
Note: make sure matplotlib is set to plot in an external window (e.g using '%matplotlib qt)
Parameters
----------
g : networkx graph or model or function
nor... | 051ba95e05c22f9c2a687a6ae8bfadb3369378fe | 58,992 |
def fuzzy_replace(
words_list,
query_list,
threshold=81,
return_string=True,
scorer=fuzz.QRatio,
whitelist=False):
"""
Function to perform fuzzy replacing based on `words_list` (vocabulary)
and similarity `threshold`.
Args:
words_list (list):
... | bb6eee92adff1bb28451dec5a9b1de895f9d842a | 58,993 |
def get_type_lists(frame, rejects=['Id', 'ID','id'],frame_type='h2o'):
"""Creates lists of numeric and categorical variables.
:param frame: The frame from which to determine types.
:param rejects: Variable names not to be included in returned lists.
:param frame_type: The type of frame being used. Acc... | 24af8163bd729306f633ffaebd01fa9bfb28ae2e | 58,994 |
def calc_CTheatload(BldgDemand, BldgToCTs, CT_catalog, t_from=None, t_to=None):
"""Calculates the CT heat load to be passed to simulate_CT() by allocating the total heat load to all the CTs by
their capacity (i.e. no smart scheduling of CTs accdg. to load).
PARAMETERS:
BldgDemand DataFrame... | d6de442fc7037717a4a8ba783e4fa049d8915bc3 | 58,995 |
def dmi(sst, frequency='monthly', apply_filter=False, base_period=None,
area_weight=False, lat_name=None, lon_name=None, time_name=None):
"""Calculate dipole mode index.
The DMI introduced by Saji et al is defined as the
difference in SST anomalies between the western and
south-eastern tropical... | a8622fef9d61aa8a52030ec82c4ac3acc5fa9589 | 58,996 |
from typing import Optional
from typing import Tuple
def ptr_to_fresh(c : Contract, ty : LLVMType, name : Optional[str] = None) -> Tuple[FreshVar, SetupVal]:
"""Add to``Contract`` ``c`` an allocation of a pointer of type ``ty`` initialized to an unknown fresh value.
:returns A fresh variable bound to the... | bdc38bfb75ee2b30d88df65e9961f06444f5398a | 58,997 |
import signal
def fit_continuum(wav, spec, func='polynomial', order=3, nit=5,
rej_low=2.0, rej_high=2.5, grow=1, med_filt=0,
percentile_low=0.0, percentile_high=100.0,
min_points=10, verbose=False):
"""
Continuum fitting re-implemented from IRAF's 'continu... | be3c55ef3b763a81511bf04b32b36262ca8ee716 | 58,998 |
def select_reads_from_bam(input_bam_fofn_fn, rawread_to_contigs_fn, rawread_ids_fn, sam_dir):
"""Write ctg.sam files into cwd,
for each 'ctg' read in input BAMs.
"""
read_partition = {}
read_to_ctgs = {}
print "rawread_ids_fn:", repr(rawread_ids_fn)
print "rawread_to_contigs_fn:", repr(rawr... | 0ec45f8fd45e904a436cb5118c31cfa33b7ccd19 | 58,999 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.