content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
from typing import Dict
import array
def extract_float_arrays(blockids: str, data: bytes) -> Dict[str, array]:
"""Extracts float arrays from raw scope, background trace, and recorder
zoom binary data (block ids a, A, b, B, x, y, Y in the DLC pro 'Scope,
Lock, and Recorder Binary Data' format).
Args:
... | 8789f73d175b9d0f244b33b61d0fe1effa702ded | 26,400 |
def rotate_image(path):
"""Rotate the image from path and return wx.Image."""
img = Image.open(path)
try:
exif = img._getexif()
if exif[ORIENTATION_TAG] == 3:
img = img.rotate(180, expand=True)
elif exif[ORIENTATION_TAG] == 6:
img = img.rotate(270, expand=True... | b4f450a3f6cb01a4d9c8e6c384edeabd0366ac63 | 26,401 |
def predict():
"""Predict endpoint.
Chooses model for prediction and predcits
bitcoin price for the given time period.
@author: Andrii Koval, Yulia Khlyaka, Pavlo Mospan
"""
data = request.json
if data:
predict = bool(data["predict"])
if predict:
if predictor.p... | 90fbc72e3a57ad7dae3617bec20268c87a0c158a | 26,402 |
def splice_imgs(img_list, vis_path):
"""Splice pictures horizontally
"""
IMAGE_WIDTH, IMAGE_HEIGHT = img_list[0].size
padding_width = 20
img_num = len(img_list)
to_image = Image.new('RGB',
(img_num * IMAGE_WIDTH + (img_num - 1) * padding_width,
... | 97d4ab32f1a734fbd04e7c558062867c2e6bd3b4 | 26,403 |
def create_segmented_colormap(cmap, values, increment):
"""Create colormap with discretized colormap.
This was created mainly to plot a colorbar that has discretized values.
Args:
cmap: matplotlib colormap
values: A list of the quantities being plotted
increment: The increment used... | 9ab8a0a95896e1ae0f8777b705f920196afc6627 | 26,404 |
from io import StringIO
def division_series_logs():
"""
Pull Retrosheet Division Series Game Logs
"""
s = get_text_file(gamelog_url.format('DV'))
data = pd.read_csv(StringIO(s), header=None, sep=',', quotechar='"')
data.columns = gamelog_columns
return data | 414de8e0409bba9651bef81bbdc811e105d1d11f | 26,405 |
def release_date(json):
"""
Returns the date from the json content in argument
"""
return json['updated'] | 635efd7140860c8f0897e90433a539c8bd585945 | 26,406 |
def init_embedding_from_graph(
_raw_data, graph, n_components, random_state, metric, _metric_kwds, init="spectral"
):
"""Initialize embedding using graph. This is for direct embeddings.
Parameters
----------
init : str, optional
Type of initialization to use. Either random, or spectral, by ... | 22c2d939a47932b625491a1e685b055214753010 | 26,407 |
def basic_hash_table():
"""Not empty hash table."""
return HashTable(1) | b06e59c2a6767309e5394df6e51bdaf12c58d073 | 26,408 |
def scan_by_key(key, a, dim=0, op=BINARYOP.ADD, inclusive_scan=True):
"""
Generalized scan by key of an array.
Parameters
----------
key : af.Array
key array.
a : af.Array
Multi dimensional arrayfire array.
dim : optional: int. default: 0
Dimension along which th... | ea9556b3e2a87a08cca62d03da41edf5985d4156 | 26,409 |
def local_luminance_subtraction(image, filter_sigma, return_subtractor=False):
"""
Computes an estimate of the local luminance and removes this from an image
Parameters
----------
image : ndarray(float32 or uint8, size=(h, w, c))
An image of height h and width w, with c color channels
filter_sigma : ... | d9cc46a205f495c0107211d7222be27f40d6896b | 26,410 |
def createBank():
"""Create the bank.
Returns:
Bank: The bank.
"""
return Bank(
123456,
'My Piggy Bank',
'Tunja Downtown'
) | 676f0d6cf330e7832064393b543a5ffd1f1068d1 | 26,411 |
def str_to_bool(param):
"""
Convert string value to boolean
Attributes:
param -- inout query parameter
"""
if param.upper() == 'TRUE':
return True
elif param.upper() in ['FALSE', None]:
return False
else:
raise InputValidationError(
'Invalid query... | ef860e2b2e623d98576c04ef1e397604576d8d48 | 26,412 |
import argparse
def create_parser():
"""
Creates the argparse parser with all the arguments.
"""
parser = argparse.ArgumentParser(
description='Management CLI for mock PCRF',
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
# Add subcommands
subparsers = parser.add_subp... | c2a1d2fbbcaafd1fec40ea8f53df29e2cc481269 | 26,413 |
import sys
def ProtoFlags(*ss):
"""
add the command options for protoc
Args:
ss : a variable number of string objects
ss may contain multiple string objects, each object can contain multiple options
one option may be:
1. option may contains $WORKSPACE, $OUT Macro... | 7d667ae25e4b6e1b3fa201064ef158c5cf5cc46a | 26,414 |
from typing import Optional
from typing import List
from typing import Dict
from datetime import datetime
def fetch_log_messages(attempt_id: Optional[int] = None,
task_id: Optional[int] = None,
min_severity: Optional[int] = None):
"""
Fetch log messages from the d... | 10e78d0ee14647cf7a390287208a28aa957551a4 | 26,415 |
import argparse
def parse_arguments():
"""Argument parser for extract_branch_length"""
parser = argparse.ArgumentParser(
description="extract_branch_length.py: extract the branch length of the "
" common ancestor of a set of species"
)
parser.add_argument(
"-t",
"--tree... | 2ee5fcce15420e77307e4444b86b51e18b0fadb7 | 26,416 |
def part_1_solution_2(lines):
"""Shorter, but not very readable.
A good example of "clever programming" that saves a few lines of code, while
making it unbearably ugly.
Counts the number of times a depth measurement increases."""
return len([i for i in range(1, len(lines)) if lines[i] > lines[i - 1]... | d393f0385a1afbea4c2f3b4d3f51d8e7d0ade204 | 26,417 |
def get_lifecycle_configuration(bucket_name):
"""
Get the lifecycle configuration of the specified bucket.
Usage is shown in usage_demo at the end of this module.
:param bucket_name: The name of the bucket to retrieve.
:return: The lifecycle rules of the specified bucket.
"""
s3 = get_s3()... | 380c884afddbf72db6474e60480bf75ebe67309e | 26,418 |
def compute_reward(ori, new, target_ids):
"""
Compute the reward for each target item
"""
reward = {}
PE_dict = {}
ori_RI, ori_ERI, ori_Revenue = ori
new_RI, new_ERI, new_Revenue = new
max_PE, min_PE, total_PE = 0, 0, 0
for item in target_ids:
PE = new_Revenue[item] - ori_Revenue[item]
# Eq. (3) in paper... | a64a1c47089924d373c7435c5018c63fd4edbe74 | 26,419 |
from typing import Any
import torch
import tqdm
def _compute_aspect_ratios_slow(dataset: Any, indices: Any = None) -> Any:
"""Compute the aspect ratios."""
print(
"Your dataset doesn't support the fast path for "
"computing the aspect ratios, so will iterate over "
"the full dataset an... | 8fd183a5c353503067666526bdf6722bb53a4317 | 26,420 |
import getopt
def parse_args(input_args):
"""
Parse the supplied command-line arguments and return the input file glob
and metric spec strings.
:param input_args: Command line arguments.
:return: A triplet, the first element of which is the input file glob,
the second element is the ... | a15327a3aa2aae86ef8ad14ebcae46b6f3593503 | 26,421 |
def _diffuse(field: jnp.ndarray, diffusion_coeff: float, delta_t: float) -> jnp.ndarray:
"""
Average each value in a vector field closer to its neighbors to simulate
diffusion and viscosity.
Parameters
----------
field
The vector field to diffuse. *Shape: [y, x, any].*
diffusion_coe... | e05763df93164bd7b4baa778720dbecc32fea228 | 26,422 |
def dAdzmm_ron_s0(u0, M, n2, lamda, tsh, dt, hf, w_tiled):
"""
calculates the nonlinear operator for a given field u0
use: dA = dAdzmm(u0)
"""
print(u0.real.flags)
print(u0.imag.flags)
M3 = uabs(np.ascontiguousarray(u0.real), np.ascontiguousarray(u0.imag))
temp = fftshift(ifft(f... | 57c958bca07b77eaa406cb6b95bf5719af34075b | 26,423 |
def create_support_bag_of_embeddings_reader(reference_data, **options):
"""
A reader that creates sequence representations of the input reading instance, and then
models each question and candidate as the sum of the embeddings of their tokens.
:param reference_data: the reference training set that deter... | 0b09423e9d62d1e5c7c99bd1ebede22ca490797a | 26,424 |
def get_hosts_cpu_frequency(ceilo, hosts):
"""Get cpu frequency for each host in hosts.
:param ceilo: A Ceilometer client.
:type ceilo: *
:param hosts: A set of hosts
:type hosts: list(str)
:return: A dictionary of (host, cpu_frequency)
:rtype: dict(str: *)
"""
hosts_cpu_total ... | aa6049b9d011d187e1a246a413835aafdbb5c6dc | 26,425 |
def _cloture(exc):
"""
Return a function which will accept any arguments
but raise the exception when called.
Parameters
------------
exc : Exception
Will be raised later
Returns
-------------
failed : function
When called will raise `exc`
"""
# scoping will sav... | b2e22f5b4bd267d1945b7f759f5ddfb1ee8c44e5 | 26,426 |
from typing import Dict
import json
def _with_environment_variables(cmd: str, environment_variables: Dict[str, object]):
"""Prepend environment variables to a shell command.
Args:
cmd (str): The base command.
environment_variables (Dict[str, object]): The set of environment
variab... | ae27d9e7a62f49e836f1c1b116205f318d9d0dd3 | 26,427 |
def update_spam_assets(db: 'DBHandler') -> int:
"""
Update the list of ignored assets using query_token_spam_list and avoiding
the addition of duplicates. It returns the amount of assets that were added
to the ignore list
"""
spam_tokens = query_token_spam_list(db)
# order maters here. Make ... | 4e7f4e5ae8a6b92ebd5a60a34d9330330690b663 | 26,428 |
import os
import gzip
def _load_idx(filename):
"""Loads a single IDX file."""
dirname = os.path.dirname(__file__)
filename = os.path.join(dirname, "data", filename)
with gzip.open(filename, "rb") as f:
return idx.read_array(f) | afcf0e50a12965223722ddfe15b874660c81ac6a | 26,429 |
import png
def png_info(path):
"""Returns a dict with info about the png"""
r = png.Reader(filename=path)
x, y, frames, info = r.read()
return info | 97b9df7dd7800f350695e8d678d25154c7a4b2b8 | 26,430 |
def _(data: ndarray, outliers: ndarray, show_report: bool = True) -> ndarray:
"""Process ndarrays"""
if type(data) != type(outliers):
raise TypeError("`data` and `outliers` must be same type")
# convert to DataFrame or Series
data = DataFrame(data).squeeze()
outliers = DataFrame(outliers).sq... | 1c478af8a6fffcf6240b2547782ee3fc256fdd0c | 26,431 |
import six
def bool_from_string(subject, strict=False, default=False):
"""
将字符串转换为bool值
:param subject: 待转换对象
:type subject: str
:param strict: 是否只转换指定列表中的值
:type strict: bool
:param default: 转换失败时的默认返回值
:type default: bool
:returns: 转换结果
:rtype: bool
"""
TRUE_STRINGS ... | 3c6efa416471da391e60b82aec3753d823ee2878 | 26,432 |
def prot_to_vector(seq: str) -> np.ndarray:
"""Concatenate the amino acid features for each position of the sequence.
Args:
seq: A string representing an amino acid sequence.
Returns:
A numpy array of features, shape (len(seq), features)"""
# convert to uppercase
seq = seq.upper()
... | ac5293ee67698243e4910c87944133f9697d8646 | 26,433 |
import os
def project_root(project):
"""Return the path the root dir of the vendored project.
If "project" is an empty string then the path prefix for vendored
projects (e.g. "ptvsd/_vendored/") will be returned.
"""
if not project:
project = ''
return os.path.join(VENDORED_ROOT, proj... | 5428b19ef68748719886997cc4908d2f70711d50 | 26,434 |
def set_partition(num, par):
"""
A function returns question for partitions of a generated set.
:param num: number of questions.
:param par: type of items in the set based on documentation.
:return: questions in JSON format.
"""
output = question_list_maker(num, par, 'set-par... | 71540d753020e5333558098b7edf96c4318fb316 | 26,435 |
def meanS_heteroscedastic_metric(nout):
"""This function computes the mean log of the variance (log S) for the heteroscedastic model. The mean log is computed over the standard deviation prediction and the mean prediction is not taken into account.
Parameters
----------
nout : int
Number of out... | 75bc5ddb482cc0e99bb4f5f9b0d557321b57cf06 | 26,436 |
def ec2_connect(module):
""" Return an ec2 connection"""
region, ec2_url, boto_params = get_aws_connection_info(module)
# If we have a region specified, connect to its endpoint.
if region:
try:
ec2 = connect_to_aws(boto.ec2, region, **boto_params)
except (boto.exception.No... | d94b5a1359a31657aa2dffd1f0c11d9cd06493dd | 26,437 |
import glob
def read_lris(raw_file, det=None, TRIM=False):
"""
Read a raw LRIS data frame (one or more detectors)
Packed in a multi-extension HDU
Based on readmhdufits.pro
Parameters
----------
raw_file : str
Filename
det : int, optional
Detector number; Default = both
... | 98351f63a78a37ac8cbb3282e71903ee6dd6bbb1 | 26,438 |
def mu(n: int) -> int:
"""Return the value of the Moebius function on n.
Examples:
>>> mu(3*5*2)
-1
>>> mu(3*5*2*17)
1
>>> mu(3*3*5*2)
0
>>> mu(1)
1
>>> mu(5)
-1
>>> mu(2**10-1)
-1
"""
if n == 1:
re... | b8347480041de2dc9dfc469096293e3815eebbcd | 26,439 |
def find_last(arr, val, mask=None, compare="eq"):
"""
Returns the index of the last occurrence of *val* in *arr*.
Or the last occurrence of *arr* *compare* *val*, if *compare* is not eq
Otherwise, returns -1.
Parameters
----------
arr : device array
val : scalar
mask : mask of the a... | 376a21174bc26ca332768aadf96b84b06e7f55f5 | 26,440 |
def find_orphans(input_fits, header_ihdus_keys):
"""Return a dictionary with keys=(ihdu, key) and values='label' for missing cards in 'header_ihdus_keys'
Parameters:
-----------
input_fits: astropy.io.fits.HDUList instance
FITS file where to find orphan header cards
header_ihdus_keys: l... | bcc98722ba43450ff68367f776a84c0e193447d9 | 26,441 |
import ipdb
import ipdb
import tqdm
def solve(n_vec, m_vec, p_vec, repeat, dns_level, seed, solver='gurobi'):
"""
Solve random optimization problems
"""
print("Solving random problems with solver %s\n" % solver)
# Define statistics to record
std_solve_time = np.zeros(len(n_vec))
avg_solv... | 1630b556f40c20696adc5b7ce2b9ef218d82a87a | 26,442 |
def Rotation_multiplyByBodyXYZ_NInv_P(cosxy, sinxy, qdot):
"""
Rotation_multiplyByBodyXYZ_NInv_P(Vec2 cosxy, Vec2 sinxy, Vec3 qdot) -> Vec3
Parameters
----------
cosxy: SimTK::Vec2 const &
sinxy: SimTK::Vec2 const &
qdot: SimTK::Vec3 const &
"""
return _simbody.Rotation_multiplyByB... | 93303a83224b29d9dddf09a64f36d7004ae2ace0 | 26,443 |
def sqrt(x: float):
"""
Take the square root of a positive number
Arguments:
x (int):
Returns:
(float): √x
Raises:
(ValueError): If the number is negative
"""
if x < 0:
raise ValueError('Cannot square-root a negative number with this '
... | ab43573010044ffa3861f6a13a58135be52c02b4 | 26,444 |
def get_tree_type(tree):
"""Return the (sub)tree type: 'root', 'nucleus', 'satellite', 'text' or 'leaf'
Parameters
----------
tree : nltk.tree.ParentedTree
a tree representing a rhetorical structure (or a part of it)
"""
if is_leaf_node(tree):
return SubtreeType.leaf
tree_t... | 15d292ab1f756594add92a6999c7874f6d7fc45b | 26,445 |
def intersection(ls1, ls2):
"""
This function returns the intersection of two lists without
repetition. This function uses built in Python function set()
to get rid of repeated values so inputs must be cast to list
first.
Parameters:
-----------
ls1 : Python list
The first list. Cannot be array.
ls2 : Pyt... | fb3bda67d8040da5f4f570e8ff10a8503e153f36 | 26,446 |
import sys
def run_tutorial(options):
"""Run a selection dlapp console CLI tutorial.
Parameters
----------
options (argparse.Namespace): a argparse.Namespace instance.
Returns
-------
None: will call ``sys.exit(0)`` if end user requests a tutorial
"""
is_tutorial_needed = options... | fab0dac555bc45f6c816a6804b1e0d7447f5a5cf | 26,447 |
def params_count(model):
"""
Computes the number of parameters.
Args:
model (model): model to count the number of parameters.
"""
return np.sum([p.numel() for p in model.parameters()]).item() | 12bb8463f6eb722a5cb7e7adfdf869764be67944 | 26,448 |
from pathlib import Path
import platform
import shutil
def open_cmd_in_path(file_path: Path) -> int:
""" Open a terminal in the selected folder. """
if platform.system() == "Linux":
return execute_cmd(["x-terminal-emulator", "-e", "cd", f"{str(file_path)}", "bash"], True)
elif platform.system() ==... | 899424cd8ab2d76a5ca47d7219a7057d29bb5abe | 26,449 |
def get_f(user_id, ftype):
"""Get one's follower/following
:param str user_id: target's user id
:param str ftype: follower or following
:return: a mapping from follower/following id to screen name
:rtype: Dict
"""
p = dict(user_id=user_id, count=200, stringify_ids=True,
include... | 31371d823509c8051660ca0869556253af6b99cc | 26,450 |
from typing import List
from typing import Tuple
from typing import Any
from typing import Optional
def walk_extension(
state: State,
trie_prefix: Bytes,
node_key: Bytes,
extension_node: ExtensionNode,
dirty_list: List[Tuple[Bytes, Node]],
cursor: Any,
) -> Optional[InternalNode]:
"""
... | bcc31ae61729db82d84e02168926845b7b42da44 | 26,451 |
import os
def gffintRead():
"""
Read the integrated free-free gaunt factors of [1]_.
"""
xuvtop = os.environ['XUVTOP']
fileName = os.path.join(xuvtop, 'continuum','gffint.dat' )
input = open(fileName)
lines = input.readlines()
input.close()
#
ngamma = 41
g2 = np.zeros(ngam... | 63233454325c192dc674f2685fc92c38a82fbd42 | 26,452 |
def bottleneck_block_v2(inputs, filters, strides, training, projection_shortcut, data_format):
"""
3-layer bottleneck residual block with batch normalization and relu before convolution layer.
:param inputs: Input images
:param filters: number of filters
:param strides: strides of convolutions
:... | 8330e68d1411c643ffcee6916ba95ef77b7cc5ee | 26,453 |
import os
def update_index(homework):
"""Check if the index of the given dataset is up to date with server version, and update it if needed.
Parameters:
homework (str): The name of the dataset to check the index of.
Returns:
bool: Indicates if we were able to check the in... | 41f2d935b990e8d9a5ab5dabd268288d864d1a60 | 26,454 |
def preprocess_lines(lines, otherAutorizedSymbols, sentencesSeparator=None):
""" complete my dataset"""
if sentencesSeparator :
result = []
for line in lines :
e = line.split(sentencesSeparator)
if e[0] != "__Error__" and e[1]!= "__Error__" :
lignes_i = sent_tokenize(e[0])
lignes... | 04bf9f90bf06f07803ca8dd6199728d33a73a6de | 26,455 |
def is_slashable_validator(validator: Validator, epoch: Epoch) -> bool:
"""
Check if ``validator`` is slashable.
"""
return (not validator.slashed) and (validator.activation_epoch <= epoch < validator.withdrawable_epoch) | 9ea82379e270f668d2dde3cb5b10a59f29f2e6e6 | 26,456 |
def check_rate_limit() -> None:
"""
Check whether or not a user has exceeded the rate limits specified in the
config. Rate limits per API key or session and per user are recorded.
The redis database is used to keep track of caching, by incrementing
"rate limit" cache keys on each request and setting... | ca49c4b2c4287bca3d664b20abebd9b7df53a0fb | 26,457 |
def update_db(mode):
"""Mode can be 'add', 'move', 'delete'"""
def decorator(func):
@wraps(func)
def wrapped(*args, **kwargs):
# did and rse are the first 2 args
did, rse = args[0], args[1]
update_db = kwargs.get('update_db', False)
if not update_... | cc91757030c9d398bd17ad73521e23d835879560 | 26,458 |
def right_size2(a1, a2):
"""
Check that a1 and a2 have equal shapes.
a1 and a2 are NumPy arrays.
"""
if hasattr(a1, 'shape') and hasattr(a2, 'shape'):
pass # ok, a1 and a2 are NumPy arrays
else:
raise TypeError('%s is %s and %s is %s - both must be NumPy arrays' \
... | 66aa2097ff67a2ef44c49118dbdbba1539f1e3ba | 26,459 |
import argparse
def arguments_parser() -> argparse.Namespace:
""" Parses arguments. """
parser = argparse.ArgumentParser(description="Input File containing list of repositories url's")
parser.add_argument("-u", "--username", default='Luzkan',
help="GitHub Username. \
... | 1c3eafc82ac2014c205f1fe5a9356ef47fe9b864 | 26,460 |
def spherDist(stla, stlo, evla, evlo):
"""spherical distance in degrees"""
return SphericalCoords.distance(stla, stlo, evla, evlo) | e2ae206c63712dbf263d6d3af28066f279571e20 | 26,461 |
def get_example(matrix, start_row, input_timesteps=INPUT_TIMESTEPS, output_timesteps=OUTPUT_TIMESTEPS):
"""Returns a pair of input, output ndarrays. Input starts at start_row and has the given input length.
Output starts at next timestep and has the given output length."""
# Make sure there are enough time ... | aa396588a32492c29e1dbb4a0e8f96016974b805 | 26,462 |
def full_mul_modifier(optree):
""" extend the precision of arguments of a multiplication to get the full result of the multiplication """
op0 = optree.get_input(0)
op1 = optree.get_input(1)
optree_type = optree.get_precision()
assert(is_std_integer_format(op0.get_precision()) and is_std_integer_form... | 6c191c274d9f130619e2831b50de65a270b41748 | 26,463 |
def find_used_modules(modules, text):
"""
Given a list of modules, return the set of all those imported in text
"""
used = set()
for line in text.splitlines():
for mod in modules:
if 'import' in line and mod in line:
used.add(mod)
return used | 0b1b2b31f60a565d7ba30a9b21800ba7ec265d0c | 26,464 |
def string2mol2(filename, string):
"""
Writes molecule to filename.mol2 file, input is a string of Mol2 blocks
"""
block = string
if filename[-4:] != '.mol2':
filename += '.mol2'
with open(filename, 'w') as file:
file.write(block)
return None | 51043e7f4edde36682713455dc33c643f89db397 | 26,465 |
def getTimeFormat():
"""
def getTimeFormat(): This functions returns the time format used in the bot.
"""
return timeFormat | cd13ab983cd91dca4fc3ae3414c3724b5019f248 | 26,466 |
from typing import Sequence
from typing import Optional
import numpy
def concatenate(
arrays: Sequence[PolyLike],
axis: int = 0,
out: Optional[ndpoly] = None,
) -> ndpoly:
"""
Join a sequence of arrays along an existing axis.
Args:
arrays:
The arrays must have the same sha... | df6c897b25279dca5187e6cafe5c1b9d22b8a994 | 26,467 |
import requests
import json
def get_cik_map(key="ticker"):
"""Get dictionary of tickers to CIK numbers.
Args:
key (str): Should be either "ticker" or "title". Choosing "ticker"
will give dict with tickers as keys. Choosing "title" will use
company name as keys.
Returns:
... | 6a9cf67bb63bfd057ee936e1a5d5be33d8655abe | 26,468 |
def _data_layers():
"""Index all configured data layers by their "shorthand". This doesn't
have any error checking -- it'll explode if configured improperly"""
layers = {}
for class_path in settings.DATA_LAYERS:
module, class_name = class_path.rsplit('.', 1)
klass = getattr(import_module... | 34b0843c76086b41bf119987283fa4373bc07190 | 26,469 |
import hashlib
def sha1base64(file_name):
"""Calculate SHA1 checksum in Base64 for a file"""
return _compute_base64_file_hash(file_name, hashlib.sha1) | aaf2daca1676c822259bec8a519ab5eae7618b17 | 26,470 |
def readfsa(fh):
"""Reads a file and returns an fsa object"""
raw = list()
seqs = list()
for line in fh:
if line.startswith(">") and len(raw) > 0:
seqs.append(Fsa("".join(raw)))
raw.clear()
raw.append(line)
if len(raw) > 0:
seqs.append(Fsa("".join(raw)... | 089cd4b7addcf99baf9394b59d44702995eff417 | 26,471 |
def with_timeout(name):
"""
Method decorator, wraps method with :py:func:`asyncio.wait_for`. `timeout`
argument takes from `name` decorator argument or "timeout".
:param name: name of timeout attribute
:type name: :py:class:`str`
:raises asyncio.TimeoutError: if coroutine does not finished in ... | 7591a4ed176fad60510dfc7aafbb6df2b44672a4 | 26,472 |
import json
def results():
"""
function for predicting a test dataset input as a body of the HTTP request
:return: prediction labels array
"""
data = request.get_json(force=True)
data = pd.DataFrame(json.loads(data))
prediction = model.predict(data)
output = list(map(int, pred... | caae7f04884532de7a4fef9e5a6d285c982d2187 | 26,473 |
import os
def check_table_updates() -> bool:
"""Check whether the table needs to be updated.
Returns:
* A `boolean` indicating whether the tables need updating
* A `string` indicating the online version.
Raises:
SSLError:HTTPSConnectionPool: Max retries exceeded with url
"""... | 01892435f042344d1971d8cdf6f59662158be05f | 26,474 |
from datetime import datetime
def tradedate_2_dtime(td):
""" convert trade date as formatted by yfinance to a datetime object """
td_str = str(int(td))
y, m, d = int(td_str[:4]), int(td_str[4:6]), int(td_str[6:])
return datetime(y, m, d) | 29db7ed41a5cac48af1e7612e1cd2b59ab843a1f | 26,475 |
def frmchg(frame1, frame2, et):
"""frmchg(SpiceInt frame1, SpiceInt frame2, SpiceDouble et)"""
return _cspyce0.frmchg(frame1, frame2, et) | db05ebf45f0d265e8f75b26fbd7c1234d9a8b4cb | 26,476 |
def map_popularity_score_keys(popularity):
"""
Maps popularity score keys to be more meaningful
:param popularity: popularity scores of the analysis
:return: Mapped dictionary of the scores
"""
return dict((config.popularity_terms[key], value) for (key, value) in popularity.items()) | 84c265e7ec6e881df878f74d5d9b9eda9d223bf3 | 26,477 |
from typing import Callable
from typing import Optional
def _get_utf16_setting() -> Callable[[Optional[bool]], bool]:
"""Closure for holding utf16 decoding setting."""
_utf16 = False
def _utf16_enabled(utf16: Optional[bool] = None) -> bool:
nonlocal _utf16
if utf16 is not None:
... | 1f0caeab03047cc847d34266c1ed53eabdf01a10 | 26,478 |
def uproot_ntuples_to_ntuple_dict(uproot_ntuples, properties_by_track_type,
keep_invalid_vals=False):
"""Takes in a collection of uproot ntuples and a dictionary from
track types to desired properties to be included, returns an ntuple
dictionary formed by selecting properties from the ntuples and th... | e4f391fc0c63e73ff320e973f624e43841a3613f | 26,479 |
from datetime import datetime
def get_container_sas_token(block_blob_client,
container_name, blob_permissions):
"""
Obtains a shared access signature granting the specified permissions to the
container.
:param block_blob_client: A blob service client.
:type block_blob_... | f17623e721e84a0953565854f2e2eedfb4f8afe6 | 26,480 |
from pytorch3d.io import load_obj
from typing import Optional
from typing import Tuple
import torch
from typing import NamedTuple
import os
import time
def create_mesh(
pdb_file: Optional[str] = None,
pdb_code: Optional[str] = None,
out_dir: Optional[str] = None,
config: Optional[ProteinMeshConfig] = ... | f44e430e2ab5ecfb9cfdb219453272563e99336e | 26,481 |
import os
import logging
def init_logger(logger_name="pfp_log", log_file_name="pfp.log", to_file=True, to_console=True):
"""
Purpose:
Returns a logger object.
Usage:
logger = pfp_log.init_logger()
Author: PRI with acknowledgement to James Cleverly
Date: September 2016
"""
# creat... | 6442c68b1f5d1a7df34ed1e604cee5b4c091fd97 | 26,482 |
def to_one_hot(y):
"""Transform multi-class labels to binary labels
The output of to_one_hot is sometimes referred to by some authors as the
1-of-K coding scheme.
Parameters
----------
y : numpy array or sparse matrix of shape (n_samples,) or
(n_samples, n_classes... | 134f4bce729c98439bdca2cd586f95d0cc9178c7 | 26,483 |
def random():
"""
getting a random number from 0 to 1
"""
return randrange(10000) / 10000 | 12ab43d5e5c8a9a993f8053363e56c2acf8b0ceb | 26,484 |
from typing import Union
def parameter_string_to_value(
parameter_string: str,
passthrough_estimate: bool = False,
) -> Union[float, int, str]:
"""Cast a parameter value from string to numeric.
Args:
parameter_string:
The parameter value, as a string.
passthrough_estimate:... | 3271acf50f5171703e16bce183d246d149d5e053 | 26,485 |
import sys
import os
import urllib
import traceback
def getNLCDRasterDataForBoundingBox(config, outputDir, bbox,
coverage=DEFAULT_COVERAGE,
filename='NLCD',
srs='EPSG:4326',
... | dbae7825d91b6a6dc3bf904391b47603ed29d092 | 26,486 |
def rfsize(spatial_filter, dx, dy=None, sigma=2.):
"""
Computes the lengths of the major and minor axes of an ellipse fit
to an STA or linear filter.
Parameters
----------
spatial_filter : array_like
The spatial receptive field to which the ellipse should be fit.
dx : float
... | a2e184dd597c840392c05d0955dba826aa528a06 | 26,487 |
import json
def get_config_from_json(json_file):
"""
Get the config from a json file
:param json_file:
:return: config(namespace) or config(dictionary)
"""
# parse the configurations from the config json file provided
with open(json_file, 'r') as config_file:
config_dict = json.loa... | 17aec6d1d0413836f647b222681e32af1a298fbc | 26,488 |
from pathlib import Path
def create_polarimetric_layers(import_file, out_dir, burst_prefix, config_dict):
"""Pipeline for Dual-polarimetric decomposition
:param import_file:
:param out_dir:
:param burst_prefix:
:param config_dict:
:return:
"""
# temp dir for intermediate files
wi... | ddfd3d9b12aefcf5f60b254ad299c59d4caca837 | 26,489 |
import argparse
def parse_args():
"""Parse argument values from command-line"""
parser = argparse.ArgumentParser(description='Arguments required for script.')
parser.add_argument('-t', '--job-type', required=True, choices=['process', 'analyze'], help='process or analysis')
args = parser.parse_args()
... | c8ca3ad879db8c9dbfb2a3fb044a747a856304e7 | 26,490 |
from typing import Literal
import math
def Builtin_FLOOR(expr, ctx):
"""
http://www.w3.org/TR/sparql11-query/#func-floor
"""
l_ = expr.arg
return Literal(int(math.floor(numeric(l_))), datatype=l_.datatype) | 495d7e2133028030e1766d0a04eb3d20f800b918 | 26,491 |
import requests
def get(target: str) -> tuple:
"""Fetches a document via HTTP/HTTPS and returns a tuple containing a boolean indicating the result of the request,
the URL we attempted to contact and the request HTML content in bytes and text format, if successful.
Otherwise, returns a tuple containing ... | 1d9d650d77776419318cbd204b722d8abdff94c5 | 26,492 |
def DOM2ET(domelem):
"""Converts a DOM node object of type element to an ElementTree Element.
domelem: DOM node object of type element (domelem.nodeType == domelem.ELEMENT_NODE)
returns an 'equivalent' ElementTree Element
"""
# make some local variables for fast processing
tyCDATA = domelem.CD... | b8288a2704995ec4fbe4dc1bc2805cd7658beb35 | 26,493 |
import torch
def f_score(pr, gt, beta=1, eps=1e-7, threshold=.5):
"""dice score(also referred to as F1-score)"""
if threshold is not None:
pr = (pr > threshold).float()
tp = torch.sum(gt * pr)
fp = torch.sum(pr) - tp
fn = torch.sum(gt) - tp
score = ((1 + beta ** 2) * tp + eps) \
... | 2c54fd24cd04ac2b41a9d5ca4bf8a7afc5e88640 | 26,494 |
def makeSatelliteDir(metainfo):
"""
Make the directory name for the 'satellite' level.
"""
satDir = "Sentinel-" + metainfo.satId[1]
return satDir | dfbb43f235bc027f25fc9b624097e8f2e0dee4f9 | 26,495 |
import os
import re
def parse_requirements(file_name):
"""Taken from http://cburgmer.posterous.com/pip-requirementstxt-and-setuppy"""
requirements = []
for line in open(os.path.join(os.path.dirname(__file__), "config", file_name), "r"):
line = line.strip()
# comments and blank lines
if re.match(r"(^#)|(^$)",... | f34892163087cecdf84aa7f14da4fc5e56e9f100 | 26,496 |
def resolve_tagged_field(field):
"""
Fields tagged with `swagger_field` shoudl respect user definitions.
"""
field_type = getattr(field, SWAGGER_TYPE)
field_format = getattr(field, SWAGGER_FORMAT, None)
if isinstance(field_type, list):
# Ideally we'd use oneOf here, but OpenAPI 2.0 use... | 90f59615395350dbd0f2ff3ff5573f28e926dada | 26,497 |
def grid_id_from_string(grid_id_str):
"""Convert
Parameters
----------
grid_id_str : str
The string grid ID representation
Returns
-------
ret : tuple of ints
A 4-length tuple representation of the dihedral id
"""
return tuple(int(i) for i in grid_id_str.split(',')) | cec058302aae701c1aa28fcb4c4a9d762efa724e | 26,498 |
def adj_to_edge_index(adj):
"""
Convert an adjacency matrix to an edge index
:param adj: Original adjacency matrix
:return: Edge index representation of the graphs
"""
converted = []
for d in adj:
edge_index = np.argwhere(d > 0.).T
converted.append(edge_index)
return con... | e2c047a6c60bfb3ea109e8686a810749a726265f | 26,499 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.