content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def _check_is_max_context(doc_spans, cur_span_index, position):
"""Check if this is the 'max context' doc span for the token."""
# Because of the sliding window approach taken to scoring documents, a single
# token can appear in multiple documents. E.g.
# Doc: the man went to the store and bought a ga... | e909ccc4e4a926a3059cd2beb960530db43f8235 | 3,604,187 |
def file_and_extension(path: str):
"""return filename and their extension."""
filename = path.split('/')[-1].split('.')[:-1][0]
extension = path.split('.')[-1][0]
return filename, extension | 0b2ccae4ac054330e9b99b80ef6a657dd08d97ed | 3,604,189 |
def input_details(interpreter, key):
"""Returns input details by specified key."""
return interpreter.get_input_details()[0][key] | b06bd5278fcc5d95da387cb506ac9b9f443d9f27 | 3,604,191 |
from typing import Union
from typing import Sequence
def _get_noise_shape(
x: tf.Tensor, noise_shape: Union[Sequence[int], tf.TensorShape]
) -> Union[tf.Tensor, tf.TensorShape, Sequence[int]]:
"""Computes the shape of the binary mask for dropout."""
# If noise_shape is none return immediately.
if noise_shap... | 3788e83ea9ad755eca777bcca79746b53102d10c | 3,604,192 |
def spread_to_trimesh(spread, cutoff):
"""Convert levelset to mesh by way of binary"""
return binary_to_trimesh(spread_to_binary(spread, cutoff)) | e7d4420af0850f643cfc6bfffafeac728ba4d429 | 3,604,193 |
def gauss_discrete(r0, i, j, w_s): # pragma: no cover
"""
2D gauss function with a discrete center position
"""
i -= w_s // 2
j -= w_s // 2
A = 1. / (np.sqrt(np.pi) * r0)
return A * np.exp(-(i ** 2 + j ** 2) / r0 ** 2) | f80484de44e4897810f1b50f986ba852dca11911 | 3,604,194 |
import torch
def add_edge(adj, node1, node2):
"""return a new adjacency matrix that inserts a symmetric edge between node1 and node2"""
num_nodes, _ = adj.sizes()
edge_index = torch.tensor([[node1, node2],
[node2, node1]])
new_edge = SparseTensor(row=edge_index[0], col=e... | 6713b066fcb539ea64969c91bcc5b842bb363248 | 3,604,196 |
def approxEntropy(N: int, p: float, r: int) -> float:
"""
Xét dãy H_{N} = (-Pr(r) log Pr(r)) + (-Pr(r+1) log Pr(r+1)) + ... + (-Pr(N) log Pr(N))
H_{N} là một dãy dương, tăng và có giới hạn là entropy của biến ngẫu nhiên nhị thức âm
Do đó khi N càng lớn, hàm approxEntropy sẽ tiến đến entropy của biến ngẫ... | e967684e5892de86e58182c87c83fc61e302ea86 | 3,604,197 |
import io
def read_item_names():
"""Read the u.item file from MovieLens 100-k dataset and return two
mappings to convert raw ids into movie names and movie names into raw ids.
"""
file_name = get_dataset_dir() + '/ml-100k/ml-100k/u.item'
rid_to_name = {}
name_to_rid = {}
with io.open(file... | 88c030e411ec832d9e958a9704bd99cddfa42074 | 3,604,198 |
def ds_point_plot(df, x, y, cmap='#1f77b4', plot_height=300, plot_width=500,
x_axis_label=None, y_axis_label=None, title=None,
margin=0.02):
"""
Make a datashaded point plot.
Parameters
----------
df : pandas DataFrame
DataFrame containing the data
x ... | 4c3cd39dd38fdeea50c508636108e5ae2c6525f3 | 3,604,199 |
def get_veff(ks, cell=None, dm=None, dm_last=0, vhf_last=0, hermi=1,
kpts=None, kpts_band=None):
"""
Coulomb + XC functional + (Hubbard - double counting) for KUKSpU.
"""
if cell is None: cell = ks.cell
if dm is None: dm = ks.make_rdm1()
if kpts is None: kpts = ks.kpts
# J + V_... | 63f5e1bbb82268ca6fde2696ccfd8edcb73d069d | 3,604,202 |
def gt_measure(disparity, gt):
"""
computes the recall of the disparity map
:param disparity: disparity image
:param gt: ground-truth image
:return: rate of correct predictions
"""
correct = np.count_nonzero(np.abs(disparity - gt) <= 3)
return float(correct) / gt.size | 7c3b2eb977f1a60be521ed28801719f4c494658c | 3,604,203 |
def parse_post(html_string):
""" Parses HTML content of a posting and returns a Post namedtuple
"""
root = lxml.html.fromstring(html_string)
post_url = root.xpath("//link[@rel='canonical']/@href")
price = root.xpath("//span[@class='price']/text()")
title = root.xpath("//span[@id='titletextonly']... | a3b0e0d2665d61f4d94af32c3af34770fc9a4a4c | 3,604,204 |
def is_single_ma_sell(kline, p=5, max_distant=0.1):
"""单均线卖点"""
kline = ma(kline, params=(p,))
ma_col = "ma%i" % p
kline['d'] = kline[ma_col].diff(1)
b = False
detail = {
"标的代码": kline.iloc[0]['symbol'],
"操作提示": "单均线卖",
"出现时间": kline.iloc[-1]['dt'],
"基准价格": kline... | 9d3d623070231ae53a13838201dcbadb8d999dcc | 3,604,205 |
def format_date( date_obj ): # date_obj is a datetime.date object
"""Returns a formatted date string given a date object. If the day is
the first of the month, then the day is dropped, eg:
format_date ( datetime.date(2013, 04, 12)) returns 2013-04-12
format_date ( datetime.date(2013, 4, 1)) r... | bfcddc9cbd4228084a0a4c5e6736be28a90d520e | 3,604,206 |
def comac(Psi_1, Psi_2, dof):
"""Co-modal assurance criterion
"""
comac = 1
return comac | 07b2de7e5034c5d0bf3db3a2b59fabd5a26129da | 3,604,207 |
def cosh(x):
"""
cosh(x) -> number
Return the hyperbolic cosine of x.
"""
try:
res, x = _init_check_mpfr(x)
gmp.mpfr_cosh(res, x, gmp.MPFR_RNDN)
return mpfr._from_c_mpfr(res)
except TypeError:
res, x = _init_check_mpc(x)
gmp.mpc_cosh(res, x, gmp.MPC_RNDNN... | b36e0e62bc526f2f545aef7bb0227aeb76d62f13 | 3,604,208 |
def fulfill_transaction(transaction, *, private_keys):
"""
Fulfills the given transaction.
Args:
transaction (dict): The transaction to be fulfilled.
private_keys (:obj:`str` | :obj:`list` | :obj:`tuple`): One or
more private keys to be used for fulfilling the
transa... | c74d30eb1c246bbdc5230bb3e691dfe2e842f2fd | 3,604,209 |
import time
def render_one(seq_to_render, ith, checkers, generation, global_lock):
""" Render the specified sequence.
@param seq_to_render: The sequence to render.
@type seq_to_render: Sequence
@param ith: The position of the target sequence (to be rendered) in the
sequence colle... | 1aa0a69dc3009f4394e1b9668bea58a8ae6e83d7 | 3,604,210 |
def get_streamline_statistics(streamlines, subsample=False, raw=False):
"""
Get streamlines statistics in mm
Args:
streamlines: list of streamlines
subsample: Do not evaluate all points to increase runtime
raw: if True returns list of fibers length and spaces
Returns:
(... | fdd44977c5f1d5411c47e96a05e51102528f4b7f | 3,604,212 |
from typing import Dict
from typing import Any
def _make_pod_podannotations() -> Dict[str, Any]:
"""Generate pod annotation.
Returns:
Dict[str, Any]: pod annotations.
"""
annot = {
"annotations": {
"k8s.v1.cni.cncf.io/networks": '[\n{\n"name" : "internet-network",'
... | 94ab8b66c5cf63546f15cb8fef6e1fbc4aa3cb49 | 3,604,214 |
def extract_conn_tags(connection):
""" Transform kombu conn info into dogtrace metas """
try:
host, port = connection.host.split(":")
return {
net.TARGET_HOST: host,
net.TARGET_PORT: port,
kombux.VHOST: connection.virtual_host,
}
except AttributeEr... | 4c22237725fc504ff2f4c9aef0045ce0493994b0 | 3,604,215 |
import copy
def get_formula_type(formula):
"""
Returns the type of formula.
:param formula: str, the content of formula
:return: FormulaType, representing the type of given formula.
"""
formula = copy(formula).split(' ')
if len(formula) == 3:
if formula[1] == '=':
retu... | 4910ab8f7f7097d1d52925f95f856ee4d40079bc | 3,604,216 |
from typing import Dict
def get_devices_conn_params() -> Dict[str, Dict[str, str]]:
"""Creates a dictionary of connection parameters for SSH"""
result: Dict[str, Dict[str, str]] = {}
yaml = YAML()
with open(HOSTS_FILE, 'r') as f:
hosts = yaml.load(f)
for device, device_details in hosts["de... | 43332053b3eabbcaecc0542398d10b05f488e5d6 | 3,604,217 |
from datetime import datetime
def parse_date(value):
"""Parses a string(ISO_8601) and return a datetime.date.
Raises ValueError if the input is well formatted but not a valid date.
Returns None if the input isn't well formatted.
"""
match = date_re.match(value)
if match:
kw = {k: int(... | 1610e8cd06b1586c2a439395f54e9a863133726d | 3,604,218 |
from datetime import datetime
def get_num_batch(file_list, infer=False):
""" Get number of bacthes. """
data_list = read_list(file_list)
counter = 0
with tf.Graph().as_default():
if not infer:
_, inputs, labels, \
lengths = get_padded_batch(data_list,
... | 6573d5eb55fb7e05b2fcd419ec9a023393d78cce | 3,604,219 |
def _tile_images(imgs, tile_shape, concatenated_image):
"""Concatenate images whose sizes are same.
@param imgs: image list which should be concatenated
@param tile_shape: shape for which images should be concatenated
@param concatenated_image: returned image.
if it is None, new image will be c... | 39c76f2b568121aeaac14756656dd06dfc5d1cc6 | 3,604,220 |
def image_to_integers(data):
"""Convert image to one dimensional array of integers
Uses vectorization to speed up calculations."""
# Flatten pixels to one dimensional array
data = data.reshape(-1, data.shape[-1])
# Binary shift of RGB data to convert to integers
red = np.left_shift(data[:, 0],... | a2f29d8d72bcb4bae201f6cce0d9f5a4cf12bf7d | 3,604,221 |
def declare_out_files(ctx, protos, out_file_format):
"""derive and declare output files from protos
Args:
ctx: rule context
protos: list of proto `File`s
out_file_format: starlark format string
Returns:
list of declared files
"""
declared_files = []
for proto in ... | a2ace7486d4c182cb69a001a208b943515716177 | 3,604,222 |
import pickle
def _load(py_container, h_group):
""" Load a hickle file
Recursive funnction to load hdf5 data into a PyContainer()
Args:
py_container (PyContainer): Python container to load data into
h_group (h5 group or dataset): h5py object, group or dataset, to spider
and l... | abc46322149b8f250ce94668314ffea2a8091aed | 3,604,224 |
def tfNamespaceWeight(func):
""" TensorBoard namespace scope and summary for Weight values."""
@wraps(func)
def wrapper(*args, **kwargs):
with tf.name_scope(func.__name__):
#print func.__name__
ret = func(*args, **kwargs)
tf.summary.histogram('Weight', ret)
... | 404a8fc8e9e858a2b908495c8cf2a1f9329e3e4a | 3,604,225 |
def detect_motion_blur(image, ratio=2, band=None):
"""
Detect if an image is blurry due to movement, and therefore unreliable
to analyze. Uses the variance of the prewitt edge detectors in the horizontal and vertical directions.
Parameters
----------
image : ndarray
rgb or grayscale ima... | 23488f30f79be99b6285c6fc31e6617a421c6dd3 | 3,604,226 |
def create_searcher(
search_alg,
**kwargs,
):
"""Instantiate a search algorithm based on the given string.
This is useful for swapping between different search algorithms.
Args:
search_alg (str): The search algorithm to use.
metric (str): The training result objective value... | 89b663180b61207b001b1c62b46f3544b0bd3095 | 3,604,227 |
def get_mean(list):
"""Calc the mean from a list of numbers
Args:
list: The list from where the calc will be done
Returns:
Return the mean from a list of numbers
"""
return get_sum(list)/len(list) | 05f19aaf1c9963af4eb16cc0236e11dba4e057c1 | 3,604,228 |
def pdvgg19_bn(pretrained=False, **kwargs):
"""VGG 19-layer model (configuration 'E') with batch normalization
Args:
pretrained (bool): If True, returns a model pre-trained on ImageNet
"""
if pretrained:
kwargs['init_weights'] = False
model = PDVGG(make_layers_pd(cfg['E'], batch_nor... | 68c6114424290b88dc697819c7a19bfbcba22f94 | 3,604,229 |
def collect_edi_listings(exchanges=None):
"""
Collect securities listings from EDI and store in securities master
database.
Parameters
----------
exchanges : list or str, required
collect listings for these exchanges (identified by MICs)
Returns
-------
dict
status ... | f2234064e996797a9b34ef6512ee95b8909cac94 | 3,604,230 |
def get_lambda_cost(df: pd.DataFrame, MB_per_request=128, ms_per_req=200):
""" Given a Dataframe with requests per time unit, calculates the AWS
Lambda costs for each row.
Args:
df (pandas.Dataframe): Dataframe with requests for each time unit per
row.
MB_per_request (in... | ccc160866f84f18982aa9d68bf5d6326660ffaaf | 3,604,231 |
import tensorflow as tf
def load_vocab(vocab_file):
"""Loads a vocabulary file into a dictionary."""
try:
with tf.gfile.GFile(vocab_file, "r") as reader:
return token_vocab_build(reader)
except ImportError:
with open(vocab_file, "r", encoding='utf-8') as reader:
re... | 618953a13996436e5c156ad90da93b4f62ba765f | 3,604,232 |
import re
def extract_ref_variant_info(ref, line, amplicon_min_depth=0):
"""
Extract reference variant information from a jSNPmania variations file.
:param ref: (dict) that will be populated with reference information, must already
contain keys for the expected NC numbers, ex {'NC... | 7fb0b3db3a7cdc85b7fc9b79906b0d9f7b20a7f9 | 3,604,233 |
def getPPSA3(ChargeSA):
"""The calculation of atom charge weighted positive surface ares
It is the sum of the products of atomic solvent-accessible
surface area and partial charges over all positively charges atoms.
-->PPSA3"""
res=0.0
for i in ChargeSA:
if float(i[1])>0:
re... | e536124fa137969fa8171c56a1c25fcfdebfdfe6 | 3,604,234 |
from bs4 import BeautifulSoup
def read_lime_questionnaire_structure(filepath: str) -> dict[str, list[dict]]:
"""Read LimeSurvey XML structure file
Args:
filepath (str): Path to the XML structure file
Returns:
dict[str, list[dict]]: A dictionary
{
"sections": [...] - l... | 6ac350512daa879389cfea7020ae6cb2a9528584 | 3,604,235 |
def make_pointer_int_pair_printer(val):
"""Factory for an llvm::PointerIntPair printer."""
pointer, value = get_pointer_int_pair(val)
if not pointer or not value:
return None
pointer_type = val.type.template_argument(0)
value_type = val.type.template_argument(2)
string = 'llvm::PointerIntPair<%s>' % poi... | 6720b11c5582e926243ef0dc3408d02cfba4c9b6 | 3,604,236 |
def generateOperations(initial):
"""
Generates all possible operations for some state
:param initial: State
:return: list of operations
"""
operations = list()
s = State()
properties = s.generateStates()
elements = ['banana', 'monkey', 'box']
movement = ['Up', 'Down']
positi... | 87fb5565cde4169ad43a9542279b0a8f96952aaf | 3,604,237 |
def unravel_coeffs(arr, coeff_slices, coeff_shapes, output_format='wavedecn'):
"""Unravel a raveled array of multilevel wavelet coefficients.
Parameters
----------
arr : array-like
An array containing all wavelet coefficients. This should have been
generated by applying `ravel_coeffs` t... | fb2f7efc0e4b5866b9a03185e7546660e69697e7 | 3,604,238 |
def verify_email(user_id, token):
""" When visited with a valid `user_id` and `token` combination,
the user's mailaddress is marked as 'verified'. The person
responsible for approving accounts will recieve an email about the
new registration with a link to approve the account."""
user = db.session.... | b7b012fb100fd87ac3c343c3be0b27a81c3969dc | 3,604,239 |
def uintersect1d(arr1, arr2, assume_unique=False):
"""Find the sorted unique elements of the two input arrays.
A wrapper around numpy.intersect1d that preserves units. All input arrays
must have the same units. See the documentation of numpy.intersect1d for
full details.
Examples
--------
... | 7ebf5fc2df516568f7224eeb3728a46b9cfd9a4c | 3,604,240 |
def call(*args, **kw):
"""Convenience wrapper for calling run.
Positional arguments are converted to a list and given to run as
an argument. Keyword arguments are passed as is to run.
>>> call('echo','-n','foo')
[0, 'foo', '']
>>> call('exit 1', shell=True)
[1, '', '']
"""
return r... | 596735af50b000a3808398d6f93a68c51fb75753 | 3,604,241 |
def get_procs(name, user=None):
"""
Return a list of (pid, cmdline) tuples of process with name.
:param `name`: process name
:param `user`: user name (default from getpass). Option: 'all_users': get
all processes
"""
user_processes = get_user_process_info(user=user)
procs = [(p["pid... | c36c97453b16eb499c792615676b6a32d6cf5b6a | 3,604,242 |
def merge_result(docker_list: dict, result_dict: dict = {}, max_entries_per_docker: int = 5) -> dict:
"""Returns a python dict of the merge result
Args:
:type docker_list: ``dict``
:param docker_list: dictionary representation for the docker image used by integration or script
:type re... | 7cfd2708e15eb65c09e32cf0c08a360f780aacb8 | 3,604,243 |
def guess_format(path):
"""wrap guess_format with custom files"""
return util.guess_format(path, SUFFIX_FORMAT_MAP) | b4ef96f9cedc0f6479b0c9ca95503c435429d306 | 3,604,244 |
def genesis_state(base_genesis_state, simple_contract_address):
"""
Includes runtime bytecode of compiled Solidity:
pragma solidity ^0.4.24;
contract GetValues {
function getMeaningOfLife() public pure returns (uint256) {
return 42;
}
functio... | 77acbb0dbba808a96401649adfc18fd28247907e | 3,604,245 |
from typing import Iterator
from typing import Tuple
def named_children(self, prop:str=None) -> Iterator[Tuple[str, ModuleSelector]]:
"""Get all named direct childs.
:param prop: Filter property. See also: :meth:`__contains__`"""
if prop is None: return self._children.items()
return ((k, v) for k, v in s... | d026fabd5ef2c6499adf66dc8f06a1d739eb9119 | 3,604,246 |
def check(sudoku_part):
"""
fukcja do sprawdzania czy dana linia lub kwadrat nie posiadaja wiecej niz 1 takiej samej wartosci
"""
is_okey = True
for i in range(1,9):
count = sum([element for element in sudoku_part if element == i])
if count > 1:
is_okey = False
... | e93bd53127ea2f280ed123d2de0a18d2a18a1f0a | 3,604,247 |
def allgather(tensor, name=None):
"""An op which concatenates the input tensor with the same input tensor on
all other Horovod processes.
The concatenation is done on the first dimension, so the input tensors on the
different processes must have the same rank and shape, except for the first
dimension, which ... | 53232e5aabbad5bc3359e4900e2cc26937cdd3a3 | 3,604,248 |
from bs4 import BeautifulSoup
import requests
def _search_anything(query):
"""search input words at SNPedia, return and compare related genotypes and yours"""
snpedia_query = "https://www.snpedia.com/index.php/" + query
soup = BeautifulSoup(requests.get(snpedia_query).content, "lxml")
links = soup.fin... | 384a15c28676c12d98b150851eb0abd5188908bd | 3,604,249 |
import torch
def gaussian_parameters(h, dim=-1):
"""
Converts generic real-valued representations into mean and variance
parameters of a Gaussian distribution
Args:
h: tensor: (batch, ..., dim, ...): Arbitrary tensor
dim: int: (): Dimension along which to split the tensor for mean and
... | f749ca498696c92a1a0f6d1898fd689f52554dc9 | 3,604,250 |
def doByte(chars, i, littleendian, esc=True):
"""
Convert two chars[i] and chars[i+1] into a byte.
@return a tuple (byte, 2)
"""
c1 = '0123456789ABCDEF'.find(chars[i].upper())
c2 = '0123456789ABCDEF'.find(chars[i + 1].upper())
buf = cStringIO()
if (c1 < 0 or c2 < 0):
raise Excep... | 112c266fbf47da0cf776d66556f617e22f1ace54 | 3,604,251 |
def get_viewport_min_width() -> int:
"""Gets the viewport's minimum width.
Returns:
int
"""
return internal_dpg.get_viewport_configuration()["min_width"] | 615d72d347bb8e717f1eec6f11e24d731b6ed9fe | 3,604,252 |
def patch_role(*, role_name: str, update_mask: UpdateMask = None) -> APIResponse:
"""Update a role"""
appbuilder = current_app.appbuilder
security_manager = appbuilder.sm
body = request.json
try:
data = role_schema.load(body)
except ValidationError as err:
raise BadRequest(detail... | 5a116ca2215cbdad7342b629b92abb46820aaac4 | 3,604,253 |
def _give_random_idx(r_unique, n):
""" asd """
r = np.random.randint(n,
size=np.random.randint(low=1, high=n))
r_tuple = tuple(r)
if r_tuple not in r_unique:
r_unique.add(r_tuple)
return np.unique(r)
return _give_random_idx(r_unique, n) | c56088884c2e1e793999d5a75dd1bb1284fc9289 | 3,604,254 |
def name(lti):
"""
Access route with 'initial' request.
:param lti: `lti` object
:return: string "hi"
"""
return lti.name | 388af21bf4ea6b47f41f9cd036fa99422f410e44 | 3,604,256 |
from typing import List
def basic_verification(latest_results: List[datastore.Result], include_logs=True):
"""Create error strings for each errored result.
Format:
* {type}: {error}
Args:
latest_results (List[Result]): List of results to generate errors for
Returns:
List[str]: L... | 3e0e85908e0e0990771f9684e5c9ad95895e9e8c | 3,604,258 |
import ast
def godot_data(input):
"""
Simply clean the list and remove all unnecessary special characters and deliver with name, xyz only
"""
data = ast.literal_eval(input)
dict_with_updated_name = {}
dict_with_updated_name["data"] = dict()
dict_with_updated_name["data"]["direct_stimulatio... | b3c4766de948a2fcf66b602559e53005fd980bcb | 3,604,259 |
def predict(w, b, X_new):
"""
Prediction for new data
:param w: optimized weight
:param b: optimized b
:param X_new: new samples
:param Y_new_true: true value for new samples
:return: predicted result after checking of threshold value
"""
m = X_new.shape[1]
result = np.zeros((1,... | 17751a20f3781b50d4363ad22ffcb75f2cdc7f15 | 3,604,261 |
def _major_minor(version):
"""Given a string of the form ``X.Y.Z``, returns ``X.Y``."""
return ".".join(version.split(".")[:2]) | 8ca52bd0324bb0445ab3c5b9b44124c0f627f635 | 3,604,262 |
def prepare_sponsor_data(euctr_cond):
"""prepare the sponsor data that we will join in later"""
spon_cols = ['eudract_number', 'eudract_number_with_country', 'sponsors']
euctr_spon = euctr_cond[spon_cols].reset_index(drop=True)
s = euctr_spon['sponsors']
# concat had sort=False in Nick's original v... | c82308e33056c5895d855af44f693459ec2da22b | 3,604,263 |
def LocationAttributeConfig():
"""Creates the location resource attribute."""
return concepts.ResourceParameterAttributeConfig(
name='region',
parameter_name='locationsId',
fallthroughs=[
deps.PropertyFallthrough(properties.FromString('deploy/region'))
],
help_text='The Cloud... | 8923247d61951561e0ec8c78d621b86e0ffe0cd1 | 3,604,264 |
from typing import Union
from typing import List
def vgg_const(
x_tens: tf_compat.Tensor,
training: Union[bool, tf_compat.Tensor],
sec_settings: List[VGGSection],
num_classes: int,
class_type: str,
kernel_initializer,
bias_initializer,
beta_initializer,
gamma_initializer,
) -> tf_c... | b5bc37bca32e0ae27dbb4c7aada91516be40192c | 3,604,265 |
def get_tags(request):
"""
返回对应标签下的所以博客
:param request:
"""
tag_id = request.GET.get('tag_id')
tag = Tag.objects.filter(pk=tag_id).first()
blogs = tag.blog_set.all()
data = {
'title': tag.name,
'blogs': blogs
}
return render(request, 'blog/blog_list.html', context... | 33c87055f5d4a3512f4edef1b67ea1f077f3805a | 3,604,266 |
def make_connection(scope, receive, send) -> type[Connection]:
"""Return a ``Connection`` instance for a protocol.
Args:
scope (dict): the request information.
receive (Coroutine): the coroutine function to call to receive a
client request.
send (Coroutine): the coroutine fu... | be9062acbc78e4d6ea61dc8fe738c69bcd30788b | 3,604,267 |
def ncor(x, y):
"""Calculate the normalized correlation of two arrays"""
return np.correlate(x, y, old_behavior=False) / \
(np.correlate(x, x, old_behavior=False) * np.correlate(y, y, old_behavior=False)) ** 0.5 | d8678dfdf15fbf09b66be97895dc23584693f1bc | 3,604,268 |
def get_fstat_df(fs, Zs, quadruples):
"""
Takes lists of lists of f values, Z values, and list of name quadruples.
"""
d = {'h1': [t[0] for t in quadruples],
'h2': [t[1] for t in quadruples],
'h3': [t[2] for t in quadruples],
'o': [t[3] for t in quadruples]}
d.update({'f_h... | 2561a261a36f17abd397e6d4fa60aac43774f654 | 3,604,269 |
def call_ccall(x):
"""
Test that a declared return type is honoured when compiled.
>>> result, return_type = call_ccall(1)
>>> (not is_compiled and 'double') or return_type
'double'
>>> (is_compiled and 'int') or return_type
'int'
>>> (not is_compiled and 1.0) or result
1.0
>>... | 08885a35b3955ded1a8088b2cf8cd19267ab22a0 | 3,604,270 |
def headerless_len(units):
"""return count of translatable (non header) units"""
return len(filter(lambda x: not x.isheader(), units)) | aaf554a02008771cf87f590f8210f80223df56b5 | 3,604,272 |
def is_lock_valid(transfer, block_number):
""" True if the lock has not expired. """
return block_number <= transfer.expiration | 186c48c8a81458a9ff25891f5afa380f07dcbede | 3,604,273 |
def Tbb_(xLW): # pragma: no cover
""" effective blackbody temperature
:param xLW - Longwave radiation (W/m2):
:return:
"""
return (xLW / SBC) ** (0.25) - 273.2 | ef876f93a7fe0f9085a6aab2a8aa3f37eb5cf7fa | 3,604,274 |
from datetime import datetime
import dateutil
def _importance_of_task(task):
"""Tuple (importance, end-time). Smaller values are more important."""
# The status of a job is going to be determined by the roll-up of its tasks.
# A FAILURE or CANCELED task means the job has FAILED.
# If none, then any RUNNING ta... | b35bcf9962120050030460c9dea504c9015bf89d | 3,604,275 |
import math
def baseline(y, deg=None, max_it=None, tol=None):
"""
Computes the baseline of a given data.
Iteratively performs a polynomial fitting in the data to detect its
baseline. At every iteration, the fitting weights on the regions with
peaks are reduced to identify the baseline only.
... | cf231331271ab50d9a32afc6f67be65ef49a48f7 | 3,604,276 |
def generate_inventory_report():
""" generate list of products x locations
based on returns from datastorage functions for
products()
locations()
and then examining if any inventory is actually there. . .
"""
#print(datastorage.products())
#print(datastorage.locations())
print("stored")
print(datastorag... | 920e58ff59fc18de0639694335b35188d97d333e | 3,604,279 |
import sre_compile
def ReplaceAll(pattern, rep, s):
"""Replaces instances of pattern in a string with a replacement.
The compiled regex is kept in a cache shared by Match and Search.
Args:
pattern: regex pattern
rep: replacement text
s: search string
Returns:
string with replacements made (... | 08944500124a07f2d98ac6d1fad520997688aa0b | 3,604,280 |
def load_supervised(filter_std=0.1, train_valid_combine=False):
"""
Load the MNIST dataset.
:param filter_std: The standard deviation threshold for keeping features.
:param train_valid_combine: If the train set and validation set should be combined.
:return: The train, test and validation sets.
... | d994cf415c4b60b50b9d7ad09a91321748dc2dbf | 3,604,281 |
def org_get_subscribed_domains(cookie, in_class_id, in_domain_group_dn, in_subscription_type):
""" Auto-generated UCSC XML API Method. """
method = ExternalMethod("OrgGetSubscribedDomains")
method.cookie = cookie
method.in_class_id = str(in_class_id)
method.in_domain_group_dn = in_domain_group_dn
... | a38fa8cd4510402b7019b558c89f2ef6c88f38cb | 3,604,283 |
def GetChangeCurrentRevision(host, change):
"""Get information about the latest revision for a given change."""
jmsg = GetChangeReview(host, change)
if jmsg:
return jmsg.get('current_revision') | e41539e0ea73abf6bf33dfdf95955390473ccee5 | 3,604,284 |
def add_metadata(submission_id: int) -> Response:
"""Render step 9, metadata."""
return handle(cntrls.metadata, 'submit/add_metadata.html',
'Add or Edit Metadata', submission_id, flow_controlled=True) | a2ef990c2c195d96c5f8fcba64d76e2967528320 | 3,604,285 |
def get_genes_without_assigned_pathways(enrichment_results, genes_query):
"""Return the genes without any known pathway assigned.
:param dict gene_set: list of managers
:param set[str] genes_query: gene set queried
:return:
"""
# Get genes in all pathways
genes_in_pathways = {
gene
... | ab40c79ca078a36f723bde553b8183079ea4313c | 3,604,286 |
import json
def GetApiDiscovery(api_name, api_version):
"""Get a discovery doc from the discovery server."""
api_path = 'apis/%s/%s/rest' % (api_name, api_version)
discovery_url = 'https://%s/discovery/%s/%s' % (
FLAGS.discovery_server, FLAGS.discovery_version, api_path)
http = httplib2.Http()
_, con... | d8b883fecb5d16f0a81a62c48d9a15a5b15a9429 | 3,604,287 |
def heap_sort(A):
"""Heap sort!
1. 'heapify' array as max-heap
2. Move the root to the end of the array (in its sorted place)
3. 'sift_down' to fix the remaining elements into a new heap
Tests
-----
>>> A = [5, 8, 6, 0, 7, 9, 1, 2, 4, 3]
[5, 8, 6, 0, 7, 9, 1, 2, 4, 3]
>>> heap_sort... | ee7fbe30eb5f2cf5e46b9ab747dd3d6e869aa10e | 3,604,288 |
def set_overlay(background, overlay, pos=(0,0)):
"""
Function to overlay a transparent image on background.
:param background: input color background image
:param overlay: input transparent image (BGRA)
:param pos: position where the image to be set.
:return: result image
"""
h... | ae9b8be9193e04ede7649ff9cab2ad4a94c4876a | 3,604,289 |
def moduleList():
"""Create module lists."""
return nn.ModuleList() | d314b842533f11460893f86ccf489c96e3d40bff | 3,604,290 |
def format_variables_info_string(variables: dict):
"""
Return some textual information about the variables contained in this data source.
Useful for CLI / REPL applications.
:param variables:
:return:
"""
if not variables:
return 'No variables information available.'
info_lines ... | 8f6f13c13040208e137efdef54175a2b68942b24 | 3,604,291 |
from typing import cast
def get_public_key(database: Database) -> dict:
"""Return a serialized version of the public key."""
public_key = database.secrets.find_one({"name": EXPORT_FIELDS_KEYS_NAME}, {"public_key": True, "_id": False})
public_key_as_dict = cast(dict, public_key)
return public_key_as_di... | d5a492042da83311f55f885510188ef7310bf83a | 3,604,292 |
def solve(instructions):
"""Return value of the recovered frequency the first time rcv is executed.
:instructions: list of instructions, separated by newlines
:returns: value of recovered frequency
>>> solve('''set a 1
... add a 2
... mul a a
... mod a 5
... snd a
... set a 0
.... | 40a4885fa75ef31f8f535057d2345f04c27f7e44 | 3,604,294 |
import math
def plot_traj_colormap_ape(ape_metric, traj_ref, traj_est1, traj_est2=None,
plot_title="", figsize=(8,8)):
""" Adds a trajectory colormap of ATE metrics to a plot collection.
Args:
ape_metric: an evo.core.metric object with statistics and information for... | d339d85fc46d99695e97a1661c6a3a1deeb9b5bc | 3,604,297 |
def simulate_bleaching_times(b, N):
"""
b = bleaching rate
N = number of fluorophores
---
returns vector of simulated bleaching times
"""
return b * np.cumsum(
np.random.exponential(1 / np.arange(1, N+1)[::-1])
) | c283a3c3ff174c5b9d78026f6537a457ff630f67 | 3,604,298 |
def flatten_SIF(data):
"""Color of pixel is the first non-transparent layer.
0=black, 1=white, 2=transparent
"""
result = np.zeros(data[0].shape) + 2
for z in range(data.shape[0]): # Drill down the layers
mask = result == 2
result[mask] = data[z][mask]
return result.astype(int) | 72987d92e071dc278ea5738de4d11db65edef29f | 3,604,299 |
def outside(x, y, xo, yo):
"""GIVEN 3 POINTS a, b, c OF A POLYGON
WITH CENTER xo, yo
DETERMINE WHETHER b IS OUTSIDE ac,
THAT IS, WHETHER abc IS CONVEX"""
# DOES o--b CROSS a--c ?
# A--B A--B
xa, xb, xc = x
ya, yb, yc = y
xA = (xo, xa)
yA = (yo, ya)
xB = (xb, xc)
... | f7aeada7357bca7e2122be4b85b55451b4a27723 | 3,604,300 |
def error_rate(predictions, labels):
"""Return the error rate and confusions."""
correct = np.sum(np.argmax(predictions, 1) == np.argmax(labels, 1))
total = predictions.shape[0]
error = 100.0 - (100 * float(correct) / float(total))
return error | 0c31cfbda1b9cdb3a31a289911295c3daa6e2037 | 3,604,301 |
import importlib
import collections
def load_mf_dataset(config=None):
"""Return the dataset of matrix factorization
Format:
{
'client_id': {
'train': DataLoader(),
'test': DataLoader(),
'val': DataLoader()
}
}
"""
... | 95a998e9a96df54b5471b712b8bdee10de2d64a7 | 3,604,304 |
def format_line(entries, sep=' | ', pads=None, center=False):
"""
Format data for use in a simple table output to text.
args:
entries: List of data to put in table, left to right.
sep: String to separate data with.
pad: List of numbers, pad each entry as you go with this number.
... | c5dfd312f8f13a54943fe18e254a6d8836d4460a | 3,604,306 |
import torch
def topk_score(scores, K=40, score_shape=None):
"""
get top K point in score map
"""
batch, channel, height, width = score_shape
# get topk score and its index in every H x W(channel dim) feature map
topk_scores, topk_inds = torch.topk(scores.reshape(batch, channel, -1), K)
... | 8431441195a558a2f0e80357cac8a1cf17a16347 | 3,604,307 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.