content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
from typing import Dict
def convert_to_km(distance: float, print_output: bool = True) -> Dict[str, float]:
"""Convert a miles distance into the double of km.
Args:
distance: a distance (in miles).
print_output: if True, prints the progress.
Returns:
A dictionary with two keys ('o... | 1fb9dbbeb890a348d0feeebaea1a308bc06b039d | 3,611,850 |
import torch
def discriminator_loss(D, real_images, fake_images):
"""Loss computed to train the GAN discriminator.
Args:
D: The discriminator.
real_images of shape (batch_size, nc, 28, 28): Real images.
fake_images of shape (batch_size, nc, 28, 28): Fake images produces by the generator.
... | 397c1cd3c4ad8f90e78f4d2d0eb0501093133735 | 3,611,851 |
def Lucas_chain(n, f, g, x_0, x_1):
"""
Given an integer n, two functions f and g, and initial value (x_0, x_1),
compute (x_n, x_{n+1}), where the sequence {x_i} is defined as:
x_{2i} = f(x_i)
x_{2i+1} = g(x_i, x_{i+1})
"""
binary = arith1.expand(n, 2)
u = x_0
v = x_1
while b... | 514d9977434cbc5538d97e9622ea6c983a0bf604 | 3,611,852 |
import itertools
def build_input_from_segments(
history, reply, tokenizer, lm_labels=False, with_eos=True
):
""" Build a sequence of input from 2 segments: history and candidate reply. """
bos, eos, speaker1, speaker2 = tokenizer.convert_tokens_to_ids(SPECIAL_TOKENS[:-1])
# build input sequence as:
... | 1ab5a269a253e8042c920f8c74990923fee7ad3d | 3,611,853 |
import aiohttp
def aiohttp_socket_timeout(socket_timeout_s):
""" Return a aiohttp.ClientTimeout object with only socket timeouts set. """
return aiohttp.ClientTimeout(total=None,
connect=None,
sock_connect=socket_timeout_s,
... | c17a40a532aee15557b4e507439b0a7b2e98989e | 3,611,854 |
import json
from datetime import datetime
def get_contributions_from_file(site, username):
"""Get a list of Wikipedia-namespace contributions."""
with open("my-contribs.json") as my_contribs_file:
data = json.load(my_contribs_file)
for contrib in data:
time = datetime.datetime.strp... | f4458c4882beadca212560f30da4d12b49d811e6 | 3,611,855 |
def alignment_to_search_path(algn):
"""
Given an alignment, make searchpath.
Searchpath must step exactly one position in x XOR y at each time step.
In the case of a block of deletions, the order found by DP is not meaningful.
To make things consistent and to improve the probability of recoveri... | c5daa5c1bd9045527f588c8ca856f69b5d52838f | 3,611,856 |
def getMulitples(indices):
"""Return a subset with no multiples (filters out the bad ones)."""
multiples = []
added = []
for i in range(0, len(indices) - 1):
if indices[i][0] == indices[i + 1][0]:
added.append(indices[i])
elif added:
added.append(indices[i])
... | 4846fe1950f7d1a5379595b93e18c3ed0eb2d160 | 3,611,857 |
def get_pourbaix_info(entry: dict) -> dict:
"""
Grabs the relevant pourbaix entries for a given mpid
from Materials Project and constructs a pourbaix diagram for it. This currently only supports MP materials.
Args:
entry: bulk structure entry as constructed by
catlas.load_bulk_st... | c53cb58af64a3b63909e56706dfee1d933db20da | 3,611,858 |
def do_math(a, b, operator):
"""Helper function that performs computation between two numbers."""
if operator == "+":
return int(b) + int(a)
elif operator == "-":
return int(b) - int(a)
elif operator == "*":
return int(b) * int(a)
elif operator == "/":
return int(b)... | 5bffd1db1659c9f3420cc66a28525698de3beef5 | 3,611,859 |
def deg_to_arcsec(angle: float) -> float:
"""
Convert degrees to arcseconds.
Args:
angle: Angle in units of degrees.
Returns:
angle: Angle in units of arcseconds.
"""
return float(angle) * 3600. | 02fd099627970116bf5513af8b8d2d62bdc8ed41 | 3,611,861 |
def pixel_level_peak_finder_1d(correlation_lines: np.ndarray) -> np.ndarray:
"""
This function returns a numpy array containing the location of the maximum surface value
to pixel level accuracy for each row of the input matrix.
:return: The location of the maximum surface values to pixel level accuracy... | 6afa9b3a9e565aeab9915e7c8b5699df0842d498 | 3,611,862 |
def Shift(**kwargs):
"""
Calculates register shifts between strands based on their pairing and length
"""
refbluefile = kwargs.get('refblue')
seg1 = kwargs.get('seg1')
seg2 = kwargs.get('seg2')
refblue = Blueprint(refbluefile)
nseg1 = len( refblue.segment_... | b0a377131df521e3d96790a0b6f9d1e2d1893a64 | 3,611,863 |
async def test_ap_fails(injector):
"""Async providers must not be usable in sync consumers"""
class A:
pass
a = A()
@injector.consumer
def consumer(a_: A):
assert a_ is a
@injector.provider
async def bean() -> A:
return a
with pytest.raises(pyserp.InjectionErr... | f9cb09ec0a5c8246b1ed65c5f388a8904d4e60d4 | 3,611,865 |
def gru_run(params, x_t):
"""Run the Vanilla RNN T steps, where T is shape[0] of input.
Args:
params: dict of GRU parameters
x_t: np array of inputs with dim ntime x u
Returns:
2-tuple of np arrays (hidden states w dim ntime x n, outputs w dim ntim x o)
"""
return gru_run_with_h0(params, x_... | 294dbd3e56d1a8ea337c03bd99b15443b6a908f5 | 3,611,866 |
def set_window_width(image, MIN_BOUND=-1000.0, MAX_BOUND=400.0):
"""่ฎพ็ฝฎ็ชๅฎฝ"""
image[image > MAX_BOUND] = MAX_BOUND
image[image < MIN_BOUND] = MIN_BOUND
return image | 0dfa6e858c74cacc2cc8724d33f9b7fd96835d0c | 3,611,867 |
def _process_merge(p1_ctx, p2_ctx, ctx):
"""compute the appropriate changed files for a changeset with two parents
This is a more advance case. The information we need to record is summarise
in the following table:
โโโโโโโโโโโโโโโโฌโโโโโโโโโโโโโโโฌโโโโโโโโโโโโโโโฌโโโโโโโโโโโโโโโฌโโโโโโโโโโโโโโโ
โ diff... | 8c3fedad5578c37eccf35a7fdd844ab3c244d57c | 3,611,868 |
def create_mmt_encoder_inputs(data_cfg: cfg.DataConfig):
"""Creates inputs for `MmtEncoder`."""
patch_embedding_size = (data_cfg.patch_size ** 2) * 3
num_patch_per_row = data_cfg.image_size // data_cfg.patch_size
num_patches = num_patch_per_row ** 2
max_seq_len = data_cfg.max_seq_len
word_ids = tf.keras.... | 1ccbe6468e25cccd32049dd65300426819d9737a | 3,611,869 |
import json
def update_chart_info(_figure, chart_data_json_str):
"""
A callback function to set the sample count for the number of samples that
have been displayed on the chart.
Args:
_figure (object): A figure object for a dash-core-components Graph for
the strip chart - triggers... | fd28e28b7b48131bb56d6d9f29e4fe438b33bb7a | 3,611,870 |
def record_copy_all(node, **kwargs):
""" A default rcd implementation that copies all kwargs to the tape.
the impl is used for the vjp and vjp primitives.
the impl is can be used for the apl primitives if no rcd is given;
but we use 'record_copy_autodiff' to save a much smaller subset
... | e7e957c1d9fb0cc36bf54c1ab431ba4c7892838c | 3,611,871 |
def read_file(filename):
""" Return the content of a file as a list of strings, each corresponding to a line
:param filename: string: location and name of the file
:return: content of filename
"""
with open(filename, 'r') as ofile:
content = ofile.read().splitlines()
return content | 58a2718265fef848e484178e407aee6f7017a52a | 3,611,873 |
def parse_record(raw_record):
"""Parses a record containing a training example of an image.
The input record is parsed into a label and image, and the image is passed
through preprocessing steps (cropping, flipping, and so on).
Args:
raw_record: scalar Tensor tf.string containing a serialized
... | 2f669bda6cec630e4fd81576532a96f1ec6d6a00 | 3,611,874 |
def helicsFederateRegisterGlobalTypeInput(fed: HelicsFederate, name: str, type: str, units: str) -> HelicsInput:
"""
Register a global publication with an arbitrary type.
The publication becomes part of the federate and is destroyed when the federate is freed so there are no separate free functions for subs... | 487179f3de8d9f72efaa696e50441250e49f5438 | 3,611,875 |
from typing import Optional
from typing import Mapping
def get_cluster(cluster_identifier: Optional[str] = None,
tags: Optional[Mapping[str, str]] = None,
opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetClusterResult:
"""
Provides details about a specific redshift c... | bd5ca8151d0fafbeef735707b1971c03f05ec9e8 | 3,611,876 |
def translate_to_origin(structure, weight="mass", atom_mask=None, dimension=None):
"""Translate a structure to the origin based on the centroid of the whole system or a subset of atom(s).
Parameters
----------
structure : str or :class:`parmed.Structure`
Molecular structure containing coordinat... | 269f566e4fbf43308bf4db8b2972adc3487fcde9 | 3,611,877 |
def score_1(game, player): # 82.14%
"""
Heuristics computing score using #player moves - k * #opponent moves
:param game: game
:param player: player
:return: score
"""
if game.is_winner(player) or game.is_loser(player):
return game.utility(player)
opponent = game.get_opponent(p... | 3995237f5d5474660c752c308e1077aad1743d06 | 3,611,878 |
def parse_line( line ):
"""Returns data located in the line."""
tokens = line.split()
return int(tokens[1]), tokens[2], (
int(tokens[4]), # n_i
int(tokens[6]), # s_i
) | 487421bcc50e4d542227e54a1362008a8a678b5b | 3,611,879 |
def find_ancestors(starting_resource, full_name):
"""Find the ancestors for a given resource.
Take advantage of the full name from the data model which has
the entire hierarchy.
Keeping this outside of the class, because the class is mocked out during
testing.
Args:
starting_resource ... | e307c902422077405eb79171d6abc9038724f03b | 3,611,880 |
import asyncio
async def is_streamable(filename: str) -> bool:
"""Return if a file is streamable by pyatv.
This method will return if the file format of the given file is supported
and streamable by pyatv. It will never raise an exception, e.g. because the
file is missing or lack of permissions.
... | f924ed95b18c04cb9f9247fecaa92f903a0663cf | 3,611,882 |
def forward_pass(x: np.ndarray, weights: np.ndarray, bias: float) -> np.ndarray:
"""
Method that calculates the activation of the sigmoid function
from a given input, weights and biases.
:param x: input data
:param weights: tuple with the weights
:param bias: value of the biases
:return: ac... | 2ae788aebe921f743cfa9379d1ea496b1b9881f5 | 3,611,883 |
def get_long_description():
"""
Provides the long description.
"""
with open("README.rst", "r", encoding="utf-8") as file_stream:
return file_stream.read() | 35e8b7d1c4db25e1cf49328d4be1d1d2f9ddf581 | 3,611,884 |
def get_connections(ccs_path):
""" Returns list of installed connection names.
Searches "<ccs_path>/ccs_base/common/targetdb/connections" directory for
installed connection names.
Args:
ccs_path (str): full path to ccs installation to use
Returns:
list: connection names
Raise... | 73bc6f875c61f792d746687277fe1a29c04539ac | 3,611,885 |
def escape_latex(strng):
"""Consistently escape LaTeX special characters for _repr_latex_ in IPython
Implementation taken from the IPython magic `format_latex`
Examples
--------
escape_latex('disease_rate') # 'disease\_rate'
Parameters
----------
strng : str
string to esc... | 50958dc7c736b6c3b7fb3d4c2715fcd2e1855205 | 3,611,886 |
import json
def list_subnets(sort_by='name'):
"""
Get list of subnets from maas server
CLI Example:
.. code-block:: bash
salt 'maas-node' maasng.list_subnets
"""
subnets = {}
maas = _create_maas_client()
json_res = json.loads(maas.get(u'api/2.0/subnets/').read())
for ite... | 313d917f6938ecd5ed3a9288fe3116493f128f7a | 3,611,887 |
def multinomial_as_basic(multinomial, *symbols):
"""
Converts the multinomial to Add/Mul/Pow instances.
multinomial is a dict of {powers: coefficient} pairs, powers is a tuple of
python integers, coefficient is a python integer.
"""
l = []
for powers, k in multinomial.iteritems():
t... | 0d481de0c572966b6fa99073173dc0cbef241fb7 | 3,611,889 |
from typing import List
from typing import Tuple
from typing import Any
import joblib
def topic_modelling(all_data_t: List[List[float]],
tfidf: TfidfVectorizer, n_keywords: int,
param_grid=TRAIN_PARAM_GRID_LDA,
retrain=False, plot=False,
... | 04a5d3f775bb9bc01f8815ba2d842edbbe43c597 | 3,611,890 |
from typing import List
def get_gpu_memory() -> List[int]:
"""Query GPU's for amount of VRAM
Modified from:
https://stackoverflow.com/questions/59567226/how-to-programmatically-determine-available-gpu-memory-with-tensorflow
Returns
-------
VRAM, List[int]
Total GPU VRAM in bits for ea... | facfe363c38b0d9d55b824fd48e79fb44b888ae2 | 3,611,891 |
import base64
def smiles2inchi(smiles):
"""
Converts SMILES to InChi. This method accepts urlsafe_base64 encoded string containing single or multiple SMILES
optionally containing header line, specific to *.smi format.
cURL examples:
curl -X GET ${BEAKER_ROOT_URL}smiles2inchi/$(cat aspirin_with_header.smi | b... | b4bf76ba132d7f52fe5be503ec72ed5149e0a859 | 3,611,892 |
from typing import Dict
from typing import Tuple
def list_vaults_command(client: Client, args: Dict) -> Tuple[str, Dict, Dict]:
"""Lists all vaults.
"""
max_results = int(args.get('max_results', 0))
raw_response = client.list_vaults(max_results)
vaults = raw_response.get('vault')
if vaults:
... | 9e8760eca79e94f0ad52a94aa205531592074b84 | 3,611,893 |
def strip_ddp_state_dict(state_dict):
""" Workaround the fact that DistributedDataParallel prepends 'module.' to
every key, but the sampler models will not be wrapped in
DistributedDataParallel. (Solution from PyTorch forums.)"""
clean_state_dict = type(state_dict)()
for k, v in state_dict.items():
... | f4cd6917db3df384e70c6b54dc4142dd760dd1d2 | 3,611,894 |
def parameter_attention(x,
total_key_depth,
total_value_depth,
output_depth,
memory_rows,
num_heads,
dropout_rate,
name=None):
"""Attention over param... | 199c0d205913a480ee67fce53030ab7d27c45df3 | 3,611,895 |
def plot_gp_plotly(
model: GPModel, mins: TensorType, maxs: TensorType, grid_density=20
) -> go.Figure:
"""
Plots 2-dimensional plot of a GP model's predictions with mean and 2 standard deviations.
:param model: a gpflow model
:param mins: list of 2 lower bounds
:param maxs: list of 2 upper bou... | 42203278f142dbfc30e00df21a2bbc3212e34f64 | 3,611,896 |
def pareto(all_y, maximize=False):
"""
Returns the indices of Pareto-optimal solutions.
Args:
Y [list]: A list of lists containing values to be evaluated for Pareto-
optimality
Returns:
list - The indices of the entries which are Pareto-optimal
"""
all_y = np.asarra... | 02985b54638d90b1ffc0026ff779ddbfaad77ebc | 3,611,897 |
def _import(module_name, class_name):
"""
Return class of the module_name, where module_name is of the form
package.module (testoob's Asserter, which does simple __import__, returns
package, not package.module in this situation).
"""
mod = __import__(module_name)
components = module_name.spl... | 27a20935b305e3c387c861392429794976d7d866 | 3,611,898 |
def plot_roc(labels, score, title='ROC', verbose=True):
"""Plot ROC curve
Parameters
----------
labels : np.ndarray
vector of ground truth
score : np.ndarray
vector of scores assigned by classifier (i.e.
clf.pred_proba(...)[-1] in sklearn)
title : str
title of p... | 4b395988249e10fee803201997140debe3314739 | 3,611,899 |
def delete_user(username: str):
"""
Parameters
----------
username : str, required
Returns
-------
Response:
{
"deleted": true,
}
Raises
------
HTTPException
"""
response = False
try:
username_constraint(username)
... | 1ad90ce7113b2551e7bc63629061b7c9a45c4943 | 3,611,900 |
def imread(image_name, colorspace="RGB"):
"""
Reads image and returns RGB numpy array
Parameters:
image_name: Image path , str
colorspace: RGB or BGR, str
Returns:
img: numpy array
"""
img = cv2.imread(image_name)
if colorspace == "RGB":
img = cv2.cvtColor(img... | 15129c95eedb86b1bc9be01c87af01a5ab4d86ee | 3,611,901 |
def _extract_time_series(data, time_series_name='values'):
"""
Extract specific time series from provided pandas DataFrame and return as a pandas Series
"""
# If it's already a series, just return it
if isinstance(data, pd.Series):
return data
if time_series_name not in data:
r... | ed10c625d158190707f05da259eb2b204bad2ba2 | 3,611,902 |
def residual_resampling(weights):
"""Residual resampling. The counts in each bin are floor(w*N) + N' where
N' is sampled from a multinomial with the residual weights."""
N = weights.shape[0]
counts = np.floor(weights*N)
R = int(np.sum(counts))
new_weights = (weights*N - counts)/(N-R)
counts ... | f96d8456caf15502c18effb7cb5d1b3cb030a785 | 3,611,903 |
def get_reftypes(exp_type, cal_ver=None, context=None):
"""Based on the exposure type, CAL s/w version, and CRDS context, determine
the list of applicable reference file types.
"""
return [] | ccb08ecd63b85d4602d419fb8fd90e77984c4048 | 3,611,904 |
def mix(n = 1):
"""Accumulate n composite samples from the active generators."""
# Gather samples and count notes.
s = np.zeros(n, dtype=np.float32)
n_notes = 0
for note in set(notemap):
e = note.envelope()
if e == None:
# Release is complete. Get rid of the note.
... | 149059ba5a67997ccd9c0866cb3af18c510aa22c | 3,611,905 |
def train_step(grid, weights, optimizer, mov, fix):
"""
Train step function for backprop using gradient tape
:param grid: reference grid return from layer_util.get_reference_grid
:param weights: trainable affine parameters [1, 4, 3]
:param optimizer: tf.optimizers
:param mov: moving image [1, m... | eb28006c71301ea1a1a7c28fa010e2cf914edf98 | 3,611,906 |
def get_CV_current(CV):
"""
Helper function to compute CV current.
Args:
CV (pd.DataFrame): CV segement of charge
Returns:
(float): current reached at the end of the CV segment
"""
if not CV.empty:
return(CV.current.iat[-1]) | 69e32ecadc57d0855eedfe3404db1e5ec9839862 | 3,611,907 |
def tanh(x):
""" Calculate hyperbolic tangent of the input AD object, integer, or float
INPUTS
=======
x: input value, an AD object, int, or float
RETURNS
========
result: hyperbolic tangent of x
EXAMPLES
=========
>>> x = ad.AD(2.0, [1.0,0.0])
>>> print(tanh(x... | 7fdafe2f8cf7c4330b8008b592ec79c993b172b5 | 3,611,908 |
def init_weights(shape):
""" Weight initialization """
weights = np.asarray(np.random.randn(*shape) * 0.01, dtype=theano.config.floatX)
return theano.shared(weights) | 657ccea8286b9ae84ef28e0285f12f8bc3b8f2e5 | 3,611,909 |
def get_img_mask_generators(dataset_path,
target_size,
img_path="img",
ann_path="ann",
img_preprocessor=None,
mask_preprocessor=None,
SEED=1,):
"""
... | c0d6a9de27bc8af98c838bea695934129ae8b73e | 3,611,912 |
def prepare_noise_cov(noise_cov, info, ch_names=None, rank=None,
scalings=None, verbose=None):
"""Prepare noise covariance matrix.
Parameters
----------
noise_cov : instance of Covariance
The noise covariance to process.
info : dict
The measurement info (used t... | eb0111c4f1c4e997bcf71f9f7a3d81ff19e9954f | 3,611,914 |
def gsl_blas_zgemm(*args, **kwargs):
"""
gsl_blas_zgemm(CBLAS_TRANSPOSE_t TransA, CBLAS_TRANSPOSE_t TransB,
gsl_complex alpha, gsl_matrix_complex A, gsl_matrix_complex B,
gsl_complex beta, gsl_matrix_complex C) -> int
"""
return _gslwrap.gsl_blas_zgemm(*args, **kwargs) | 5d273fab2e8b9c0379cd477b1ba51fb5c7e1525c | 3,611,915 |
import requests
from bs4 import BeautifulSoup
def get_login_api(username, password):
"""
็ปๅ
ฅ็ณป็ป
"""
s = requests.session()
lt = get_ticker(s)
url = 'http://ids.sdufe.edu.cn/authserver/login?service=http%3A%2F%2Flibst.sdufe.edu.cn%2Fcas%2Findex.php%3Fcallback%3Dhttp%3A%2F%2Flibst.sdufe.edu.cn%2Fh... | 7d739178f8316f19e421de9564a2a72a7070d09d | 3,611,916 |
import torch
def sparsify_array(array):
"""Convert a np.array into a torch.sparse.FloatTensor
Args:
array (np.array)
returns:
sparse (torch.sparse.Tensor)
"""
return sparsify_tensor(torch.FloatTensor(array)) | db16c3a369f696694abc050ef0a11264406fff62 | 3,611,917 |
def tracer(pid):
"""tracer(pid) -> int
Arguments:
pid (int): PID of the process.
Returns:
PID of the process tracing `pid`, or None if no `pid` is not being traced.
Example:
>>> tracer(os.getpid()) is None
True
"""
tpid = int(status(pid)['TracerPid'])
retur... | 8042e473f392c255d0e8c75d2e05aa88237361bd | 3,611,918 |
async def staking_config_cms(
project: str,
db=Depends(get_db),
):
"""
Get config
"""
try:
return get_staking_config_by_name(db, project)
except Exception as e:
return JSONResponse(
status_code=status.HTTP_400_BAD_REQUEST, content=f"{str(e)}"
) | 5227bf979a7025c5e946cb152e31e7625cb764ec | 3,611,919 |
import bisector
import build_specified_commit
import tempfile
import logging
import traceback
def do_bisect(bisect_type, source_id, project_name, engine, sanitizer,
architecture, fuzz_target, old_commit, new_commit, testcase):
"""Do the actual bisect."""
with tempfile.NamedTemporaryFile() as f:
... | 548c9525199f16778adff12c42ebf4f69a68144f | 3,611,921 |
import torch
def _unstack(array):
"""Similar to `tf.unstack`."""
num_splits = int(array.shape[0])
return [torch.squeeze(x, dim=0) for x in np.split(array, num_splits, axis=0)] | 34df9cd0ea0620f88f47ab6aeeaec80a6d2ba030 | 3,611,922 |
def predict(images, model, alpha, rho=0, return_model=False):
"""Apply background subtraction to a batch of images
Args:
images: numpy array with shape [num_ims, height, width, channel]
containing the images to process.
model: tuple (mean, std) obtaining with create_model() function.
... | b06512141faa884cda315d789058a81f95569e2f | 3,611,924 |
def stations_by_river(stations):
"""This function creates a dictionary with river names as a key and a list of all the
station names on the respective river"""
rivers = rivers_with_station(stations)
river_dictionary = {}
for river in rivers:
river_dictionary[river] = [] #Generating Empty Di... | e1ae6797a44a551594dcad1e5b38e171cef7730a | 3,611,925 |
import unicodedata
def filter_nick(name):
"""
filter_nick(name) -> String
Process the name and get rid of all whitespace, invisible characters and
make it all lower case.
This function is intended to mimic euphoria's name pinging system, however
it is slightly less pedantic, allowing for pun... | bba506f4b2e84b4f82df8a4b31feb82203db8356 | 3,611,926 |
from datetime import datetime
from dateutil import tz
def get_mondays():
"""Returns a tuple with start and end Time Stamp Strings from last monday to midnight this monday.
Unless it is a monday. In that case we actually want the previous period."""
today = datetime.now().replace(hour=0, minute=0, second=0... | 1d04182150ae2e4196002b5b18d338e103980d40 | 3,611,927 |
def tfidf_score_str(tokens, texts, tfidf_function_name, number_all_texts_in_db, m=10,*args):
# Same as tfidf_score, only takes tfidf_function name as input instead of function itself.
"""Assigns score to documents based on tfidf_function metric.
Args:
tokens (list): List of tokens (tokenized query).... | bfc91875f28e189b68630115bf7acba1ad05e6e5 | 3,611,928 |
def distort_img(input_img, d_limit=4):
"""
Apply warpPerspective transformation on image, with 4 key points, randomly generated around the corners
with uniform distribution with a range of [-d_limit, d_limit]
:param input_img:
:param d_limit:
:return:
"""
if d_limit == 0:
return ... | c8e214a0a022ade460686b5557b8bc78747a38f1 | 3,611,929 |
def delete_v1_session(session_id): # noqa: E501
"""DELETE /v1/session
Delete the session by session id
"""
with BosEtcdClient() as bec:
key = "{}/{}/".format(BASEKEY, session_id)
resp = bec.delete_prefix(key)
if resp.deleted >= 1:
return '', 204
else:
... | 92e1d3564bf1698cdaeede161370f994dcd7682a | 3,611,930 |
def label_name(event_data):
"""Get the label name from a label-related webhook event."""
return event_data["label"]["name"] | 903173b4fd9ddeb0a74a3e10be94626e0685a037 | 3,611,931 |
from datetime import datetime
def new_event(dtstart=None, dtend=None, summary=None, timezone=None,
_now=datetime.now):
"""create a new event
:param dtstart: starttime of that event
:type dtstart: datetime
:param dtend: end time of that event
:type dtend: datetime
:param summary:... | 9721e2cac6e0fef45e60436e7cf5e5d0d1eb750c | 3,611,933 |
def getCashflowsByUserID(db, userID):
"""
Get cash flows by user's ID
:param db: database object
:param userID: user's ID
:return: Tuple of cash flow
((flowID, userID, amount, message, date), ((flowID, userID, amount, message, date)))
"""
if db is None:
return None
try:
... | b2a1e1d52de74559792feca57f2366d38ced9e46 | 3,611,934 |
def predict_fn(self, x):
"""
Overrides the predict function for models, provided that the predict
function takes in one argument.
"""
predict_array = self.predict(x)
return convert_prediction_to_event(self, predict_array, x) | 0c7d34c121446155f371cb11871714acf78c37d5 | 3,611,935 |
from typing import Dict
from typing import Any
from typing import Type
from typing import Optional
def run(config: Dict[str, Any],
data_class: Type[DataModule],
model_class: Type[Module],
optuna: Optional[Optuna] = None,
runner: Optional[Runner] = None) -> Trainer:
"""Run the pipel... | 8d0890ff3e7a29d770f3365a85324be7edc5ed61 | 3,611,936 |
def concretePolynomialLoad():
"""
pytest fixture that returns a PolynomialLoad object with concrete parameters
:return: PolynomialLoad object initialized with concrete values
"""
addnl_params = dict(p=0.5, q=0.98, r=2678.88)
test_load_params = dict(a=0.01, b=0.05, c=0.1, j_load=0.1, p=0.5, q = ... | 910bc2a38f4b8c321cba4324cfcf99fbc72c9ffe | 3,611,937 |
def decode(data):
"""
Decodes URL safe base64 encoded value
"""
padding = 4 - (len(data) % 4)
data += ('=' * padding)
return urlsafe_b64decode(data).decode() | a39c75e1260a500ec1431c86a9bfa57623599823 | 3,611,938 |
from demisto_sdk.commands.upload.uploader import ConfigFileParser, Uploader
from demisto_sdk.commands.zip_packs.packs_zipper import (EX_FAIL,
PacksZipper)
def upload(**kwargs):
"""Upload integration or pack to Demisto instance.
DEMISTO_BASE_URL environment variable should contain the Demisto server base U... | eba4120bc7701752a1fb9831e4874c20ef29293a | 3,611,939 |
def bit_length_power_of_2(value):
"""Return the smallest power of 2 greater than a numeric value.
:param value: Number to find the smallest power of 2
:type value: ``int``
:returns: ``int``
"""
return 2 ** (int(value) - 1).bit_length() | bb49afee83ac255549ce5b5aaab80bb76ad4e337 | 3,611,940 |
def clip_but_pass_gradient(x, l=-1., h=1.):
"""
Stole this function from SpinningUp
Args:
x: data to be clipped.
l: lower bound
h: upper bound.
Return:
if x < l:
l
elif x > h:
h
else:
x
"""
clip_up = tf.cast(x > ... | a30e034a7b4c98df15c0da766f34c47a1bb39651 | 3,611,941 |
def get_encryption_algs():
"""Return a list of available encryption algorithms"""
return _enc_algs | 54813d7ec3caf8e077ac0d53e69166b861941c4e | 3,611,942 |
def get_statements_by_hash(hash_list, simple_response=False, *args, **kwargs):
"""Get fully formed statements from a list of hashes.
Parameters
----------
hash_list : list[int or str]
A list of statement hashes.
simple_response : bool
If True, a simple list of statements is returned... | 566557527b32348121f0a0f2473a221a1e671e98 | 3,611,943 |
import abc
def _get_prop(props_dict, spec):
"""Gets the given property specification from the dictionary
The specification can be a string or a pair of string and a callable.
:param dict props_dict: The dictionary to retrieve the property.
:param spec: The specification of the property, it can be a ... | 732c65fdfacd44f3b14bdd590990bd35d16c3d22 | 3,611,944 |
from typing import Match
def real_time(
minutes: float = 5,
increment: int = 8,
variant: Variant = Variant.STANDARD,
color: Color = Color.RANDOM,
) -> Match:
"""Start a live match that two players can join
:param minutes: :class:`float`
The number of minutes for the match (excluding i... | 05fcdde0ba90b69763d570749107b656675cb4da | 3,611,945 |
import json
def json_top_atom_count(json_str):
"""Count the number of atoms in a JSON topology used by wepy HDF5."""
top_d = json.loads(json_str)
atom_count = 0
atom_count = 0
for chain in top_d['chains']:
for residue in chain['residues']:
atom_count += len(residue['atoms'])
... | 0e1e23cd4b9e5cedf3e6b5d815ee817798188752 | 3,611,947 |
def length_squared(point):
"""
square of length from origin of a point
Args:
point (QPointF) the point
Returns
square of length
"""
return point.x()*point.x() + point.y()*point.y() | 0289ca736f087dd75f9b9e0f1347fdc223d03f84 | 3,611,948 |
def api_report_conference_role(conference_id, role_id):
"""
Takes a role ID and report data and reports the object with the
provided ID.
"""
return api_report_conference_child(conference_id, request.json, role_id, object_type="role") | 4a1b8ecadfccafdf76e616df851a5ca937e1a432 | 3,611,949 |
from typing import Union
from typing import Sequence
from typing import Callable
from typing import Optional
from typing import Dict
from typing import List
from typing import Any
from typing import Tuple
def plot_planckian_locus_in_chromaticity_diagram_CIE1960UCS(
illuminants: Union[str, Sequence[str]],
chro... | efc5dee6f632adccaf9fb413385bc71acda1ef54 | 3,611,950 |
def topSort(G):
"""
ไฝฟ็จBFSๅฎ็ฐๆๆๆๅบใ
ๆฏๆฌกๆพๅฐๅ
ฅๅบฆไธบ0็่็นๆพๅ
ฅๅ้๏ผ้ๅไธๅ
ฅๅบฆไธบ0็็น็ธ้ป็่็น๏ผๅนถๅฐๅบฆๆฐๅๅฐ1๏ผๅฆๆๅบฆๆฐๅไธบ0ๅๆพๅ
ฅๅ้ใ็ดๅฐๅ้ไธบ็ฉบใ
"""
Q = [] # ๅ้ๅญๅจๆฏไธช่็น
counter = 0
sort = {}
for i in G:
if i.degree == 0:
Q.append(i)
while len(Q) != 0:
vertex = Q.pop()
sort[vertex] = counter
counter += 1
if vertex.c == None:
continue
for j in... | 3b8662a4adbc32d9a2174b5faf82d0c763d703fe | 3,611,951 |
def _process_hooks(hooks):
"""Prepare hooks data for report."""
hooks_ctx = []
for hook in hooks:
hook_ctx = {"name": hook["config"]["action"][0],
"desc": hook["config"].get("description", ""),
"additive": [], "complete": []}
for res in hook["results"... | f0804e25c095547840f6f7eb5de7a76864b98970 | 3,611,952 |
def find_nearest_index(seq, value):
"""
Return the index of the value in the sequence that is closest to the
given value
"""
return (np.abs(np.array(seq)-value)).argmin() | 199e2ca62a0d820a04964676a28b702993701b36 | 3,611,953 |
def get_pv_asp_n(n):
"""Returns ASP PV associated with neg(-) beam species, either -.
Required for Main Buncher.
Arguments:
n(str or int): module or buncher number
"""
return get_pv_asp(n, '+') | e571d8cf062da019a0c52c7b1e383c33bac4afd4 | 3,611,956 |
def get_ancestor(taxid, tree, stop_nodes):
"""Walk up tree until reach a stop node, or root."""
t = taxid
while True:
if t in stop_nodes:
return t
elif not t or t == tree[t]:
return t # root
else:
t = tree[t] | f7841bc5104f96cd66122165a0646b70fc3fd33e | 3,611,957 |
def display_image(obd, mime_type):
"""Display the opaque binary response data with the image using IPython's
display.Image class
:param str obd: The opaque binary data
:param str mime_type: The image mime_type
:rtype: IPython.display.Image
"""
filename = write_temp_file(obd, mime_type)
... | f6530051c6b03d30cbf0952aa4d25412e0ba31b7 | 3,611,959 |
def load_checkpoint_train(cpdir, model, optimizer):
"""Load model and optimizer parameters for training
Note:
This is simply a wrapper to load_checkpoint so that
global_step and epoch are updated correctly.
If cpdir is None, do not load checkpoint and returns
0 for global_step an... | 076d7dc40eb361d523a164a5b1082cd8b1fe4ca9 | 3,611,960 |
def separable_conv1d(x, depthwise_kernel, pointwise_kernel, strides=1,
padding='valid', data_format=None, dilation_rate=1):
"""1D convolution with separable filters.
# Arguments
x: input tensor
depthwise_kernel: convolution kernel for the depthwise convolution.
poin... | 6ccfa89d31ccb1255552fbb9adef4500846281fa | 3,611,961 |
def has_sub_tasks(task):
"""Returns True if the task has sub tasks"""
if istask(task):
return True
elif isinstance(task, list):
return any(has_sub_tasks(i) for i in task)
else:
return False | fe55cbef39dc9d2a748e8bf9dc283d6146f27c79 | 3,611,962 |
from typing import List
def largest_values_in_row_colums(xs: np.array) -> List[float]:
""" Approximates the largest value in each row/column.
"""
if xs.shape == (0, ):
return [0]
assert len(xs.shape) == 2
# resize matrix to square dimensions if needed
if xs.shape[0] != xs.shape[1]:
... | 5a53345364d24fcf40305b4de5253051572a7de0 | 3,611,963 |
import xmlrpc
def delete_vm(client, session, vm, params):
"""Delete (ie: terminate) a virtual machine."""
if vm['state'] is None:
return {'changed': False}
xmlrpc(client, 'vm.action', session, 'terminate', vm['id'])
return {'changed': True, 'vm_id': -1, 'actions': ['terminated']} | d3f6c4d5fec34569fc9a066b6402f43e7816164e | 3,611,964 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.