content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def vect3_scale(v, f):
"""
Scales a vector by factor f.
v (3-tuple): 3d vector
f (float): scale factor
return (3-tuple): 3d vector
"""
return (v[0]*f, v[1]*f, v[2]*f) | 94902cad0a7743f8e3ed1582bf6402229b8a028d | 3,631,500 |
from typing import Optional
def segment_max(data: Array,
segment_ids: Array,
num_segments: Optional[int] = None,
indices_are_sorted: bool = False,
unique_indices: bool = False,
bucket_size: Optional[int] = None,
mode: Opti... | 2e98814bd37be39cc7abadd0cb795471e267d050 | 3,631,501 |
from typing import List
from typing import Any
from typing import Optional
def _recursive_pad(nested: List[Any], fill_value: Optional[Any] = None) -> np.array:
"""Pads a jagged nested list of lists with the given value such that a proper multi-dimensional array can be
formed with rectangular shape. The paddin... | 2ab19444f0b3e2e865d51f24b590de5a1d814c96 | 3,631,502 |
def create_trigger_body(trigger):
"""Given a trigger, remove all keys that are specific to that trigger
and return keys + values that can be used to clone another trigger
https://googleapis.github.io/google-api-python-client/docs/dyn/tagmanager_v2.accounts.containers.workspaces.triggers.html#create
:p... | 3b324407e77c1f17a5f76f82181db4976966e21b | 3,631,503 |
from typing import Union
def is_less_or_equal(hash_1: Union[str, bytes],
hash_2: Union[str, bytes]) -> bool:
"""check hash result."""
if isinstance(hash_1, str):
hash_1 = utils.hex_str_to_bytes(hash_1)
if isinstance(hash_2, str):
hash_2 = utils.hex_str_to_bytes(hash_2)... | 1633aa11587669d67ddd49eae9d73ab061e7e69b | 3,631,504 |
def get_video_id(url):
""" Get YouTube video ID from YouTube URL
Args:
url (str): YouTube URL.
Returns:
YouTube id
"""
if not url:
return ""
# If URL is embedded
if "embed" in url:
return url.split("/")[-1]
parse_result = urlparse(url)
query = par... | 9253bb3c11a4ed0ceaddfcb5b848de9157d9b290 | 3,631,505 |
import sys
def running_under_virtualenv():
# type: () -> bool
"""
Return True if we're running inside a virtualenv, False otherwise.
"""
if hasattr(sys, 'real_prefix'):
# pypa/virtualenv case
return True
elif sys.prefix != getattr(sys, "base_prefix", sys.prefix):
# PEP... | 8266c6d3dd7fe05e51797208fc978c481093f8d0 | 3,631,506 |
def _tile_to_image_size(tensor, image_shape):
"""Inserts `image_shape` dimensions after `tensor` batch dimension."""
non_batch_dims = len(tensor.shape) - 1
for _ in image_shape:
tensor = tf.expand_dims(tensor, axis=1)
tensor = tf.tile(tensor, [1] + image_shape + [1] * non_batch_dims)
return tensor | 57b460e58e3e9c705af62c87479ce6d4c81c787b | 3,631,507 |
def icp3d(src, trgt, abs_tol=1e-8, max_iter=500, verbose=True):
"""
Parameters
----------
src : numpy array
Source object. Each row should be a point with (X, Y, Z) columns.
trgt : numpy array
Target object. Each row should be a point with (X, Y, Z) columns.
abs_tol : float, opt... | 969dc9bc2b0fce2933c7a31d45ab98089619e7d1 | 3,631,508 |
def event_type(event):
"""
.. function:: event_type(event)
Return pygame event type.
"""
return getattr(pygame, event) | de49421703a98df43ac57a5beea7acb042eaa8ff | 3,631,509 |
def ULA(step, N, n):
""" MCMC ULA
Args:
step: stepsize of the algorithm
N: burn-in period
n: number of samples after the burn-in
Returns:
traj: a numpy array of size (n, d), where the trajectory is stored
traj_grad: numpy array of size (n, d), where the gradients of t... | 36772e2988f35e408fc72da8bb71a78de602aee8 | 3,631,510 |
import logging
def get_parameters(parameters):
"""Get parameters from a function definition"""
params_out = {}
for parameter in parameters:
param_out = {}
# TODO
# Resolve meta refs
# if "$ref" in param.keys():
# meta_path = param["$ref"].split("/")
# ... | f66f3d5f0799cbbec38af57f324671521b38ec32 | 3,631,511 |
def openbabel_mol_to_rdkit_mol(obmol: 'openbabel.OBMol',
remove_hs: bool = False,
sanitize: bool = True,
embed: bool = True,
) -> 'RWMol':
"""
Convert a OpenBabel molecular structure to a ... | ab30d50013aa7f8d0c45a7d502471afb42f8aa57 | 3,631,512 |
def get_display_name(record):
"""Get the display name for a record.
Args:
record
A record returned by AWS.
Returns:
A display name for the bucket.
"""
return record["Name"] | a34c1c416cc41ae5f0087ba471d75b4bc5c87216 | 3,631,513 |
import math
def RadialToTortoise(r, M):
"""
Convert the radial coordinate to the tortoise coordinate
r = radial coordinate
M = ADMMass used to convert coordinate
return = tortoise coordinate value
"""
return r + 2. * M * math.log( r / (2. * M) - 1.) | 1bbfad661d360c99683b3c8fbe7a9c0cabf19686 | 3,631,514 |
from typing import Set
def extract_leaves(
tree_dict: StrDict,
) -> Set[str]:
"""
Extract a set with the SMILES of all the leaf nodes, i.e.
starting material
:param tree_dict: the route
:return: a set of SMILE strings
"""
def traverse(tree_dict: StrDict, leaves: Set[str]) -> None:
... | c932426f8d308a840690347bdd41af402bf6880a | 3,631,515 |
def station_matcher(
data_stream_df,
ses_directory="../data/seattle_ses_data/ses_data.shp"):
""" Matches Purple Air data with census tracts
This function reads in the census-tract-level socioenconomic
dataset and joins it with the input Purple Air DataStreams.
Args:
data_stream_df... | 9b4c1293d7987138d17c9ec6606fff18d4a6e8c6 | 3,631,516 |
def running(pid):
"""
pid: a process id
Return: False if the pid is None or if the pid does not match a
currently-running process.
Derived from code in http://pypi.python.org/pypi/python-daemon/ runner.py
"""
if pid is None:
return False
try:
os.kill(pid, signal.SIG_DFL)
... | 622951e6d5c2f832516e00a607e6ac612ce365a9 | 3,631,517 |
import requests
import json
def get_pulls_list(project, github_api=3):
"""get pull request list
github_api : version of github api to use
"""
if github_api == 3:
url = f"https://api.github.com/repos/{project}/pulls"
else:
url = f"http://github.com/api/v2/json/pulls/{project}"
... | 891c99d53faa5fb89960e5bb52c85e42f6003c42 | 3,631,518 |
import os
import re
def get_version(*file_paths):
"""Retrieves the version from flexible_reports/__init__.py"""
filename = os.path.join(os.path.dirname(__file__), *file_paths)
version_file = open(filename).read()
version_match = re.search(r"^__version__ = ['\"]([^'\"]*)['\"]",
... | 37439dc2f5aa1c49cd82978c26f4092b21fbad29 | 3,631,519 |
import urllib
import json
def get_articles(id):
"""
Function that gets the json response to our url request
"""
get_sources_news_url = source_url.format(id,api_key)
with urllib.request.urlopen(get_sources_news_url)as url:
get_news_data = url.read()
get_news_response = json.loads(ge... | 5a2e2410561302b4023746559edd28102ccaa527 | 3,631,520 |
def read_chunk(path, start_offset, end_offset, delete_me_entire_func_maybe):
"""
Return only if 100% successful.
"""
try:
with open(path, 'rb') as f:
f.seek(start_offset)
return f.read(end_offset - start_offset)
except FileNotFoundError as e:
raise e | e45c948bcb7f75fdf0eecac8289e4323b2d88dfe | 3,631,521 |
def returnBestAddress(genes, loop):
"""Searches for available genes matching kegg enzyme entry.
This function searches 'sequentially'. It returns the best available model
organism genes. Organisms phylogenetically closer to Cricetulus griseus are
preferred, but they are chosen by approximation. A detai... | af38d9456120dbbe99a243764dea20e52d0ba3c1 | 3,631,522 |
from typing import Any
def is_name_like_value(
value: Any, allow_none: bool = True, allow_tuple: bool = True, check_type: bool = False
) -> bool:
"""
Check the given value is like a name.
Examples
--------
>>> is_name_like_value('abc')
True
>>> is_name_like_value(1)
True
>>> i... | f465c0e660399c4c330dc08d24cde479dfd0ff47 | 3,631,523 |
def get_uptime(then):
"""
then: datetime instance | string
Return a string that informs how much time has pasted from the provided
timestamp.
"""
if isinstance(then, str):
then = dt.datetime.strptime(then, "%Y-%m-%dT%H:%M:%SZ")
now = dt.datetime.now()
diff = now - then.replace(... | b1110c9c3edfd4960405b74da8da57e5f455775d | 3,631,524 |
import subprocess
import click
def _create_kube_config_gcloud_entry(cluster_name, cluster_zone, project):
"""Uses GCloud CLI to create an entry for Kubectl.
This is needed as we install the charts using kubectl, and it needs the correct config
Args:
cluster_name (str): Name of cluster
cl... | b161e397445393bde989b6ae9dec1353fec38329 | 3,631,525 |
import torch
def gaussian2kp(heatmap, kp_variance='matrix', clip_variance=None):
"""
Extract the mean and the variance from a heatmap
"""
shape = heatmap.shape
#adding small eps to avoid 'nan' in variance
heatmap = heatmap.unsqueeze(-1) + 1e-7
grid = make_coordinate_grid(shape[3:], heatmap... | 5953e9ef4e0717341f01555e227868a5a4b2fc2d | 3,631,526 |
def BRepBlend_HCurve2dTool_Circle(*args):
"""
:param C:
:type C: Handle_Adaptor2d_HCurve2d &
:rtype: gp_Circ2d
"""
return _BRepBlend.BRepBlend_HCurve2dTool_Circle(*args) | e3087d0e9e1505b47d10066b2a4ab25d72b15de2 | 3,631,527 |
import inspect
import math
def patchMath():
""" Overload various math functions to work element-wise on iterables
>>> A = Array([[0.0, pi/4.0], [pi/2.0, 3.0*pi/4.0], [pi, 5.0*pi/4.0], [3.0*pi/2.0, 7.0*pi/4.0]])
>>> print(round(A,2).formated())
[[0.0, 0.79],
[1.57, 2.36],
... | da29f21ee08bfee29d9cd62148384fbd0fa9ede7 | 3,631,528 |
def iddr_rid(m, n, matvect, k):
"""
Compute ID of a real matrix to a specified rank using random matrix-vector
multiplication.
:param m:
Matrix row dimension.
:type m: int
:param n:
Matrix column dimension.
:type n: int
:param matvect:
Function to apply the matri... | 7878a49dfa4e0c7c4530e16fb904a6778ee2aa3d | 3,631,529 |
def MediumOverLong(lengths):
"""
A measure of how needle or how plate-like a molecules is.
0 means perfect needle shape
1 means perfect plate-like shape
ShortOverLong = Medium / Longest
"""
return lengths[1]/lengths[2] | 48a053b55b39a50d7b0f618f843d370a55220765 | 3,631,530 |
import base64
from pathlib import Path
def cbase64(obj, mode: int = 1, to_file: t.Union[str, Path] = None, altchars=None, validate=False):
"""
base64加密与解密
使用示例:
# 1)针对字符
obj = b'这是一个示例'
cobj = crypto.cbase64(obj)
# 2)针对文件
obj = 'D:/tmp/t.txt'
to_file = 'D:/t... | bb70ddb23185e8934c2c31400f4eb0c0adaee202 | 3,631,531 |
from typing import Optional
import os
import re
def change_suffix(fname: str, new_suffix: str, old_suffix: Optional[str] = None) -> str:
"""Change suffix of filename.
Changes suffix of a filename. If no old suffix is provided, the part that is replaced is guessed.
Args:
fname: Filename to proces... | ae9f4c05d88d8d293e59d8e8a58b8961a36c568c | 3,631,532 |
def segment_objects(white_cloud):
"""
Cluster extraction and create cluster mask
"""
tree = white_cloud.make_kdtree()
# Create a cluster extraction object
ec = white_cloud.make_EuclideanClusterExtraction()
# Set tolerances for distance threshold
# as well as minimum and maximum cluster ... | 590c3d75a1739128d97e998a601e92e335507915 | 3,631,533 |
import sys
def new_markers():
"""
Read name of packages from scripts arguments and create set of them.
"""
new_markers = set()
for x in sys.argv[1:]:
if check_package(x):
new_markers.add(x)
else:
error(f"ERROR: Package {x} not installed in system. Can't mark... | 42bfebc5669e211fdc2c1fa039293bf35c46d9fb | 3,631,534 |
def form():
"""Dummy endpoint for demonstration purposes."""
return [
ActionFormField(
name='email_address',
label='Email Address',
description='Email address to send PowerPoint document',
required=True,
),
ActionFormField(
name... | 9b10b3621f39d061c448d3e3d0c512dc0d1639fe | 3,631,535 |
import cmd
def task_pgtune_tune():
"""
pgtune: Apply Greg Smith's pgtune.
"""
def alter_sql():
with open(PGTUNE_CONF, "r") as f:
for line in f:
if "=" in line:
key, val = [s.strip() for s in line.split("=")]
sql = f"ALTER SYS... | 489e8ab45b139620ca621be5600f6c61dbf81210 | 3,631,536 |
def rescale_exchange(exc, value, remove_uncertainty=True):
"""Dummy function to rescale exchange amount and uncertainty.
This depends on some code being separated from Ocelot, which will take a bit of time.
* ``exc`` is an exchange dataset.
* ``value`` is a number, to be multiplied by the existing amo... | b3fee3bc20632563722b624dd35e4fa6a3a5b9c8 | 3,631,537 |
def create():
"""
does setup of Tellor contract on Alogrand
solidity equivalent: constructor()
args:
0) governance address
1) query id
2) query data
"""
return Seq(
[
App.globalPut(tipper, Txn.sender()),
# TODO assert application args length is corre... | d875d137d66b00d33241c5bd25e977e70d903f45 | 3,631,538 |
import json
import os
def task(args):
"""Find the adequate limits for a task."""
solutionList = args.path[:]
if args.usecorrect or len(args.path) == 0:
try:
taskSettings = json.load(open(os.path.join(args.taskpath, 'taskSettings.json'), 'r'))
correctSolutions = taskSettings... | 6aed71c44ad23e890f1d419239208da9409e8004 | 3,631,539 |
def merge_channels(channels):
""" Takes a list of channels as input and outputs the image obtained by merging the channels """
return channels[0] if len(channels) == 1 else cv2.merge(tuple(channels)) | 7eff099248f40d8c166c711d341834d5db0c1b7f | 3,631,540 |
import warnings
def rng(spec=None, *, legacy=False):
"""
Get a random number generator. This is similar to :func:`sklearn.utils.check_random_seed`, but
it usually returns a :class:`numpy.random.Generator` instead.
.. warning::
This method is deprecated. Use :func:`seedbank.numpy_rng` instea... | 63b6cfa03c336c31f47da7b215888335b37da5e4 | 3,631,541 |
def create_sdcard_tar (adb,tarpath):
"""
Returns the remote path of the tar file containing the whole WhatsApp directory from the SDcard
"""
tarname = '/sdcard/whatsapp_' + ''.join(random.choice(string.letters) for i in xrange(10)) + '.tar'
print "\n[+] Creating remote tar file: %s" % tarname
cm... | 4d01bedc86c18cb43d53ce4c53be06e1eb7b1232 | 3,631,542 |
import pickle
import os
def table_coverage(class_name, name, root, Xsamp, burnin=500, MC=None, plot=False, movie=False, thinning=1,
loadDict=False, CI='quant'):
"""
:param class_name:
:param name:
:param root:
:param burnin:
:param MC:
:param plot:
:return:
"""
... | 1b2998769dce95c35f9041d0da3ead564941ed06 | 3,631,543 |
def roll_zeropad(a, shift, axis=None):
"""
Roll array elements along a given axis.
Elements off the end of the array are treated as zeros.
Args:
a: array_like
Input array.
shift: int
The number of places by which elements are shifted.
axis (int): optional... | 97d29b4aff48580367d6c0ed474ca1ba020e2cf8 | 3,631,544 |
from typing import Callable
from typing import Any
from typing import Coroutine
def callable_to_coroutine(func: Callable, *args: Any, **kwargs: Any) -> Coroutine:
"""Transform callable to coroutine.
Arguments:
func: function that can be sync or async and should be transformed into
corouin... | 44fc48295f61ac0b7c74cfa9d9724473afb272ea | 3,631,545 |
import six
import warnings
def construct_engine(engine, **opts):
""".. versionadded:: 0.5.4
Constructs and returns SQLAlchemy engine.
Currently, there are 2 ways to pass create_engine options to :mod:`migrate.versioning.api` functions:
:param engine: connection string or a existing engine
:para... | 10acf0bbee55391d5bdc63038d4f43f451c78818 | 3,631,546 |
def array_to_binary(array, start=None, end=None):
"""Create binary search tree from `array` values via recursion."""
start = 0 if start is None else start
end = len(array) - 1 if end is None else end
if start > end:
return ''
mid = (start + end) // 2
node = Node(array[mid])
node.left... | 263fc8869961b3412d61288bd5aa562b8221ae37 | 3,631,547 |
async def handle_slack_command(*, db_session, client, request, background_tasks):
"""Handles slack command message."""
# We fetch conversation by channel id
channel_id = request.get("channel_id")
conversation = conversation_service.get_by_channel_id_ignoring_channel_type(
db_session=db_session, ... | 890db0570da2782482c4c1a2aa2772fbada48278 | 3,631,548 |
def load_cert_files(
common_name, key_file, public_key_file, csr_file, certificate_file,
crl_file
):
"""Loads the certificate, keys and revoked list files from storage
:param common_name: Common Name for CA
:type common_name: str, required when there is no CA
:param key_file: key file full path... | fe8a3765e020e91880f6b44791e37b59002eb13e | 3,631,549 |
def parse_note(note: Note) -> MetaEvent:
"""
Parse a single non system note.
"""
attributes = {}
attributes["event"] = "note"
attributes["note_id"] = note["id"]
attributes["content"] = note["body"]
attributes["event_id"] = note["id"]
attributes["noteable_id"] = note["noteable_id"]
... | 8105ca5da84a1fc85fae0351d446b9d1dd9fae4b | 3,631,550 |
def get_mvdr_vector(atf_vector, noise_psd_matrix):
"""
Returns the MVDR beamforming vector.
:param atf_vector: Acoustic transfer function vector
with shape (..., bins, sensors)
:param noise_psd_matrix: Noise PSD matrix
with shape (bins, sensors, sensors)
:return: Set of beamforming ... | 70249a7795c07ed15f351b158cbf6dc1b83895ec | 3,631,551 |
def get_numpy(required=True):
"""Tries to import numpy.
If `required` is False, don't ask again if the user already declined;
return None if numpy is not available.
If `required` is True, do ask to install, and raise ImportError if numpy
can't be set up.
"""
global _numpy
if _numpy is ... | 1cb4486de4231f93b73f1bc649a1a05454faf530 | 3,631,552 |
def norm_pdf(x, mu, sigma):
"""
Return probability density of normal distribution.
"""
z = (x - mu) / sigma
c = 1.0 / np.sqrt(2 * np.pi)
return np.exp(-0.5 * z ** 2) * c / sigma | 12db092dad01331b15366b4819d4fde9e631b8de | 3,631,553 |
import sqlite3
def delete_diagnosis(request):
"""
This method is used to delete diagnosis data in diagnosis table.
Query Explanation:
- Delete data in diagnosis table.
:param request:
:return:
"""
if request.method == 'POST':
con = sqlite3.connect("Hospital.db")
con.row... | 53cf92845c2df00f0fced044bb8faf95530deba6 | 3,631,554 |
def chip_calibration(
data,
mol="O2",
F_cal=None,
primary=None,
tspan=None,
tspan_bg=None,
t_bg=None,
gas="air",
composition=None,
chip="SI-3iv1",
):
"""
Returns obect of class EC_MS.Chip, given data for a given gas (typically air) for which
one component (typically O... | 321ccc5a229c4a9ebf4be80614340e32aef6231c | 3,631,555 |
import string
def tamper(payload, **kwargs):
"""
Unicode-escapes non-encoded characters in a given payload (not processing already encoded) (e.g. SELECT -> \u0053\u0045\u004C\u0045\u0043\u0054)
Notes:
* Useful to bypass weak filtering and/or WAFs in JSON contexes
>>> tamper('SELECT FIELD FRO... | ef293a5be9698dea8f01186a38794ff9c3482c94 | 3,631,556 |
def to_axis_aligned_ras_space(image):
""" Transform the image to the closest axis-aligned approximation of RAS
(i.e. Nifti) space
"""
return to_axis_aligned_space(image, medipy.base.coordinate_system.RAS) | c7bb77a1e141672f2d8ea4ecb76c3b3dd0a00d66 | 3,631,557 |
def _fixParagraphs(element):
"""
moves paragraphs so they are child of the last section (if existent)
"""
if isinstance(element, advtree.Paragraph) and isinstance(element.previous, advtree.Section) \
and element.previous is not element.parent:
prev = element.previous
parent ... | 0875e08afe27171a0bd8773298a320acd93a0382 | 3,631,558 |
def dice_loss(label, target):
"""Soft Dice coefficient loss
TP, FP, and FN are true positive, false positive, and false negative.
.. math::
dice &= \\frac{2 \\times TP}{ 2 \\times TP + FN + FP} \\\\
dice &= \\frac{2 \\times TP}{(TP + FN) + (TP + FP)}
objective is to maximize the d... | 526104e7ba1fd974444b1141913d593e4ee4efb1 | 3,631,559 |
from typing import Union
from typing import List
def no_subseqs(x_tokens: Union[List[str], str]) -> bool:
"""
Checks to see whether a string lacks the subsequences ab, bc, cd,
and dc.
:param x_tokens: A string
:return: True iff x_tokens does not have any subsequences
"""
letters = set()
... | 434dade2ca1801bed0895a79ba281f90e6b78177 | 3,631,560 |
import torch
def _get_random_R():
""" random angle-axis -> Rodrigues """
random_angle_axis = torch.tensor(np.random.rand(1, 3))
return RodriguesBlock()(random_angle_axis).numpy()[0] | 69fd6cfe7a8338941b67b77448941d17cc2c16d0 | 3,631,561 |
from datetime import datetime
def timestamp_to_iso(timestamp):
"""
Converts an ISO 8601 timestamp (in the format `YYYY-mm-dd HH:MM:SS`) to :class:`datetime`
Example:
>>> timestamp_to_iso(timestamp='2020-02-02 02:02:02')
datetime(year=2020, month=2, day=2, hour=2, minute=2, second=2)
... | 7de7ea8b1fd5bd4d854c43b9818bf6f8f58da279 | 3,631,562 |
def rename_category_for_flattening(category, category_parent=""):
"""
Tidy name of passed category by removing extraneous characters such as '_' and '-'.
:param category: string to be renamed (namely, a category of crime)
:param category_parent: optional string to insert at the beginning of the str... | 360e87da0a8a778f32c47adc58f33a2b92fea801 | 3,631,563 |
import math
def billing_bucket(t):
"""
Returns billing bucket for AWS Lambda.
:param t: An elapsed time in ms.
:return: Nearest 100ms, rounding up, as int.
"""
return int(math.ceil(t / 100.0)) * 100 | 87b9963c1a2ef5ad7ce1b2fac67e563dcd763f73 | 3,631,564 |
import hashlib
def filename_to_int_hash(text):
"""
Returns the sha1 hash of the text passed in.
"""
hash_name_hashed = hashlib.sha1(text.encode("utf-8")).hexdigest()
return int(hash_name_hashed, 16) | b5cb53b921146d4ae124c20b0b267acc80f6de43 | 3,631,565 |
def export():
"""Export all components and connected nets, as a netlist in KiCad pcbnew compatible format.
This also saves a database with all captured internal information about
schematic, components and nets. These information are used in subsequent
runs to ensure stable designators.
"""
return export_(_... | 141c670b43f831cc4374692370f5f651445486fb | 3,631,566 |
def dropout(x, rate, training=None):
"""Simple dropout layer."""
if not training or rate == 0:
return x
if compat.is_tf2():
return tf.nn.dropout(x, rate)
else:
return tf.nn.dropout(x, 1.0 - rate) | 77ba40883e76366de27d15fc03f601d7efdcae0b | 3,631,567 |
import re
def readFastQ(fastq_path):
"""
Reads fastq file and returns a dictionary with the header as a key
"""
with open(fastq_path,'r') as FASTQ:
fastq_generator = FastqGeneralIterator(FASTQ)
readDict = {re.sub('/[1-2]','',header).split(' ')[0]:(seq,qual) for header,
... | 4dbcbb8d7ba8a6b5d77c2477c2b97d00d4a9a19c | 3,631,568 |
def dilation(args) -> list:
"""Compute dilation of a given object in a segmentation mask
Args:
args: masks, obj and dilation kernel
Returns:
"""
mask, obj, kernel = args
dilated_img = binary_dilation(mask == obj, kernel)
cells = np.unique(mask[dilated_img])
cells = cells[cells... | f9edc59e4db7e8774916542be887e0ad3a82ec78 | 3,631,569 |
def adjust_lr_on_plateau(optimizer):
"""Decrease learning rate by factor 10 if validation loss reaches a plateau"""
for param_group in optimizer.param_groups:
param_group['lr'] = param_group['lr']/10
return optimizer | 615631fd4853e7f0c0eae59a3336eb4c4794d3a3 | 3,631,570 |
import os
def generate_key():
"""
生成节点公私钥
:return:
私钥
公钥
"""
extra_entropy = ''
extra_key_bytes = text_if_str(to_bytes, extra_entropy)
key_bytes = keccak(os.urandom(32) + extra_key_bytes)
privatekey = keys.PrivateKey(key_bytes)
pubKey = keys.private_key_to_public_ke... | fc04640b04bf316c160fc21f0482a6ffd33d72cc | 3,631,571 |
from typing import List
from typing import Dict
from typing import Any
from typing import Union
def get_partial_match_metrics(
preds: List[List[str]], labels: List[List[str]]
) -> Dict[Any, Any]:
"""
Suppose there are N such pairs in the gold data and the system predicts M such pairs. Say a ‘partial match... | 05eaf9fce152e6266698e9b5613a2770a000c48d | 3,631,572 |
def find_submission_id_command(
client: Client,
limit: int = 50,
filter: str = "",
offset: str = "",
sort: str = "",
) -> CommandResults:
"""Find submission IDs for uploaded files by providing an FQL filter and paging details.
:param client: the client object with an acce... | e7e285c8d2b10af6ab7d0337cb0db7bea2664478 | 3,631,573 |
def average(aggregation, discard_zeros=False):
"""Perform the average aggregation"""
# This method take the data from the inmediate lower granularity and computes the
# average, then it insert the new average
try:
# Calculate the inmediate lower granularity:
LOGGER.debug('Requested gran... | f6e7d7338c2ada52c7ec6f8abd30dcdeba07e1ff | 3,631,574 |
def chain(node1, node2, include_ids=False, only_ids=False):
"""
Find a chain of dependency tags from `node1` to `node2` (if possible)
:param node1: The node 1
:type node1: udon2.Node
:param node2: The node 2
:type node2: udon2.Node
"""
node, chain = node2, ... | bcfe1497ea731ad902bc5760542c8ce6f3286b60 | 3,631,575 |
def parallax(sc, d2p=True, **kw):
"""Parallax.
Parameters
----------
sc: SkyCoord
** warning: check if skycoord frame centered on Earth
d2p: bool
if true: arg = distance -> parallax_angle
else: arg = parallax_angle -> distance
Returns
-------
parallax_angle o... | d2d79dd67a07e71ef6a411fd4567c591335cbe83 | 3,631,576 |
def dense(x, output_dim, reduced_dims=None, expert_dims=None,
use_bias=True, activation=None, name=None):
"""Dense layer doing (kernel*x + bias) computation.
Args:
x: a mtf.Tensor of shape [..., reduced_dims].
output_dim: a mtf.Dimension
reduced_dims: an optional list of mtf.Dimensions of x t... | 1303b164c266759f617f6abf3cfba07fdeff5ccd | 3,631,577 |
import os
def record_CT(dataset_path):
"""load CT image folds into json format
"""
patients_dict = dict()
for p in os.listdir(dataset_path):
print(p)
patient_path = osp.join(dataset_path, p)
studies_list = dict()
for study in os.listdir(patient_path):
study_... | 8b1ecf09f0b22ec4901e9844cf896a9321401489 | 3,631,578 |
import select
def requires_cuda_enabled():
"""Returns constraint_setting that is not satisfied unless :is_cuda_enabled.
Add to 'target_compatible_with' attribute to mark a target incompatible when
@rules_cuda//cuda:enable_cuda is not set. Incompatible targets are excluded
from bazel target wildcards ... | aec9d4c9ed55c44aaf0f6d3e6862bf6b0c24471e | 3,631,579 |
from typing import Union
from typing import Any
from typing import Callable
import warnings
def add_activated_handler(parent : Union[int, str], *, label: str =None, user_data: Any =None, use_internal_label: bool =True, tag: Union[int, str] =0, callback: Callable =None, show: bool =True) -> Union[int, str]:
"""
Adds... | d3b107b0cd1d1fef195590a01d923adf8e84ee24 | 3,631,580 |
import logging
import sys
import csv
import configparser
import toml
import json
def main(argv=None, abort=False, debug=None):
"""Drive the validator.
This function acts as the command line interface backend.
There is some duplication to support testability.
"""
init_logger(level=logging.DEBUG if ... | 9ad9f8f7a4666c093f908cf3514ec2528a1214ff | 3,631,581 |
import os
import fnmatch
import time
def filter_files(files, search_settings):
"""
Filter a list of files based on the search settings
"""
ret_val = []
patterns = search_settings['patterns']
for f in files:
try:
file_path = f.path
except AttributeError:
... | 4f33968ad37ebbb0b18d1440ce14c40af7a32d79 | 3,631,582 |
def application(service, custom_app_plan, custom_application, request):
"""First application bound to the account and service_plus"""
plan = custom_app_plan(rawobj.ApplicationPlan(blame(request, "aplan")), service)
return custom_application(rawobj.Application(blame(request, "app"), plan)) | dc27ecd53a276bf194e92c6ee716b94fa2cf1445 | 3,631,583 |
def printf_line(*args):
"""printf_line(int indent, char format, v(...) ?) -> bool"""
return _idaapi.printf_line(*args) | a1a9214f6c4013d3654187724839b6aeed1c4220 | 3,631,584 |
import logging
def baseline_correction_using_plane(coh_ab,uw_phase,kz):
""" Baseline correction based on a plane
WARNINGS:
- From choi idl code
- We should really check with TAXI the baseline correction for a better processing
Parameters
----------
coh_ab : 2D numpy array
... | f8d812bb019d0d96d23440d51315aaa40448a5b2 | 3,631,585 |
import os
def load_example_asos() -> DataFrame:
"""
Fixture to load example data
"""
example_data_path = os.path.abspath(
os.path.join(os.path.dirname(__file__), os.pardir, os.pardir, "staticdata")
)
data_path = os.path.join(example_data_path, "AMW_example_data.csv")
return meteog... | fb411893a5e40c03d451c0cd4a6e707bf85653e6 | 3,631,586 |
def variable(default=None, dependencies=(), holds_data=True):
"""
Required decorator for data_dict of custom structs.
The enclosing class must be decorated with struct.definition().
:param default: default value passed to validation if no other value is specified
:param dependencies: other items (string or ... | fdc11425beddaf47985cea7729244ac073922794 | 3,631,587 |
def define_circle(p1, p2, p3):
"""
Returns the center and radius of the circle passing the given 3 points.
In case the 3 points form a line, returns (None, infinity).
"""
temp = p2[0] * p2[0] + p2[1] * p2[1]
bc = (p1[0] * p1[0] + p1[1] * p1[1] - temp) / 2
cd = (temp - p3[0] * p3[0] - p3[1] *... | aedb4bc6173df09962ab81a4124acbd245af7612 | 3,631,588 |
def create_upload_token(self, request, form):
""" Create a new upload token. """
layout = ManageUploadTokensLayout(self, request)
if form.submitted(request):
self.create()
request.message(_("Upload token created."), 'success')
return morepath.redirect(layout.manage_model_link)
... | feba475900a01e3984fed7d49b3c6709e8b82bd8 | 3,631,589 |
def vertical_channel_region_detection(image):
"""
:param image:
:return:
"""
f = spectrum_bins_by_length(image.shape[1])
ft_h_s = tunable('channels.vertical.recursive.fft_smoothing_width', 3,
description="For channel detection (recursive, vertical), spectrum smoothing widt... | f70b702df3ab52c1d0c538c55cb1df180b003df2 | 3,631,590 |
import os
def file_str(f):
"""
:param f: 输入完整路径的文件夹或文件名
:return: 返回简化的名称
a/b ==> <b>
a/b.txt ==> b.txt
"""
name = os.path.basename(f)
if os.path.isdir(f):
s = '<' + name + '>'
else:
s = name
return s | 60ea019dc5bf2145b85d15e4c58ae9c08a588c38 | 3,631,591 |
def image_output_size(input_shape, size, stride, padding):
"""Calculate the resulting output shape for an image layer with the specified options."""
if len(size) > 2 and input_shape[3] != size[2]:
print("Matrix size incompatible!")
height = size[0]
width = size[1]
out_depth = size[3] if le... | 77665f8304570bd5ba805241131a96d5d6908587 | 3,631,592 |
import re
from typing import Tuple
def _info_from_match(match: re.Match, start: int) -> Tuple[str, int]:
"""Returns the matching text and starting location if none yet available"""
if start == -1:
start = match.start()
return match.group(), start | 3599c6345db5ce2e16502a6e41dda4684da2f617 | 3,631,593 |
def otherICULegacyLinks():
"""The file `icuTzDir`/tools/tzcode/icuzones contains all ICU legacy time
zones with the exception of time zones which are removed by IANA after an
ICU release.
For example ICU 67 uses tzdata2018i, but tzdata2020b removed the link from
"US/Pacific-New" to "America/Los_Ang... | bfacf0d8b5a31c5edbd69f93c4d55d8857599e1a | 3,631,594 |
def _postprocess_gif(gif: np.ndarray):
"""Process provided gif to a format that can be logged to Tensorboard."""
gif = np.clip(255 * gif, 0, 255).astype(np.uint8)
B, T, C, H, W = gif.shape
frames = gif.transpose((1, 2, 3, 0, 4)).reshape((1, T, C, H, B * W))
return frames | c9adb9c2d56dc437ee0e6b0aa7482da4e430aa2e | 3,631,595 |
def format_meta(metadictionary):
"""returns a string showing metadata"""
returntext = EMPTYCHAR
returntext += 'SIZE' + BLANK + COLON + BLANK + str(metadictionary['size'])+EOL
returntext += 'USER' + BLANK + COLON + BLANK + str(metadictionary['user'])+EOL
returntext += 'DATE' + BLANK + COLON + BLAN... | e24f6846a8d9470899e74099a56780b0a16a7e76 | 3,631,596 |
import os
def look_in_directory(directory, file_to_find):
"""
Loop through the current directory for the file, if the current item
is a directory, it recusively looks through that folder
"""
# Loop over all the items in the directory
for f in os.listdir(directory):
# Uncomment the ... | 2023281e743227d3ba0172cc38fa9e9fe14bcdb2 | 3,631,597 |
def accumulating_income():
"""
Real Name: Accumulating Income
Original Eqn: Income
Units: Month/Month
Limits: (None, None)
Type: component
Subs: None
"""
return income() | 9753c68223f351629deefbb46266b051952e31e5 | 3,631,598 |
import sys
def createConfig(namespace=None, updateEnv=None, updateEnvMap=None, updateEnvHelp=None, updateEnvDefaults=None,
updateProperties=None, config=Config, initFromEnv=True, **settings):
"""Creates a base configuration class."""
namespace = sys.modules[namespace] if isinstance(namespace, str) else na... | b4966623c6ea20ae26335e51f279b0d2f9521005 | 3,631,599 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.