content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def import_models(config, checkpoints_logdir, device, verbose=1):
"""Import model from configuration file
"""
model_manager = models.ModelManager(checkpoints_logdir, config['task_ids'])
model, last_ckpt = model_manager.load_model(
model_name=config['models']['name'],
model_weight... | 295dd11c4f7734fc529b0bfe31d908b60dfcdd89 | 47,357 |
from typing import Union
def greater_than_equal_to_validator(start) -> Validator:
"""
Validate that a given value is greater or equal to a number.
Can be used with int, float or BaseImageContainer.
:param start: the value to be greater than or equal to
"""
if not isinstance(start, (float, int)... | 0c6b026727c3c4dab5c58b259562c8aad95b9fed | 47,358 |
def single_text_phrase(context, slug=None, language=None):
"""
for using this template tag you must
enable one of the text_phrase context_processors.
this templatetag will return the first text phrase object,
if there is more then one object.
if you want single text phrase in special language se... | 7e9b5a28cbf1ae0215e201e3af0f22631aad9ac2 | 47,359 |
def slow_trajectory(robot, joints, path, min_fraction=0.1, ramp_duration=1.0, **kwargs):
"""
:param robot:
:param joints:
:param path:
:param min_fraction: percentage
:param ramp_duration: seconds
:param kwargs:
:return:
"""
time_from_starts = instantaneous_retime_path(robot, joi... | 22de73888ec8f34d9df9f7793b3e8b0acd4fd596 | 47,360 |
from typing import Callable
def make_request(func: Callable) -> Callable:
"""
Allows clients to customize how they want to make a request to the
service undergoing fuzz testing.
"""
get_abstraction().request_method = func
return func | 7f8ddeea6b38d4716f253941ebd77ce184439933 | 47,361 |
def renderScene(
background_plane, assembly, component_poses,
camera_pose=None, camera_params=None, object_appearances=None):
""" Render a scene consisting of a spatial assembly and a background plane.
Parameters
----------
Returns
-------
"""
# Start by rendering the back... | 3ededcb5caaead0eaff8aaa799dffb98f7a770ad | 47,363 |
def split_train_test():
"""
Import the dataset via sklearn, shuffle and split train/test.
Return training, target lists for `n_clients` and a holdout test set
"""
print("Loading data")
diabetes = load_diabetes()
y_raw = diabetes.target
X_raw = diabetes.data
# print(type(y_raw))
y... | 7bb6dfe8fe2afbae28f4303a0fa5312cda1da3eb | 47,364 |
def plot_dist_mat_multi_row(D, figsize=(3,3), titles=None, ylabels=None, wspace=0, hspace=0, sharex=False, sharey=False, cmap='Greys'):
"""Plots distaince matrices in a multi column and multi row manner (square matrix)."""
nr = len(D)
nc = len(D[0])
titles = titles or [None] * nc
ylabels = ylabels... | 8a99f6c9ed555a09857078acdd3e27566e62aa57 | 47,367 |
def read_several_fasta(input_files):
"""
Read several fasta files
Note that each fasta file may contain several sequences.
Parameters
----------
input_files: a list of fasta file paths.
Returns
-------
pb_name: a list of the headers
pb_seq: a list of the sequences
"""
... | 7eabeb44625c65e1bd1fe3c98d0d507b783dae8a | 47,368 |
def collect_sim_params(aperiodic_params, periodic_params, nlv):
"""Collect simulation parameters into a SimParams object.
Parameters
----------
aperiodic_params : list of float
Parameters of the aperiodic component of the power spectrum.
periodic_params : list of float or list of list of fl... | a39343bd307cc2e1b4194495da9177ef7ce1495d | 47,372 |
def dut_addr(dut, execute_helper):
"""Fixture to return the DUT address."""
return get_dut_address(dut, execute_helper) | a8ebc74a2b827e383c0f605b8e87edcf840cd161 | 47,373 |
import array
def encodeDPID (vendor,role, location, id):
"""
Generates a DPID that is encoded as follow:
DPID format: byte7 byte6 byte5 byte4 byte3 byte2 byte1 byte0
vendor type reserved <--- ASCII Name ------> id
:param location: 4 letters max. location (i.e. STAR, LBNL).
... | b5dbf8530c0f9b5d06d9da75ed8e10145ebc935e | 47,374 |
def smooth_segmentation(data_img, seg_img, fwhm, noise_img=None,
inplace=False):
"""Filter each compartment of a segmentation with an isotropic gaussian.
Parameters
----------
data_img : nibabel image
3D or 4D image data.
seg_img : nibabel image
3D label imag... | 1536ca1733692dc94d8c40e57ea32f018fdad0a1 | 47,375 |
def remove_node(**kwargs):
"""
删除节点任务
"""
code, res = SaltClient.operate_cetus_node(kwargs.get('id'), 'abort')
if not code:
TbCetusNodeInfo.objects.filter(pk=kwargs.get('id')).delete()
PeriodicTask.objects.filter(name='node_%s_monitor' % kwargs.get('id')).delete()
return '删除... | a5213996824fea1e5a1012880234b78706585438 | 47,376 |
def setup_training(layer_info,prob, trinit=1e-3,refinements=(.5,.1,.01),final_refine=None ):
""" Given a list of layer info (name,xhat_,newvars),
create an output list of training operations (name,xhat_,loss_,nmse_,trainop_ ).
Each layer_info element will be split into one or more output training operations... | 8d17f8651fe6e2cb1b3d157e10589beab2433df7 | 47,377 |
def update_messages_incoming(
messages_outgoing: jnp.ndarray,
nodes_factor_masks: jnp.ndarray,
nodes_indices: jnp.ndarray,
nodes_factor_indices: jnp.ndarray,
perturbation_configurations: jnp.ndarray,
):
"""update_messages_incoming.
Args:
messages_outgoing: Array of shape (n_nodes, n... | 6b17f8efc7d9b070e83c6a704de79a6b4c0ea2d4 | 47,379 |
import uuid
import time
def convert(req: SongMetadataForDownload, background_tasks: BackgroundTasks, request: Request):
"""Start download and conversion of song with given metadata in the background"""
uid = uuid.uuid4()
jobs[uid] = DownloadJob(request_id=uid, status=Status.WAITING, percentage_done=0.0, l... | 3c657cf34f9ba3ea1bbd3c6542fa1dfa7be29427 | 47,380 |
def linear_scale(input, in_low, in_high, out_low, out_high):
""" (number, number, number, number, number) -> float
Linear scaling. Scales old_value in the range (in_high - in-low) to a value
in the range (out_high - out_low). Returns the result.
>>> linear_scale(0.5, 0.0, 1.0, 0, 127)
63.5
""... | caeab8e992caca2dba96f48b0eb617fd361bb9eb | 47,381 |
import random
def meme_rand():
""" Generate a random meme """
img = random.choice(imgs)
quote = random.choice(quotes)
path = meme.make_meme(img, quote.body, quote.author)
return render_template('meme.html', path=path) | 02bff0fb08244eec61ecb10cd2f565d441a3b182 | 47,382 |
def magma_snrm2(n, dx, incx):
"""
Euclidean norm (2-norm) of vector.
"""
return _libmagma.magma_snrm2(n, int(dx), incx) | c10b482ef5e8353da9b85606946abd71b9dc9e0d | 47,383 |
def lowerCase(length: int = 1) -> str:
"""
returns random lowercase letter strings
:parameters:
length: defines the length of the character sequence
if length is not given, the function returns only a single character
"""
return "".join(choice(lowercase) for i in range(length)) | 1354d1d361e499b5338c27901bdd4a362a310f34 | 47,384 |
from typing import List
from typing import Dict
from typing import Tuple
def process_commits(
commits: List[CommitInfo],
check_merge_commits: bool,
) -> Dict[str, List[str]]:
"""
Process commit information to detect DCO infractions.
:param commits: the list of commit info
:param check_merge_c... | e1155e51f11bed54f53fd6c1e48162bd2729a57a | 47,385 |
from typing import Optional
def single_time_vis(channel: dict,
bt=0,
tt=0,
chart_type: Optional[str] = None,
enable_playback: bool = True,
height: int = 50,
params=None,
title: s... | 8291bbaee0b4679211b5f92e050bfb217ce1a30f | 47,386 |
def cart_contents(request):
"""
Ensures that the cart contents are available when rendering
every page
"""
cart = request.session.get('cart', {})
cart_items = []
total = 0
destination_count = 0
for id, quantity in cart.items():
destination = get_object_or_404(Destinations, p... | 03dd02318cf498005c5050d80eaac6f101175a7b | 47,388 |
from cp_documento import Documento
def main():
"""Funçao index"""
print('Init do main_route')
#window_id = str(get_window_id())
#print('1')
#set_base_context(window_id)
#print('2')
#ctx_dict = get_context(window_id)
ctx_dict = {'titulo':'Portal de Compras Públicas'}
resQueryDocLeis... | e7cba8d516a4f1f376e3092fb4df0b1547fb132d | 47,389 |
def lastweek_homes_avg():
""" Returns the average of homes we reached last week """
# find last week monday
# iter over tail checking dates
lastweek_monday = date.today() - timedelta(
6 + date.today().isoweekday() % 7)
homes = [0] * 7
for line in Popen(('tail', '-12', settings.DOMICILIOS... | 13344d11142306afaa9d966033821d4f3f1eb7b8 | 47,390 |
from sparktk.frame.frame import Frame
def top_k(self, column_name, k, weight_column=None):
"""
Most or least frequent column values.
Parameters
----------
:param column_name: (str) The column whose top (or bottom) K distinct values are to be calculated.
:param k: (int) Number of entries to r... | 2e196ebab45e42774bf45b25083689249084f250 | 47,391 |
def connect(server_name, aedt_client_port):
"""Connect to an existing aedt server session.
Parameters
----------
server_name : str
name of the remote machine to connect.
aedt_client_port : int
port on which rpyc_server is running inside AEDT
Returns
-------
rpyc object.... | 9804413d97271cde6eacf5e4bbd9ee9de6c92899 | 47,392 |
def _slice(iterable, pattern):
"""
a custom built slice method that can be used
inside jijna template enginer
:param iterable: string
:param pattern: string ex (::-1)
:return: string
"""
if iterable is None or isinstance(iterable, Undefined):
return iterable
# convert to lis... | be77930aeb4fa3edab306fa7fdb23e39f366810b | 47,393 |
import inspect
def inline_c_precompile(source):
"""Precompile C/C++ code and run it in-line"""
fr = inspect.currentframe().f_back
(lib, code) = _load_func(fr)
return _call_func(lib, code, fr) | 802befa0f8fb3ea903de1f954755526af8a501d7 | 47,394 |
def docs(node, manifest, config, column_name=None):
"""Return a function that will process `doc()` references in jinja, look
them up in the manifest, and return the appropriate block contents.
"""
current_project = config.project_name
def do_docs(*args):
if len(args) == 1:
doc_p... | 3504b572f02b37679e4b1d91f7a2b7b6cf9fa47c | 47,395 |
def Footer(*content, **attrs):
"""
Wrapper for footer tag
>>> Footer().render()
'<footer></footer>'
"""
return KWElement('footer', *content, **attrs) | cf13a602c246d918a3fda2fd5a6a24d8777a93e7 | 47,397 |
def dKT(counts, lower_quantile=0.25, upper_quantile=0.75):
"""
Parameters: 1-D array_like, int Vector of counts.
lower_quantile : float, optional
Lower bound of the interquantile range. Defaults to lower quartile.
upper_quantile : float, optional
Upper bound of the interquantile range. Defau... | c8b8bccbc164ce1cf5dde8761fe3c346077c79f9 | 47,399 |
def app_validate_batch(app_name_or_id, alias=None, input_params={}, always_retry=True, **kwargs):
"""
Invokes the /app-xxxx/validateBatch API method.
For more info, see: https://documentation.dnanexus.com/developer/api/running-analyses/apps#api-method-app-xxxx-yyyy-validatebatch
"""
fully_qualified... | 07ea5f856749e578d66f0138acf86d4a9f46ae7c | 47,400 |
import collections
def build_dataset(words, vocabulary_size=50000):
"""Returns:
data:
list of the same length as words, with each word replaced by a unique
numeric ID.
count:
counters for the vocabulary_size most common words in 'words'.
dictionary:
maps word->ID
r... | 149f72d18a1304fe4414a95ed1491a7e6bd6c4de | 47,401 |
def used_voltage_params():
"""
Returns a list of qdac voltage parameters for the used channels
"""
station = qc.Station.default
qdac = station['qdac']
chans = sorted(used_channels())
voltages = [qdac.channels[ii - 1] for ii in chans]
return voltages | 4fde688214c98ca92a9f6b640e484ac713c5f7b8 | 47,404 |
def get_config_files():
"""Get the config file for dataduct
Note:
The order of precedence is:
1. /etc/dataduct.cfg
2. ~/.dataduct/dataduct.cfg
3. DATADUCT_CONFIG_PATH environment variable, if it exists
Returns:
A list of file paths of dataduct config file locations,... | f043cbed27d3b49f50cb2c235931fdbdc49b5d27 | 47,405 |
from typing import Dict
from datetime import datetime
def make_epoch_log(seconds: float,
metric_data: Dict[str, AverageValueMeter],
epoch: int) -> str:
"""Create the log message basen on input parameters.
Args:
seconds (float): Time spent on train and valid epoch... | 23e3931133944ce2ec588180f4898a3fef4f32d2 | 47,406 |
def _error_matches_criteria(error, criteria):
"""
Check if an error matches a set of criteria.
Args:
error:
The error to check.
criteria:
A list of key value pairs to check for in the error.
Returns:
A boolean indicating if the provided error matches the... | 8f52f7288fdefa496084b4faf689ed269360050a | 47,407 |
import torch
def eval(device, model, datas, criterion):
"""Eval the model"""
losses = 0
model.eval()
with torch.no_grad():
for data, target in datas:
output = model(data.to(device)).flatten()
losses += criterion(output.flatten(), target.to(device)).item()
return los... | bf9d71640922e3c3a9d9bcd0fc83bc37f6c2da7d | 47,408 |
def find_first_link(content: str) -> Link:
"""Metin içerisindeki ilk bağlantıyı bulur
Arguments:
content {str} -- Metin
Returns:
Link -- Bulunan bağlantı objesi
Examles:
>>> find_first_link('[name1](path1) [name2](path2)')
Link(name='name1', path='path1')
"""
r... | 7b6b437b8ff407b0244b9c5f067b1d524e9eed9c | 47,409 |
import asyncio
def create_rfxtrx_tcp_dsmr_reader(host, port, dsmr_version,
telegram_callback, loop=None,
keep_alive_interval=None):
"""Creates a DSMR asyncio protocol coroutine using a RFXtrx TCP connection."""
if not loop:
loop = asy... | 18254fb10a422a9c63255a64832ad457dbf43651 | 47,410 |
from lifelines import KaplanMeierFitter
def find_mean_differential_survival(outcomes, interventions):
"""
Given outcomes and interventions, find the maximum restricted mean survival time
"""
treated_km = KaplanMeierFitter().fit(outcomes['uncensored time treated'].values, np.ones(len(outcomes)).astype... | 9d0fca74ec4ee8a8fbdd59e7a08f67e1ccd49f9e | 47,411 |
def check_if_git_is_installed():
"""Check if GIT is installed by calling 'git --version'."""
try:
git_version = check_output(["git", "--version"]).decode('utf-8')
if git_version.startswith("git version"):
return True
raise Exception('Git not installed')
except:
re... | 6702e1302c361954f557fec468b2d89e78c19fb1 | 47,413 |
import re
def pad_punctuation_w_space(text: str) -> str:
"""Pad punctuation marks with space for separate tokenization."""
result = re.sub(r'([:;"*.,!?()/\=-])', r" \1 ", text)
result = re.sub(r"[^a-zA-Z]", " ", result)
result = re.sub(r"\s{2,}", " ", result)
# code for removing single characters
... | 8bdb82865d5e127e32d483f83246f4ad1b96b0be | 47,415 |
from typing import Type
def get_fastx_flag_extractor(fmt: FastxFormats) -> Type[ABCFlagExtractor]:
"""Retrieves appropriate flag extractor class."""
if FastxFormats.FASTA == fmt:
return FastaFlagExtractor
elif FastxFormats.FASTQ == fmt:
return FastqFlagExtractor
else:
return AB... | 009698de417857cd9254527e74f6e7ac12eabad8 | 47,416 |
def tensors2classlist(tensor, seq_lens):
"""
Converts a 3d tensor (max(seq_len), batch_size, output_dim=1) to a 2d class list (list[batch_size * list[seq_len]])
Arguments:
tensor (torch.tensor) : 3d padded tensor of different sequence lengths of
shape (max(seq_lens), batch_size, output_... | 52de31050a32ce54b2733f4c4dd348044e3da259 | 47,418 |
def skippable_exons(exons):
""" Determine which exon(s) can be skipped
For each exon (except the first and second, which cannot be skipped), we
want to find the minimum number of exons which together have a size that
can be divided by 3.
>>> list(skippable_exons([30]))
[]
>>> list(skippable... | f96ec0da6d72191d252cfe0ba5cdbeb21bc4388c | 47,419 |
from typing import Callable
from typing import Any
def not_pf(predicate: Callable[[Any], bool]):
"""
Negates the predicate
* **predicate**: predicate to be tested
* **return**: a predicate that is the negation of the passed predicate
>>> p = not_pf(true_p)
>>> p(1)
False
>>> p = not_... | 50d3993c4a83e5794a63134b65c732d1aa0ca1fa | 47,420 |
def _ShouldSkip(commit_check, modified_lines, line, rule, test_class=False):
"""Returns whether an error on a given line should be skipped.
Args:
commit_check: Whether Checkstyle is being run on a specific commit.
modified_lines: A list of lines that has been modified.
line: The line that has a rule vi... | 7f7cd6410f6c8357d1cd465b11445cf49bd500b5 | 47,421 |
def monte_carlo(cycles, precision, concunique, bottom_temp_est, dp, por,
por_fit, seddepths, sedtimes, temp_d, bottom_temp, z,
advection, leg, site, solute_db, ds, por_error, conc_fit,
runtime_errors, line_fit):
"""
Monte Carlo simulation of flux_model output to f... | d7a435fd982f525b74ee05d377e9ee8a1f7eecda | 47,422 |
from typing import List
def getViewsAlias()->List[str]:
"""获取所有views.py的别名"""
obj = getEnvXmlObj()
return obj.get_childnode_lists('alias/file[name=views]') | 3dc5a38e44f8eef707beb9361fcbca8b16476b52 | 47,423 |
from typing import Optional
def get_logs(experiment_name: Optional[str] = None, save: bool = False) -> pd.DataFrame:
"""
Returns a table of experiment logs. Only works when ``log_experiment``
is True when initializing the ``setup`` function.
Example
-------
>>> from pycaret.datasets import ... | 6f1b55864361098ac9d5c8bd843d5405d59765ac | 47,424 |
def filter_genes(centroids):
"""returns genes that have std > 0"""
return centroids.index[(centroids.std(axis=1) != 0).tolist()] | fcfbd18b6d657d6758feb324642c4118b80aecfd | 47,425 |
def multivariate_t_logpdf(x, m, S, df=np.inf):
"""calculate log pdf for each value
Parameters
----------
x : array_like, shape=(n_samples, n_features)
m : array_like, shape=(n_features,)
S : array_like, shape=(n_features, n_features)
covariance matrix
df : int or float
de... | 8a53d603b6e91fbc2e74e5f444d024b38af38d23 | 47,426 |
def get_iou_score(class_weights=1., smooth=SMOOTH, per_image=True, threshold=None):
"""Change default parameters of IoU/Jaccard score
Args:
class_weights: 1. or list of class weights, len(weights) = C
smooth: value to avoid division by zero
per_image: if ``True``, metric is calculated a... | 03123ab38dad5ff1d8efaa44a0b4fd00cd3d47dd | 47,427 |
from typing import List
from typing import Tuple
def make_flfacts_mach_sweep(alt: float, machs: List[float], eas_limit: float=1000.,
alt_units: str='m',
velocity_units: str='m/s',
density_units: str='kg/m^3',
... | fd31ad68da7f5a3167457370e4e78ecda66235fd | 47,429 |
def create_rnn_numpy_batches(
array, batch_size=500, timesteps=TIMESTEPS, features=1, array_type="X"
):
"""Transform a numpy array, so that it can be fed into an RNN.
RNNs require all batches to be the exact same length. This function
removes excess elements from the array and so ensures all batches ar... | 5ba4d1c23fb1e9e2040e075a02d78f872545ef05 | 47,430 |
def nll_loss(input,
label,
weight=None,
ignore_index=-100,
reduction='mean',
name=None):
"""
This api returns negative log likelihood.
See more detail in :ref:`api_nn_loss_NLLLoss` .
Parameters:
input (Tensor): Input tensor, the ... | 2b22c63a2c3847bf259ff579782df0316ae7665d | 47,431 |
def image_to_string(
image,
lang=None,
config='',
nice=0,
output_type=Output.STRING,
timeout=0,
):
"""
Returns the result of a Tesseract OCR run on the provided image to string
"""
args = [image, 'txt', lang, config, nice, timeout]
return {
Output.BYTES: lambda: run_... | d2ccb74f2cc9dceb3036e234af4cc541f82255bf | 47,432 |
def organic_pdf_to_img(pdf_file, pdf_dim=None):
"""
Converts pdf file into image
:param pdf_file: path to the pdf file
:return: wand image object
"""
if not pdf_dim:
pdf_dim = get_pdf_dim(pdf_file)
page_width, page_height = pdf_dim
print('read pdf {}'.format(pdf_file))
# img ... | 3c355edc017d19662ed11647ba9f176272daa851 | 47,433 |
from typing import Dict
from typing import List
def list_keys(bucket: str, prefix: str, suffix: str, delta_to: Dict[str, str] = None) -> List[str]:
"""
Lists all the keys belonging to a give key prefix in object storage
:param bucket: The object storage bucket
:param prefix: The key prefix
:param ... | 9db7dfa842d721a6285b87a27448e5cdbfe88fee | 47,436 |
def info_panel_factory(db):
"""
Returns:
The factory class used to generate info panels for testing.
"""
return InfoPanelFactory | e43aa05f28d1ebead281f6caa5faf46a1b2b8b27 | 47,437 |
import numpy
def brier_score(survival_train, survival_test, estimate, times):
"""Estimate the time-dependent Brier score for right censored data.
The time-dependent Brier score is the mean squared error at time point :math:`t`:
.. math::
\\mathrm{BS}^c(t) = \\frac{1}{n} \\sum_{i=1}^n I(y_i \\le... | 02c4568451b054838b203ed037677f015a9a10b6 | 47,438 |
from operator import mul
def dot(A, B):
"""
Dot product between two arrays.
A -> n_dim = 1
B -> n_dim = 2
"""
arr = []
for i in range(len(B)):
if isinstance(A, dict):
val = sum([v * B[i][k] for k, v in A.items()])
else:
val = sum(map(mul, A, B[i]))
... | 9ea609f78e27eb3046507db3e366531090b26d6d | 47,439 |
def get_invocation_command(toolset, tool, user_provided_command = [],
additional_paths = [], path_last = False):
""" Same as get_invocation_command_nodefault, except that if no tool is found,
returns either the user-provided-command, if present, or the 'tool' parameter.
"""
... | 7fd76a04468de1764e234183f758640de00e6141 | 47,440 |
def decoding_layer(dec_input, encoder_state,
target_sequence_length, max_target_sequence_length,
rnn_size,
num_layers, target_vocab_to_int, target_vocab_size,
batch_size, keep_prob, decoding_embedding_size):
"""
Create decoding layer
... | 2d832771359c7af2443629f488b03aa386e0cbe5 | 47,441 |
def create_interaction(principal_id, **kw):
"""
Create a new interaction for the given principal ID, make it the
:func:`current interaction
<zope.security.management.newInteraction>`, and return the
:class:`Principal` object.
"""
principal = Principal(principal_id, **kw)
participation = ... | ef7c5eb7045e3504bdd00cc9420c1a0402c2bcce | 47,442 |
from datetime import datetime
import uuid
def python_type(type_description):
"""Return object representing the Python type.
Args:
type_description (str): Arc-style type description/code.
Returns:
Python object representing the type.
"""
instance = {
"date": datetime.datet... | 007367c9b7852c0d24c9bfddb8bf710afcd3f89f | 47,443 |
def openedx_extract_transform_factory(get_config):
"""
Factory for generating OpenEdx extract and transform functions based on the configuration
Args:
get_config (callable): callable to get configuration for the openedx backend
Returns:
OpenEdxExtractTransform: the generated extract an... | 73c1231fdcd6208f29af00d0a38aaafba59468e2 | 47,444 |
def _mint(challenge, bits):
"""Answer a 'generalized hashcash' challenge'
Hashcash requires stamps of form 'ver:bits:date:res:ext:rand:counter'
This internal function accepts a generalized prefix 'challenge',
and returns only a suffix that produces the requested SHA leading zeros.
NOTE: Number of ... | 691631769f09413b8257a92c7831ab8953bbcb6b | 47,445 |
def product(A, B, p_name):
""" Computes the product automaton of two DFAs.
Args
----
A, B : variables referencing a DFA.
p_name : name of the product automaton.
Returns
-------
An DFA which is a product automaton of input DFA or A and B with name "p_name".
Testable Code
... | 3dd06d21f3659c2c17c270a729d9a1fa751902a5 | 47,446 |
def load_data(dataset_str):
"""
Loads input data from gcn/data directory
ind.dataset_str.x => the feature vectors of the training instances as scipy.sparse.csr.csr_matrix object;
ind.dataset_str.tx => the feature vectors of the test instances as scipy.sparse.csr.csr_matrix object;
ind.dataset_str.al... | 4611a50d4d7fde4659b766ce13d1363e35fcdc8c | 47,447 |
from typing import OrderedDict
def dense_video_sampling(videos, annotations=None, bckg_label=201, t_res=16,
t_stride=16, drop_video=True):
"""Sample clips to extract C3D.
Parameters
----------
videos : pandas.DataFrame
Table with info about videos in dataset i.e. uniq... | 7bb9d4ae4de3868e63b5ad2afc308c026f98dd28 | 47,448 |
def IsImage(a):
"""Return if the object is of Image type.
Args:
a: object whose type needs to be checked
Returns:
True if |a| is of Image type, False otherwise
"""
return isinstance(a, Image) | fe43e6ef7d25d0f7e470507540d10a1e935beacb | 47,450 |
def upload_to_object_store(
client,
bucket,
full_path_to_filename,
object_name=None,
content_type="binary/octet-stream",
):
"""Uploads the specified file to the object store
Parameters:
client: str, the boto3 client object
bucket: str, target bucket location
full_pat... | 1652a69341664e8cfa5b5e32787808f9022004e8 | 47,451 |
def set_autocommit(autocommit, using=None):
"""Set the autocommit status of the connection."""
return get_connection(using).set_autocommit(autocommit) | 792cb38ec8f31b3390489742dceef67bc52dc70f | 47,452 |
def get_frame_size(*args):
"""get_frame_size(func_t pfn) -> asize_t"""
return _idaapi.get_frame_size(*args) | a5e08be1463e808107e84fce1f1c049b7815a424 | 47,454 |
from operator import index
def z_decode(p):
"""
调用方式,
while p:
v,p=z_decode(p) #v:值 p:bytes(每次z_decode计算偏移量)
params = v
递归地取字符串p,每次取一些到v,剩下的更新为p,继续迭代
decode php param from string to python 根据php serialize
p: str
"""
#print(p)
if p[0]=='N': #NULL 0x4e-'N'
return None,p[2:]
elif p[0]=='b':... | 1038dcf8a356e53574fb6eab6a9842bec78a5db6 | 47,455 |
def scaling_aligned_one_dim_cascade(
time,
x,
y,
z,
track_azimuth,
track_zenith,
):
"""Cascade with topology defined by a cascade at `SCALING_CASCADE_ENERGY`,
and changing energy only modifies number of photons produced"""
return aligned_one_dim_cascade(
time=time,
x=... | 81d6e23a6c3bd7308a32c24311db47a063df7e81 | 47,456 |
def GetParsedDeps(deps_file):
"""Returns the full parsed DEPS file dictionary, and merged deps.
Arguments:
deps_file: Path to the .DEPS.git file.
Returns:
An (x,y) tuple. x is a dictionary containing the contents of the DEPS file,
and y is a dictionary containing the result of merging unix and comm... | cfa7c4dd3134b131063e4cf288be730fd93b0c19 | 47,457 |
def _parse_option(line):
"""
Parses option line.
Returns (name, value).
Raises ValueError on invalid syntax or unknown option.
"""
match = _OPTION_REGEX.match(line)
if not match:
raise ValueError('Invalid syntax')
for name, type_ in _OPTIONS:
if name == match.group(1):
... | bf8f7e71c2a5d0ed61fdbecb8f8ac033e8771c43 | 47,458 |
def convert(from_unit, to_unit, *args, **kwargs):
"""
Convert the value from one unit to another
:param from_unit: Source unit
:param to_unit: Target unit
:param args: Additional parameters (values)
:param kwargs: Additional parameters (additional values like for conversion watts to ohms)
:r... | 233c16fda7943ae15093a8e455f6634bd75bbd4a | 47,459 |
def hex_validator(length=0):
"""
Returns a function to be used as a model validator for a hex-encoded
CharField. This is useful for secret keys of all kinds::
def key_validator(value):
return hex_validator(20)(value)
key = models.CharField(max_length=40, validators=[key_validat... | 6ab272ab19f3b801ec612309ab41c845154a1eae | 47,460 |
def bytes_feature(value):
"""Create a multi-valued bytes feature from a single value."""
return tf.train.Feature(bytes_list=tf.train.BytesList(value=[value])) | f3b7ec25baca436fae7851fecbcd29787e6cc639 | 47,461 |
def mkmatrix(m, n):
"""
Return a random invalid correlation matrix of order `m+n` with
a positive definite top left block of order `m`.
"""
while True:
A = randcorr(m)
#B = randcorr(n)
B = np.identity(n)
Y = np.matrix(np.random.randn(m, n) / (m+n)**1.2)
M0 = ... | a8d45f0b99adc08b43ca3a5f4c740edaab1e95de | 47,463 |
def remove_last_range(some_list):
"""
Returns a given list with its last range removed.
list -> list
"""
return some_list[:-1] | ea2063c901d3aaf67caad97f1760f6fb6afb31c1 | 47,464 |
import torch
def lazy_bind(concrete_type, unbound_method):
"""
Returns a function that lazily binds `unbound_method` to a provided
Module IValue, then invokes the method. We do this so that any Python
shenanigans that will poison type sharing are impossible at compile
time.
"""
def lazy_bi... | 2d483782772bd1d4dc8b81dd621bc029d5876c38 | 47,465 |
from typing import Optional
from typing import Dict
from typing import Any
from typing import cast
def require_dict(value: Optional[Dict[Any, Any]], key_type: Any=None, value_type: Any=None,
allow_none: bool=False) -> Any:
"""Make sure a value is a Dict[key_type, value_type].
Used when deali... | 31611fa58de5a09b4bf9833cf22be1e151df00df | 47,467 |
def reconstructTimestamp(currentTimestamp, lsbTimestamp):
"""
Reconstructs a timestamp from a partial timestamp, that only has the least significant bytes.
:param currentTimestamp: Current time, obtained with time.time().
:param lsbTimestamp: Partial (least significant) timestamp, as a uint16.
:retu... | df8836b3e849051fe62b8d2105fd46f9c1211bc1 | 47,468 |
def get_date_print_format(date_filter):
"""
Utility for returning the date format for a given date filter in human readable format
@param date filter : the given date filter
@return the date format for a given filter
"""
vals = {
'day': '[YYYY-MM-DD]',
'hour': '[YYYY-MM-DD : HH]'
}
return vals[date_filter] | a7b15f944905c44c6bff1ed65514fdb0133d150b | 47,469 |
def pre_submission(*args, **kwargs):
"""
Perform a presubmit of a list of local files. This is the first
stage for a batch submit of files.
Variables:
None
Arguments:
None
Data Block (REQUIRED):
{
"1": # File ID
{"sh... | fa68404d833145a3a44fe1a0dd1be09fd1b3cbb9 | 47,471 |
from typing import List
def _historical_user_data_for_decisions(user: User, days: int) -> List:
"""
Return public data regarding the clicked Statements for a certain user
:param days: The number of days ending with today for which the data shall be procured.
:param user: The user for which the data s... | 6536c474fa90a388cf2d599c5e147017dfe62427 | 47,472 |
def collapse_locations(obj_list, keyname):
"""
Given a CustomQuerySet object, filter/aggregate it down
so we just have one item per country or city.
keyname is 'country' or 'city'.
Also drop the 'privacy_country' or 'privacy_city' field.
On input, we might have:
country privacy_coun... | 75586dc7fbd180ff6db031a0a706ea2221ced387 | 47,474 |
def updateHand(hand, word):
"""
Assumes that 'hand' has all the letters in word.
In other words, this assumes that however many times
a letter appears in 'word', 'hand' has at least as
many of that letter in it.
Updates the hand: uses up the letters in the given word
and returns the new ha... | 767aec56bec10900a3ccd67e2772355baf7886d0 | 47,475 |
def filter_by_indices(good_indices, vals):
""" 从分段算法得到的下标集合中得到 对应的轨迹点集合
:param good_indices: 下标集合
:param vals: 原始点数据(未分段) 集合
:return: 分段后的点集合
"""
vals_iter = iter(vals)
good_indices_iter = iter(good_indices)
out_vals = []
num_vals = 0
for i in good_indices_iter:
if i != ... | c38dd76a90452cdbe96c92c8850752f56cc9882f | 47,477 |
def transform_tabular_data(xml_input):
"""
Converts table data (xml) from BambooHR into a dictionary with employee
id as key and a list of dictionaries.
Each field is a dict with the id as the key and inner text as the value
e.g.
<table>
<row id="321" employeeId="123">
... | 025831e3192a9a7ce6b8130b76e4e1bf827a1744 | 47,479 |
def create_workflow(name=None, namespace=None, bucket=None, **kwargs): # pylint: disable=too-many-statements
"""Create workflow returns an Argo workflow to test kfctl upgrades.
Args:
name: Name to give to the workflow. This can also be used to name things
associated with the workflow.
"""
builder = B... | 62e967e6e767fbdbfd3aec1151dc1213fe95212d | 47,481 |
def create_annotation_model(table_name: str,
annotation_columns: dict,
with_crud_columns: bool=True):
""" Create an declarative sqlalchemy annotation model.
Parameters
----------
table_name : str
Specified table_name.
annotation_colum... | c33af504cc921537474574a8f30948b772498ce4 | 47,482 |
def speed_control(target, current, Kp=1.0):
"""
Proportional control for the speed.
:param target: target speed (m/s)
:param current: current speed (m/s)
:param Kp: speed proportional gain
:return: controller output (m/ss)
"""
return Kp * (target - current) | ce01369dc9445f65249a82cfb7882223ded38f36 | 47,483 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.