content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
import os
def listdir(d):
"""Get full paths to the files and folders in d.
Args:
d (str):
Path of directory to scan.
Returns:
full_paths (genexp):
The full paths to the entries in the directory d.
"""
return (os.path.join(d, f) for f in os.listdir(d)) | 79cd75ab402cf7fca4210a2476276e9ac244b054 | 3,604,200 |
import os
import glob
def read_job_output(path: str) -> GeoDataFrame:
"""Read job output produced by 'wri/gfw_forest_loss_geotrellis' into GeoDataFrame
Parameters
----------
path: str
Directory of the job output or CSV file path.
Path can be local or S3 URI.
"""
if path[:5] ==... | 14ad642e065c26afade34bae297a1c262acd93e9 | 3,604,201 |
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 |
import sys
import time
def convert_halocat_to_h5(filenames, outputdir="./",
write_halo_props_cont=True,
fields=None, drop_fields=None,
chunksize=100000, compression='gzip',
comm=None, show_progressbar=False):
... | 1fd72df5f6abd6944ed835df0eda86c3535727c2 | 3,604,211 |
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 |
import os
def _get_swift_source_root(swift_path, env=None):
"""Returns the Swift source root or None if one cannot be determined.
Users are able to manually override the source root by setting the SWIFT_SOURCE_ROOT
environment variable. If that cannot be found then this function will check the
direct... | 4ae83bd814d8f78fb02ffdb805fa76a97e58168a | 3,604,213 |
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 |
def point_inside_ellipse(xpoint, ypoint, xcen, ycen, xsemimajor, ysemiminor,
orient,
left_only=False, right_only=False, bottom_only=False,
top_only=False):
"""
Helper function to determine if a point (xpoint,ypoint) is
inside an... | 88f7b0a50ffd648d582d44609d6b32b4685d0955 | 3,604,223 |
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 |
import os
import shutil
def get_used_disk_per():
""" Get the disk usage of working directory."""
if not os.path.exists(config.WORKING_PATH):
try:
os.makedirs(config.WORKING_PATH)
except FileExistsError:
pass
total, used, _ = shutil.disk_usage(config.WORKING_PATH)
... | 198a687dfd5e320623e1c42d423b91ab79a64c47 | 3,604,255 |
def name(lti):
"""
Access route with 'initial' request.
:param lti: `lti` object
:return: string "hi"
"""
return lti.name | 388af21bf4ea6b47f41f9cd036fa99422f410e44 | 3,604,256 |
import sys
def version_check(current_version=None, version_url=_VERSION_URL, check_for_point_releases=False):
"""
Gets the latest version information from version_url and check against the current version.
Recommends upgrade, if a newer version exists.
:returns: True if current version is the latest ... | f761b3351210f55c53524cbf05e2296a0657db5c | 3,604,257 |
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 |
import argparse
import os
def setup_cppcheck_tool_plugin(use_plugin_context=True, binary=None):
"""Initialize and return an instance of the cppcheck plugin."""
arg_parser = argparse.ArgumentParser()
arg_parser.add_argument("--cppcheck-bin", dest="cppcheck_bin")
arg_parser.add_argument(
"--mapp... | a9b418997c99c0bb2b4f264f3ea40a72cd430ed2 | 3,604,260 |
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 |
import os
def parse_configuration(configuration_file_name):
"""
Parse configuration file.
Args:
configuration_file_name: Configuration file name (include path) to parse.
Returns:
A ConfigParser object.
Raises:
ConfigurationException: Fail to parse configuration file.
... | 0e36c551270adf338ca514e070d98e3d90685aa3 | 3,604,271 |
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 parse_pb_data(raw_data, pv, start, end, count=None):
"""
Turn raw PB data into an ArchiveData object
Args:
raw_data: The raw data
pv: name of PV
start: datetime.datetime for start of window
end: datetime.datetime for end of window
count: return up to this many ev... | 6cb91dbfcb921f05ebaae58cd87e1c24e035ed3c | 3,604,277 |
import os
import re
def parse_type_collections(fidl_file, handled_files=None):
"""
This following function is parsing fidl-file
:param fidl_file: File to parse
:param handled_files: Number of handled files with types
:return: Raw type_collections
"""
if handled_files is None:
handl... | 4ee9d95db996810773a5db0c39172acb9125514b | 3,604,278 |
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 callback(request, network):
"""
This is the authentication view called by social network after the
user authenticates via the social network.
"""
oauth_request_token = request.session.get(SK_REQUEST_TOKEN)
if not oauth_request_token:
raise Http404
backend = get_network_backend_... | af645af2a37f28ae15a7526a76f186ebc98617eb | 3,604,282 |
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 |
import sys
def do_training_CMMVH(training_stages,prob,LT,loaddata,savefile,savefilemat,savemodel,ivl=10,maxit=1000000,better_wait=500):
# ivl=10,maxit=1000000,better_wait=5000
"""
ivl:how often should we compute the nmse of the validation set?
maxit: max number of training iterations
better_wait:w... | 095e2b2fdececc6372b9940dac06a6cf0b38c53a | 3,604,293 |
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 os
def compare_data(request, test_name, scope="session"):
"""Returns a function which either saves some data to a file or (if that file exists already) compares it to pre-existing data using a given comparison function."""
def inner(compare_fct, data, tag=None):
dir_name, file_name = test_name... | 0dd170ecbf135d44f4492c3aa8013e52c37738d7 | 3,604,295 |
import six
def generate_global_index(library_name, index, reference_resolver):
"""Given a dict of full names to python objects, generate an index page.
The index page generated contains a list of links for all symbols in `index`
that have their own documentation page.
Args:
library_name: The name for th... | f4e858709bcc7cfd11056401b65ef94cab720569 | 3,604,296 |
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 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.