content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def build_1tdm_costly(no,bra_space,ket_space,basis,spin_case):
"""
Copy of ca_ss
Compute a(v1,v2,j) = <v1|a_j|v2>
Input:
no = n_orbs
bra_space = (n_alpha,n_beta) for bra
ket_space = (n_alpha,n_beta) for ket
spin_case: 'a' or 'b'
basis = dict of basis vectors
... | b6373204d19efc58e8bbe28fbd63dfb1d7eadb97 | 36,307 |
def read_words_pos(parse):
"""
Read the given parse string and return a list of tuples
(token, pos_tag) in lower case.
"""
parse = parse.lower()
tree = nltk.Tree.fromstring(parse)
word_pos = [(word, map_wn_pos(pos)) for word, pos in tree.pos()]
return word_pos | 5d2ad55052df3d7f336eb75a061441688b4ec51f | 36,308 |
def get_state_02y1_pure_state_vector() -> np.ndarray:
"""returns the pure state vector of :math:`\\frac{1}{\\sqrt{2}} (|0\\rangle - j|2\\rangle)`.
Returns
-------
np.ndarray
the pure state vector.
"""
vec = np.array([1, 0, -1j], dtype=np.complex128) / np.sqrt(2)
return vec | 7efc28ee76f75fdc32052fc2b1658efebca13889 | 36,309 |
def check_input_allowed(object):
"""
This is a generic function called with the object being commented.
It's defined as the default in 'COMMENTS_INK_APP_MODEL_OPTIONS'.
If you want to disallow comments input to your 'app.model' instances under
a given conditions, rewrite this function in your code ... | fae4c59a4326af5257302a48e7be18131e378371 | 36,310 |
import torch
def eval_dev(dev_file, batch_size, epoch, shuffle, cuda, top_k,
sender, receiver, desc_dict, map_labels, file_name,
callback=None):
"""
Function computing development accuracy
"""
desc = desc_dict["desc"]
desc_set = desc_dict.get("desc_set", None)
desc_s... | c64f03d3c674b1cbfd4ebf6b6767d4e0b7c0f0a3 | 36,311 |
from typing import Any
def is_dataclass_instance(obj: Any) -> bool:
"""Return True if the given object is a dataclass object, False otherwise.
In py36, this function returns False if the "dataclasses" backport is not available.
Taken from https://docs.python.org/3/library/dataclasses.html#dataclasses.is... | daca965952ab34fdefddd648152b8a974765c43e | 36,313 |
import re
def isChr(s, c):
"""
:param s: String
:param c: Chromosome, number or X or Y
:return: Whether s matches c
"""
if 'X' == c:
return 'X' in c
if 'Y' == c:
return 'Y' in c
return str(c) in re.findall("[1-9][0-9]*", s) | b54666e3cf2c376bfbd687734eb40fc65f233c20 | 36,315 |
def get_mxnet_module_arg_params(x):
"""
given parameter name,
get the updated value from mxnet module arg_params
:param x: parameter values to (e.g. kernels, bias)
:return: updated parameter values
"""
# retrieve from bind values first, which is up to date with
# arg_params in mxnet mod... | d93b7fe25439bdb8fe032ec2c564d57b144dbaac | 36,316 |
def psnr_denoise(y_true, y_pred):
""""Calculating peak signal-to-noise ratio (PSNR) between two images."""
return tf.image.psnr(y_pred, y_true, max_val=1.0) | f5d061db0343b696c2fb01ad0f6db72baf59d02e | 36,317 |
def humanize_duration(time_delta, show=None, sep=" "):
"""
Humanize a timedelta object.
:param time_delta: the timedelta object to humanize.
:param sep: specify a separator for days, hours, minutes and seconds in the
final string.
:return: a dict with keys: ``days``, ``hours``, ``mi... | 0a1af033846805e461a4922e331147db08a8be25 | 36,319 |
import json
def process_stats(args):
"""Process the VPP Stats.
:param args: Command line arguments passed to VPP PAPI Provider.
:type args: ArgumentParser
:returns: JSON formatted string.
:rtype: str
:raises RuntimeError: If PAPI command error occurs.
"""
try:
stats = VPPStat... | 4dbf7cead63bbe7e7610a8d8a85d7e5f66c896e2 | 36,320 |
def loads(s, **kwargs):
"""
Deserialize an object from a bytestring.
:param bytes s:
the bytestring to deserialize
:param kwargs:
keyword arguments passed to :class:`CBORDecoder`
:return:
the deserialized object
"""
with BytesIO(s) as fp:
return CBORDecoder(f... | 117e293b66eace069a4fecfbc9b36323b722192b | 36,321 |
import csv
def TsvToXY(filePath):
"""This method reads .tsv file and returns the data, XY split in a tuple"""
with open(filePath, 'r') as file:
lines = list(csv.reader(file, delimiter='\t'))
data = []
for line in lines:
# for each line, split the PCM into a list
listedLine = []
for column in line[:-1... | 8cc05fba66d0f7f9c346955765e5a50c2cd7e33f | 36,322 |
def nondimensional():
"""
Factory associated with Nondimensional.
"""
return Nondimensional() | 114372c208d70f51cdc09a5b84968256000ef8f3 | 36,323 |
def patch_configuration(client, configuration_id, patches):
"""
:param patches: List of patches in format [
{"op": op, "path": path, "value": value},
{"op": op, "path": path, "value": value}
]
:return: requests Response
"""
data = []
data = patches
return client._patch("/compa... | a229390fd8845238e1b5eeddb9922f79772b9840 | 36,324 |
def f_next_point_zeta(f2new: float,free_energyb: np.ndarray,za: np.ndarray,zb: np.ndarray,cova: np.ndarray,covb: np.ndarray,f1new: float,fa: np.ndarray,fb: np.ndarray) -> float:
"""
Free energy difference function of the next point to be optimized if the Number of points is greater than 1
Specialized for t... | b797a830401bc2ac30fac31c277a194fe6fc8104 | 36,326 |
async def async_setup(opp, config):
"""Set up ZHA from config."""
opp.data[DATA_ZHA] = {}
if DOMAIN not in config:
return True
conf = config[DOMAIN]
opp.data[DATA_ZHA][DATA_ZHA_CONFIG] = conf
if not opp.config_entries.async_entries(DOMAIN):
opp.async_create_task(
o... | cc9d908c65bdf423338f64a5476a66937dd12591 | 36,327 |
def choice(*args, **kwargs):
"""
Wraps numpy random.choice call in ASPIRE Random context.
"""
seed = None
if "seed" in kwargs:
seed = kwargs.pop("seed")
with Random(seed):
return np.random.choice(*args, **kwargs) | 1b35f02dac0d4639d9e2063a6ee9208cca798ea1 | 36,328 |
def convert_state_quara_to_qiskit(
quara_state: State,
) -> np.ndarray:
"""converts Quara State to densitymatrix in Qiskit.
Parameters
----------
quara_state: State
Quara State.
Returns
-------
np.ndarray
Qiskit density matrix of quantum state.
"""
qiskit_state... | cf581f24bea8dd1cb397fe6a4abb6aab80bccec1 | 36,329 |
import re
def camel2snake(name):
"""
Args:
name (str): camelCase
Returns:
str: snake_case
"""
s1 = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', name)
return re.sub('([a-z0-9])([A-Z])', r'\1_\2', s1).lower() | 9d4581b1f6731d7d572214676736d4e623d3fac0 | 36,330 |
def calc_nu_b(b):
"""Calculate the cyclotron frequency in Hz given a magnetic field strength in Gauss.
This is in cycles per second not radians per second; i.e. there is a 2π in
the denominator: ν_B = e B / (2π m_e c)
"""
return cgs.e * b / (2 * cgs.pi * cgs.me * cgs.c) | a4d6f15ce0e4e710f92954e2a978ef61ada60f01 | 36,331 |
def checking_if_table_exists():
"""
Checking if table exists or not
"""
conn = connect(dbpath)
c = conn.cursor()
try:
c.execute("""
SELECT name FROM sqlite_master
WHERE type='table'
AND name='webhooks';
""")
res = c.fetchall()
... | 274749e2210ee04aa33a840532f8a6bdfe6248f9 | 36,332 |
def can_represent_dtype(dtype):
"""
Can we build an AdjustedArray for a baseline of `dtype``?
"""
return dtype in REPRESENTABLE_DTYPES or dtype.kind in STRING_KINDS | 06ea2f41cd3063e81a963a322509d1b87c180be8 | 36,333 |
from functools import reduce
from operator import add
from operator import sub
from operator import mul
from operator import truediv
def calc_apply(operator, args):
"""Apply the named operator to a list of args.
>>> calc_apply('+', as_scheme_list(1, 2, 3))
6
>>> calc_apply('-', as_scheme_list(10, 1, ... | 09fdb5ec5606bcfcf84606b925666de836a2afb2 | 36,334 |
def build_mpo_list(single_mpo, site_num, regularize=False):
"""
build MPO list for MPS.
:param single_mpo: a numpy ndarray with ndim=4.
The first 2 dimensions reprsents the square shape of the MPO and the last 2 dimensions are physical dimensions.
:param site_num: the total number of sites
:para... | 7781bbd3f27905f685412a59a48dddf93e51cccf | 36,335 |
def efun_git_status(paths: ldmud.Array) -> ldmud.Array:
"""
SYNOPSIS
mixed** git_status(string* paths)
DESCRIPTION
For the given directories or files list any changes that are not
committed. Returns an array for each such file:
[0] Repository ... | 6f126d4735dbcb46ffd65749a3713d9ba12831e3 | 36,336 |
import json
import requests
async def tx_t(context):
""" PagerMaid universal translator. """
reply = await context.get_reply_message()
message = context.arguments
lang = 'zh'
if message:
pass
elif reply:
message = reply.text
else:
await context.edit("出错了呜呜呜 ~ 无效的参数。... | 5070fc40a26599aaf727f824abef9bbee19dfb09 | 36,337 |
def resize_convex_hull_polygon(_convex_hull_points, _resize_ratio):
"""
对凸包的多边形进行缩放
Args:
_convex_hull_points: 凸包多边形的轮廓
_resize_ratio: 缩放比例
Returns: 缩放后的点
"""
center_point = np.mean(_convex_hull_points, axis=0)
diff_points = _convex_hull_points - center_point
r ... | e7b46e54f4fb1983df117d1e47848ebf22a97527 | 36,338 |
def convert_xyz_to_rgb(source_color_xyz: tuple) -> tuple:
"""
Converts a color from the CIE XYZ 1931 to the RGB colorspace.
Args:
source_color_xyz: a tuple with X, Y and Z values of the color.
Returns:
a tuple with the R, G and B values of the color.
"""
logger.trace("Convert... | 0d0ce8e01d286ff2ca218ec168659a21b3733c5e | 36,339 |
def _lower_triangular_solve_sparse(M, rhs, dotprodsimp=None):
"""Solves ``Ax = B``, where A is a lower triangular matrix.
Parameters
==========
dotprodsimp : bool, optional
Specifies whether intermediate term algebraic simplification is used
during matrix multiplications to control exp... | 6aaff272ff43c94cf80d1ea406b6603700469e06 | 36,340 |
def clip_to_frames_all(lena_mappings, human_mappings, consider_overlapped, frame_length=10):
""" Returns the accumulated labelled frames for all 60 clips.
"""
total_lena = []
total_human = []
for i in range(1, 61):
y_lena, y_human = clip_to_frames_single(i, lena_mappings, human_mappings,
... | ecc6ea71ba03599fd9b4de65a2e97f7731bc68ab | 36,341 |
def _cart_id(request):
"""
If the user is logged in, retrieve the user
associated cart_id from the database.
If the user is anonym, then use the session
to retrieve the cart_id.
"""
if request.session.get(CART_ID_SESSION_KEY, '') == '':
request.session[CART_ID_SESSION_KEY] = _genera... | 89599e3c43f433b5c09bfa929453c543c5a9ece2 | 36,342 |
def flatpage_nav(_):
"""
Context processor which adds data required for the main navigation of flatpages to the context.
"""
categories = flatpages_models.Category.objects.all()
pages = flatpages_models.Flatpage.objects_without_category.all()
return {'all_categories': categories, 'pages_withou... | acb3a6c76d830673f807204384d5aef99d18acc4 | 36,343 |
def ortho(left, right, bottom, top, znear, zfar):
"""Create orthographic projection matrix
Parameters
----------
left : float
Left coordinate of the field of view.
right : float
Right coordinate of the field of view.
bottom : float
Bottom coordinate of the field of view.... | 767e34a6b8a8538adb62545d9222567ac06b29a5 | 36,344 |
def to_str(bit_str):
"""Transform bit string in a string of characters"""
chars = []
for i in range(int(len(bit_str) / 8)):
byte = bit_str[i * 8:(i + 1) * 8]
if byte == "11111111":
break
chars.append(chr(int(''.join([str(bit) for bit in byte]), 2)))
return ''.join(cha... | db75acd548805eb06a383c8443a0a85631d8e65d | 36,345 |
def compute_coeffs(track_y, track_t):
"""
Least squares polynomial fit to obtain step size.
Parameters
----------
track_y : 1-D array with shape (3, )
Array containing the three smallest function values from
applying either forward or backward tracking.
Mus... | a46a07047fd564c10b7c553370e211c23bd0cc51 | 36,347 |
import json
async def test_route_message_with_existing_route(base_central_system,
boot_notification_call):
""" Test if the correct handler is called when routing a message.
Also test if payload of request is injected correctly in handler.
"""
@on(Actio... | 002b8d7bce1a68d51bc77472dc169b2d65015c89 | 36,349 |
def PyTmYDSminusYDS(y1, d1, s1, y2, d2, s2):
"""
Get difference between two year-day-seconds entries
NOTE: the original Caris function doesn't take leap seconds into account
Parameters
----------
y1: int, year 1
d1: int, day 1
s1: int, seconds 1
y2: int, year 2
d2: int, day 2
... | 891043cc38d9683a067e3f330bc213df2059f630 | 36,350 |
def random_pos(z_offset=0.2):
"""generate random position for dropping sphare
Parameters
----------
z_offset : float, optional
z offset, by default 0.2
Returns
-------
pos list [x, y, z]
random position
"""
pos = [np.random.randn() * 0.05,
np.random.rand... | 849a59542d55f9caa4eb6ab73d163f533274ee7a | 36,351 |
import torch
def filter2D(input, kernel, border_type='reflect', normalized=False):
"""
Convolve a tensor with a 2d kernel.
"""
if not isinstance(input, torch.Tensor):
raise TypeError("Input border_type is not torch.Tensor. Got {}"
.format(type(input)))
if not ... | 0e419bc6d6b0ea9d23689bdc49415be02bf0fc75 | 36,352 |
def get_all(ip_string):
"""
@ date: 2017-12-2
@ author: wxw
@ function: 接口函数,产生num个线程,在队列中取出IP进行爬取
@ input: C段地址 如:182.40.12
@ output: 完成标志 0 (int)
"""
global queue_ip, mutex_href_get, mutex_href_put
threads = []
# 线程数量
num = THREAD_NUM
class_ip = ip_string
proxy_ip... | 900261d93ce070e4454b8cd88692a39479fc68a6 | 36,353 |
def scale(df, resolution=0.5):
"""
:param df: 5d-array [sample, steps, height, width, channels]
:param resolution: float (0,1)
"""
df = ndimage.zoom(input=df, zoom=(1, 1, resolution, resolution, 1), order=1)
print("Scaled")
return df | fe55959c833cac6db202c468cdcb82f0cecfe661 | 36,354 |
def view_image():
"""
View a Fullscreen version of an Image - called from Reports
"""
try:
_id = request.args[0]
except:
return "Need to provide the id of the Image"
table = s3db.doc_image
record = db(table.id == _id).select(table.name,
... | 10d2704a54cd32a67de8418de3db4a94674673c4 | 36,355 |
import struct
def bits_ip_to_str(bit_ip : bitarray) -> str:
""" 将比特形式的ip转成字符串形式,形如 '192.168.3.5' """
bytes_ip = bit_ip.tobytes()
ip_num_list = struct.unpack('!BBBB', bytes_ip)
str_ip = ''
# 首次循环标志,如果不是首次循环的话就加一个'.'
first_flag = 1
for i in range(0,4):
if(1-first_flag):
s... | 39fcbeba281d8de0712f9c06c00d100c4ef4be17 | 36,356 |
def resolve_user_by_user_id(slack_wrapper, user_id):
"""
Resolve a user id to an user object.
"""
return slack_wrapper.get_member(parse_user_id(user_id)) | eb6931f0902d1bc0fbdda883788e9e5cd90fff0a | 36,357 |
from typing import Optional
from typing import List
from typing import Any
def get_handler(
theme: str, # noqa: W0613 (unused argument config)
custom_templates: Optional[str] = None,
setup_commands: Optional[List[str]] = None,
**config: Any,
) -> PythonHandler:
"""Simply return an instance of `Py... | a6255211af0dbcc03dc95bed478347f0a38643d2 | 36,358 |
import logging
def extract_temperature(
df,
value_threshold = 0,
grad_threshold = 10,
curve_threshold = 1e5,
side = 'high',
mask_window = 75,
):
"""
Finds the temperature coefficient from a PL curve.
Performs a linear fit on the log of PL spectra on the low or high energy side.
... | ca04b8a6f9f48bf1ff1702ca38f47b89e9dfc8bd | 36,359 |
import torch
import warnings
def near_eye_init(
shape: tuple, is_complex: bool = False, noise: float = 1e-3
) -> Tensor:
"""
Initialize an MPS core tensor with all slices close to identity matrix
Args:
shape: Shape of the core tensor being initialized.
is_complex: Whether to initializ... | 53fc514cec263be07f9e90e60370f1c06021b142 | 36,360 |
def stft( # pylint: disable=unused-argument
signal, ax=None, limits=None, log=True, colorbar=True, batch=0,
sample_rate=None, stft_size=None, stft_shift=None,
x_label=None, y_label=None, z_label=None, z_scale=None,
):
"""
Plots a spectrogram from an stft signal as input. This is a wrapp... | 25b9e71e510d5cfbc0d150dc545e8edf8958bb87 | 36,361 |
def match_text(pattern: str) -> Predicate:
"""
predicate for filtering messages which text matches the given regex
:param pattern: regex to match
:type pattern: str
:return: Predicate
:rtype: Predicate
"""
return match(pattern, "text") | 66b66471d60df3e8312725e48ce96e1bf6d5a48f | 36,362 |
from typing import Tuple
from typing import List
def compute_lane_following_features(
scene_df: pd.DataFrame,
agent_list: list,
precomputed_lanes: pd.DataFrame,
raw_data_format: list,
map_inst: ArgoverseMap,
seq_id: int,
obs_len: int,
precomputed_physics: pd.DataFrame,
# Configurab... | 722f80219a128796b982aad917ef1e8477e3ef93 | 36,364 |
import platform
def identify_operating_system():
"""identify current operating system
Returns:
(str): 'Windows', 'Linux', or 'Darwin' for mac
"""
return platform.system() | 05f4ec68aa535cdbef61c4cbf36d9cfc5a75fbcc | 36,365 |
def vlog_exd(v:np.ndarray,t:np.ndarray,FileHeader:dict):
"""
Interpolation function used in genereatevmodel2
"""
dt=FileHeader['dt']
nt=FileHeader['ns']
t2 = np.arange(0,nt*dt,dt)
return np.interp(t2,t,v) | b4718b240639a56b3312b1bf45cb5dc7fcf26b76 | 36,366 |
def unpad(outputs, lengths):
"""Unpads a padded batch of waveforms to their initial lengths
args:
outputs ([B, num_samples_max] array): padded waveforms
lens (list of ints): initial lengths before padding in features space.
This needs to be multiplied by hop length to... | de93cd4f325920819c62d5f9bf10d4ca22102de5 | 36,367 |
def quote_preview_pdf(request, pk):
""" This view returns a preview of our PDF file for a given quote
"""
# we get the selected item to use as the "object" context to be able to have some mockup data
quote_instance = invoice.models.Quote.objects.get(pk=pk)
quote_pdf_name = "quote-%s.pdf" % str(quote... | 2837a15262a9e844345f8d684adb8129fbd1a1df | 36,368 |
def check_uniq(X):
"""Checks whether all input data values are unique.
Parameters
----------
X: array-like, shape (n_samples, )
Vector to check whether it cointains unique values.
Returns
-------
bool
"""
s = set()
return not any(x in s or s.add(x) for x in X) | 9a332ae5378374672201488637d76bd656b53264 | 36,369 |
def PrettyPrint(oData=None, hOutputFile=None, bToConsole=True, nIndent=0, sPrefix=None, bHexFormat=False):
"""
|
**Function:**
**PrettyPrint**
Wrapper function to create and use a ``CTypePrint`` object. This wrapper function is responsible for
printing out the content to console and to a file (depending on ... | f7b9957f9627d72c02cff0649c2609962cc66bac | 36,370 |
def _get_object(lst, _id):
"""
Internal function to grab data referenced inside response['included']
"""
for item in lst:
if item['id'] == _id:
return item | f18c6f330750f72d9495d1283ef28ef41cf58a97 | 36,371 |
def projected_projectedLinearEccentricity(a,e,W,w,inc):
"""
Args:
a (numpy array):
semi-major axis in AU
e (numpy array):
eccentricity
W (numpy array):
Longitude of the Ascending Node in Radians
w (numpy array):
Argument of periapsi... | ecc12d44022dda5dc744beab1122c0471389b82e | 36,372 |
def isAntiCapability(capability):
"""Returns True if capability is an anticapability; False otherwise."""
if isChannelCapability(capability):
(_, capability) = fromChannelCapability(capability)
return isCapability(capability) and capability[0] == '-' | 0ece8135d72ebc16d869a83e2848e00630ff9a04 | 36,373 |
import csv
import json
def decrypt_accession_id(request):
"""HTTP Cloud Function.
Args:
request (flask.Request): The request object.
<http://flask.pocoo.org/docs/1.0/api/#flask.Request>
Returns:
The response text, or any set of values that can be turned into a
Response obje... | 04c41a7352b381dea9fb8453dea88c18342959f0 | 36,375 |
def search_astroph(keywords, arxiv_channel, old_id=None):
""" do the actual search though astro-ph by first querying astro-ph
for the latest papers and then looking for keyword matches"""
today = dt.date.today()
day = dt.timedelta(days=1)
max_papers = 1000
# we pick a wide-enough search r... | 1106794e8949d92800257c93c23e80fd0e9957c3 | 36,376 |
from typing import Tuple
def make_cdl_pars_data_from_linregress(
Cdl_dataprep: pd.DataFrame,
xcol="scanrate",
ycol="j_A_cm2",
grpbykeys=[EvRHE, "SweepType"],
) -> Tuple[pd.DataFrame, pd.DataFrame]:
"""
Parameters
----------
Cdl_dataprep : pd.DataFrame
A frame that is prepared f... | 79436e80cf25f11fee1a834654273196be7c27c5 | 36,378 |
import yaml
def increment_version(image_name: str, current_version: str, increment: str) -> str:
"""
:brief: increment app version.
:param: current_version - current app version
:param: increment - number to add to minor part of the current version
:example: number - 2, 2+ 0.1.40(current version) ... | 86aae5b4b3fc04c1d23f54afed166b07e869c739 | 36,379 |
def getfrom(v):
"""
pass through function for using the
filter_for decorator directly
"""
return v | 7a01fecbac63bca67fef10bfb39f8641e0cacda7 | 36,380 |
import math
def projected_distance(ra1, ra2, dec1, dec2):
"""
Function that returns the projected distance (in arcminutes) between two points.
"""
if ra1 == ra2 and dec1 == dec2:
return 0.0
else:
dist = math.acos(math.sin(deg2rad(dec1)) * math.sin(deg2rad(dec2)) + math.cos(deg2rad(dec1)) * ... | 6403b01cca702019edbe9d3cf6685d1b0b82ca7d | 36,381 |
def get_dishes(restaurant, data):
"""
:type restaurant: meican.models.Restaurant
:type data: dict
:rtype: list[meican.models.Dish]
"""
sections = {}
for section_data in data.get("sectionList", []):
section = Section(section_data)
sections[section.id] = section
dishes = []... | 8f3cfa00c48e2e75be70c016944f0cfae30c5939 | 36,382 |
import logging
def setup_logger(level):
"""
Setup a logger for the REST handler
"""
logger = logging.getLogger('splunk.appserver.service_account_keys_rest_handler.rest_handler')
logger.propagate = False # Prevent the log messages from being duplicated in the python.log file
logger.setLevel(le... | dab40d34f7fcf47cf4506e3fbf838b423a13d823 | 36,384 |
def callit(callback, *args, **kargs):
"""Inspect argspec of `callback` function and only pass the supported
arguments when calling it.
"""
maxargs = len(args)
argcount = (kargs['argcount'] if 'argcount' in kargs
else getargcount(callback, maxargs))
argstop = min([maxargs, argcoun... | 92232a4c8c0927cbf8a3f0c592b5406862f7b9f0 | 36,385 |
def drop_nan_columns(data, settings):
"""
:param data: A list with pandas's DataFrame.
:param settings: A dictionary with:
* subset: optional list of column names to consider.
* thresh: int, default None If specified, drop rows that have less
than thresh non-null values. This overwrites th... | 0a49305d03924f9f25ae6b3e159124e1d9b1fea5 | 36,386 |
from typing import Optional
def crf_log_likelihood(
inputs: Tensors,
tag_indices: Tensors,
sequence_lengths: Tensors,
transition_params: Optional[Tensors] = None,
) -> tf.Tensor:
"""Computes the log-likelihood of tag sequences in a CRF.
Args:
inputs: A [batch_size, max_seq_len, num_tags]... | 82ca8c7a3cda8fe91a37daa45112c9624a38367d | 36,387 |
def t_POUND(t):
"""header token"""
# 如果header前面有换行
if t.value[0] == '\n':
t.value = str(len(t.value) - 1)
else:
t.value = str(len(t.value))
return t | 8625bb266d4ad9eec9f08a3edc81483c41e87aff | 36,389 |
def nearby_difference(x):
"""Compute L2 norms for nearby entries in a batch."""
# This is a very rough measure of diversity.
with tf.device('cpu'):
x1 = tf.reshape(x, shape=[int(x.shape[0]), -1])
x2 = tf.roll(x1, shift=1, axis=0)
return tf.sqrt(tf.reduce_sum(tf.square(tf.subtract(x1, x2)))) | ead36d7e085024f67c717aa53e2cf651ec6f9cc6 | 36,390 |
import re
def _split_article_sentences(article_text):
"""
Recieves a string containing the plain text of a wikipedia article
Returns a list containing the sentences of the recieved article text
"""
def not_image_thumb(paragraph):
"""
True if the paragraph is wikitext for displayin... | 5fca6ac2113a7c54456132d3afb2171bd8644603 | 36,391 |
import functools
def get_metric(fn, tags):
"""
Wraps the metric function to decorate with additional tags
"""
@functools.wraps(fn)
def wrapper(name, *args, **kwargs):
# the metric name starts as the name of the function itself
metric = fn.__func__.__name__
_tags = tags.cop... | a108c4610dc32495604c2e224f4d8ac2fae289c2 | 36,392 |
from typing import List
import time
def import_data(table: List[str] | None = None,
url: str | dict | None = None,
chunksize: int | None = None) -> tuple[DataFrame | Series, ...]:
"""
Importing data from database as a pandas DataFrame.
:param table: List of table n... | d9749253eb387d7d6ff8163c08081df2e67b98d6 | 36,395 |
def accuracy_plot(a, b, z, ref, func):
"""Plot the relative error in using func to approximate hyp1f1.
Parameters
----------
a, b: array_like
Meshgrid of a and b values.
z : float
Value of the argument.
ref : array_like
An array of reference values, of the same shape as ... | df5bb002f2cb891c91ab702e81e5da05a8136d17 | 36,396 |
def plot_zero_check(amplitudes, properties, vars=['polar_angle', 'eccentricity'], hue='hemi',
sum_idx=1, nan_check=False):
"""plot properties of voxels with zero or NaN amplitude
after interpolation, some voxels may end up with zero amplitude for
some reason, including because their coo... | 091a4eeb507bd0124948c2e919923da3bcd72e7f | 36,397 |
from typing import List
def cum_sound_chunks(audio_frames: List) -> AudioSegment:
"""cummulate sound frames"""
sound_chunk = pydub.AudioSegment.empty()
for audio_frame in audio_frames:
sound = pydub.AudioSegment(
data=audio_frame.to_ndarray().tobytes(),
sample_width=audio_f... | afa665459175422c1ab76b3bf11bd533ca68eb1e | 36,398 |
import re
def _nowiki_sub_fn(m):
"""This function escapes the contents of a <nowiki> ... </nowiki> pair."""
text = m.group(1)
text = re.sub(_nowiki_re, _nowiki_repl, text)
text = re.sub(r"\s+", " ", text)
return text | dc6b7ed50d3828563863f01aff9a7eb2afd5a27b | 36,399 |
import pytz
def display_timezone():
"""Displays the dialog for all"""
tzlist = pytz.common_timezones
tzlist.sort()
tag = tzlist
desc = []
for item in tag:
desc.append(item.split("/")[-1])
mytzlist = zip(tag, desc)
return DISPLAY.menu(
"Please select the system timezon... | 0709aae540f04baa267050066542c1f44477bd8a | 36,401 |
def operate_favorite(rid: int, type_: str, add_media_ids: list = None,
del_media_ids: list = None, verify: utils.Verify = None):
"""
操作收藏夹
:param rid:
:param type_:
:param add_media_ids: 要添加的收藏夹内容列表
:param del_media_ids: 要删除的收藏夹内容列表
:param verify:
:return:
"""
... | c2de969541f893312be8aed9b41ce99f8e4bb7a2 | 36,402 |
import random
def kmeans_rand_centroids_1_d(data, k, max_error, max_iters):
"""Performs K-Means analysis on a one dimensional array, starting with centroids that are randomly distributed across the range of the input set."""
# Sanity check.
data_len = len(data)
if data_len <= 1:
return []
... | eb50fdcb4b05c5c99dd655d6c9b74b0d80c621d2 | 36,404 |
def _compute_fscores(a_stat, a_fscore_stat):
"""
Compute macro- and micro-averaged F-scores
@param a_stat - statistics disctionary on single classes
@param a_fscore_stat - verbose statistics with F-scores for each
particular class (will be updated in this method)
@return 6-tu... | a5e2cf4eff650e56a4c6b8c83955e3740d6bb937 | 36,405 |
def pseudonymize(collection, entry, pseudonymizer, config):
"""Pseudonymize an entry in the database."""
entry_out = entry
if collection in config['pseudonymize']:
entry_out = deepcopy(entry)
config_keys = config['pseudonymize'][collection]
entry_keys = entry_out.keys()
#... | b2db89029bc46d3fa358afa63f594d10fee69c55 | 36,406 |
def vector_layer_db(map, layer):
"""Return the database connection details for a vector map layer.
If db connection for given layer is not defined, fatal() is called.
:param str map: map name
:param layer: layer number
:return: parsed output
"""
try:
f = vector_db(map)[int(layer)]
... | 4bd25e62d635c02374bd27ce6cd885625697190a | 36,408 |
def _Flatten(nmap_list):
"""Flattens every `.NestedMap` in nmap_list and concatenate them."""
ret = []
for x in nmap_list:
ret += x.Flatten()
return ret | 10a13836353894524c1f6cea45296d854054e8a7 | 36,409 |
from typing import Union
from typing import Dict
def get_all_subscription_request(
from_position: Union[Dict[str, int], str] = constants.START,
resolve_link_to_s: bool = False,
filters: Dict = None,
) -> streams_pb2.ReadReq:
"""Returns a streams_pb2.ReadReq configured for subscription operations for t... | 20ce7be5217e6a076eb1e9dc635b1bb51679b197 | 36,410 |
def us2en(edate, **kwargs):
"""
Wrapper function for :func:`date2date` with English date format output
That means `date2date(edate, format='en', **kwargs)`;
but *format* given in call will overwrite *format='en'*.
Examples
--------
>>> edate = ['11/12/2014 12:00', '01.03.2015 17:56:00',
... | 2a96c89302abc24c25cecc36b2b7763b3cd3a2af | 36,411 |
def autosave_info(user, namespace_project):
"""Information about all autosaves for a project."""
if user.get_renku_project(namespace_project) is None:
return make_response(
jsonify(
{"messages": {"error": f"Cannot find project {namespace_project}"}}
),
... | 01754718eda2ec22ceeb739f079000058160156b | 36,412 |
def per_subgroup_fnr_diff_from_overall(df, subgroups, model_families, threshold,
squared_error):
"""Calculates the sum of differences between the per-subgroup false negative rate and the overall FNR."""
d = per_subgroup_nr_diff_from_overall(df, subgroups, model_families,
... | 3ce163a1a2faca9e84b0e919a75d38b831c7c56e | 36,413 |
def scaffold_split_from_smiles(
smiles_list, frac_train=0.8, frac_valid=0.1, frac_test=0.1,
):
""" The same algorithm as scaffold_split. Only take SMILES list as input and return
indices of the train, validation, and test samples.
Args:
smiles_list (list): list of SMILES to be splitted.
... | e302a1cf9106b04f76432dd051a8a1b2fd5ff021 | 36,415 |
def _get_transitive_values(values, deps, deps_accessor):
"""Returns the transitive values from "values" added to values from deps.
Args:
values: the values of to be added to the transitive values from deps.
deps: list of dependencies with GLSLInfo providers to add to the
transitive ... | 6184fc25819eacd2003ba7ad4481882e744c7892 | 36,416 |
from typing import Dict
from typing import Any
def get_common_config(
io_conf: ConfigType, mqtt_conf: ConfigType, mqtt_options: MQTTClientOptions
) -> Dict[str, Any]:
"""
Return config that's common across all HQ discovery announcements.
"""
disco_conf: ConfigType = mqtt_conf["ha_discovery"]
c... | b0f0109e114fdd2a2782eb2d6b4d1980f23bf9ae | 36,417 |
def compute_sampled_logits_css(
weights, # [V, d]
biases, # [V]
probable, # [B, P]
inputs, # [B, T, d]
num_sampled,
num_classes,
minval=1, # use this to control what's the first valid class
bias_correction=True
):
"""
:param weights: class... | 7b8ffc2bd0e7174cfb3ceac03e34a0be36c011ed | 36,418 |
def interp_weights(xyz, uvw, d=2):
"""
Fast interpolation of multiple datasets over the same grid
from: https://stackoverflow.com/a/20930910/2197375
Parameters:
---
xyz: ndarray, array of starting irregular grid coordinates
uvw: ndarray, array of target regular grid coordinates
d: int, ... | 405a75e2590f0b2d36a4922b53436f2ebd286909 | 36,419 |
def add_shopping_list_items(create_client_shopping_list, client, generate_token): # noqa
"""
add items to a shopping list
"""
shopping_list_id = create_client_shopping_list.data['data']['id']
token, _ = generate_token
url = reverse('shoppingItem:get shopping list items', args=[shopping_list_id]... | f1be8b5ef2b0ba99ff4f543c0c74cf8c32068f35 | 36,420 |
def _get_mode():
"""Get the current mode (0 is Graph mode, 1 is PyNative mode)"""
return context.get_context('mode') | 013789d9eae12710bc016bdb3191a35cac006dc6 | 36,421 |
def parse_xml(text:str):
"""Parse the given string as XML."""
return etree.fromstring(text) | 373d6cfb04b570a3212f7a830aa4055dfb9d9f14 | 36,422 |
def crop_anno(img_path, crop_position, df, im_w=None, im_h=None,
filesystem:FileMan=None):
"""Calculate annos for a crop-position in an image
Args:
img_path (str): image to calculate the crop-annos
crop_position (list): crop-position like: [xmin, ymin, xmax, ymax]
... | 91cd205ee1aa7b19eda552353d9bf4f55ae52905 | 36,423 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.