content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def nice_Horizons(target, centre, epochs, id_type, refplane='earth'):
"""
Mike Alexandersen
Convenience function to reformat data returned by Horizons
Only require the inputs I actually want to vary.
Return in the format I actually want, not an astropy table.
"""
horizons_table = Horizons(t... | e3803f4886a10850199eeb2b8532a5a7db9ff103 | 42,200 |
import random
def policy_iteration(mdp,verbose=0):
"""Solves an MDP by policy iteration"""
U = {s: 0 for s in mdp.states}
pi = {s: random.choice(mdp.actions(s)) for s in mdp.states}
if verbose:
print("Initial random choice:",pi)
iter_count=0
while True:
iter_count+=1
... | eeb017febda3857c62a9c5b83dee440b40ea7f2d | 42,201 |
import sys
def calc_contact(scp,sigma_ext):
"""
return (du_da, # distributed stress concentration field along crack, in Pa/m, positive tensile
contact_stress, # physical positive-compression contact stress between crack faces, Pa
displacement) # Physical displacement between crack s... | 7c234b9402f758b0cecbd6352d919a361db5ff3a | 42,202 |
def _func_call_cache_key(func, arg_map_function, *args, **kwargs):
"""
Returns a cache key based on the function's module,
the function's name, a stringified list of arguments
and a stringified list of keyword arguments.
"""
arg_map_function = arg_map_function or force_text
converted_args =... | f4ecfa3fdb5848b43c0df4cefd0f88b5fc149da3 | 42,203 |
def thermal_conductivity_carbon_steel(temperature):
"""
DESCRIPTION:
[BS EN 1993-1-2:2005, 3.4.1.3]
PARAMETERS:
OUTPUTS:
REMARKS:
"""
temperature += 273.15
if 20 <= temperature <= 800:
return 54 - 0.0333 * temperature
elif 800 <= temperature <= 120... | cfeb40bcff2b2acb6bf8c60f1bea2b00f323207a | 42,204 |
def reshape_image(frame, model):
"""
reshape_image:
Reshaping the camera input frame to fit the model
"""
image = frame.copy()
image = tf.image.resize_with_pad( np.expand_dims(image, axis=0), model.input_dim[0], model.input_dim[1] )
input_image = tf.cast(image, dtype=tf.float32)
... | b2defbb91c90be58d28b6c40b6c7002cb5b88c49 | 42,205 |
import inspect
def _get_func_signature(func):
"""
Given a function or method, return its signature.
For example:
1 function::
def func(a, b='a', *args):
xxxx
get_func_signature(func) # 'func(a, b='a', *args)'
2 method::
class Demo:
def __init__(... | 39907227e724b33c9ec1f56fe2a91cda3ecd1d53 | 42,206 |
def get_password():
"""
:return: the password of the user (needed for lid)
"""
global _password
return _password | c08d5c41041d4807426092972a40589cff6e031c | 42,207 |
import os
def _file(*args):
""" Wrapper around os.path.join and os.makedirs."""
filename = os.path.join(*args)
_makedirs_for_file(filename)
return filename | c8cb9e7a05b09ada4d0d5ac682a4fbdb394a2475 | 42,208 |
from typing import Callable
from typing import Tuple
def get_chosen_table_size(input_text: str, get: Callable[[str], QWidget]) -> Tuple[int, int]:
"""
Returns chosen table size from gui according to given input text
"""
if len(input_text) <= 0:
return (0, 0)
sizes, _ = get_potential_tabl... | 458176b796ed3312c6ec25bf8f1537bc5b6169d4 | 42,209 |
def get_scheme(url):
"""
Get the scheme from a URL, if the URL is valid.
Parameters:
url: A :term:`native string`.
Returns:
The scheme of the url as a :term:`native string`, or ``None`` if the
URL was invalid.
"""
try:
return urlparse(url).scheme
except Valu... | 40a400faa1f5924730a481d66c5f13eeee67a61b | 42,210 |
def fast_inverse_hadamard_transform(k, dist):
"""Performs inverse Hadamard transform."""
if k == 1:
return dist
dist1 = dist[0:k // 2]
dist2 = dist[k // 2:k]
trans1 = fast_inverse_hadamard_transform(k // 2, dist1)
trans2 = fast_inverse_hadamard_transform(k // 2, dist2)
trans = np.concatenate((trans1 +... | 88448b0fa8ea173c034adcc53d549b0b30f1323b | 42,211 |
def putListIntoInt(inList, base = 2):
"""takes a list of values and converts it into an int"""
string = "".join(str(i) for i in inList)
return int(string, base) | a73c3f64e44962a34d974098e0b04fe92395adc8 | 42,212 |
def parse_money(s: str, *, unit="円") -> int:
"""Parse amount of money en JPY.
The unit of string ("円" or "万円") can be chosen the to apply
the appropriate conversion to JPY units.
"""
if s == "-":
return 0
multipliers_by_unit = {"円": 1, "万円": 10000}
pattern = rf"(\d*[.]?\d+){unit}"
... | 8389c7eb1144d966ff5731ae6415bc7208e7e50f | 42,213 |
def false_pred():
"""Returns a predicate that always returns ``False``."""
def new_pred(*args):
return False
return new_pred | 07dcd2e8594bd27eb4d520b240a0e3e722c7bc79 | 42,214 |
def DeferredLightResolveAddShadowManager(builder, shadowManager):
"""This method is deprecated. Please switch to AddShadowManager."""
return AddShadowManager(builder, shadowManager) | 3e143ca583a5a0772a0246f8e34dae22acf3d4cd | 42,215 |
def calculate_speech_ratio(vad):
"""Calculate percentage of time when each speaker is active"""
speaker1 = np.sum(vad[:, 0]) / vad.shape[0]
speaker2 = np.sum(vad[:, 1]) / vad.shape[0]
speakers = speaker1 + speaker2
return np.array([[speaker1 / speakers, speaker2 / speakers], [speaker1, speaker2]]) | 81b7a1178bd23b1d4a4e024792da7eae8057efb3 | 42,216 |
def get_leaves(conn, category, attached_db="", tbl=""):
"""returns a list of 'category' objects in attached_db
[objectCode, objectLabel, Definition, 'sub-level']
"""
# create formatting shortcuts
def f(t):
return ('"%s"' % t.replace('"', '""')) if t != "" else t
def d(t):
return... | 3bb3570e9d9408011aa186aab39232d64a9c9cc2 | 42,217 |
def start_session(file_name='appdata.db', echo=False):
""" 既存のデータベースを使ってセッション開始 """
db_engine = create_engine('sqlite:///' + file_name, echo=echo)
metadata = Base.metadata
Session = sessionmaker(bind=db_engine)
return Session() | 29517df5edd27419a56892e02175c5b7b39affa3 | 42,218 |
def process_NNC(chrom, positions, strand, edge_IDs, vertex_IDs, transcript_dict,
gene_starts, gene_ends, edge_dict, locations, vertex_2_gene, run_info):
""" Novel not in catalog case """
novelty = []
start_end_info = {}
gene_ID = find_gene_match_on_vertex_basis(
vertex_IDs, str... | e5941b107d7368c5c1f8f91802089b9d0300d7c7 | 42,219 |
def density_angle(rho0: Density, rho1: Density) -> float:
"""The Fubini-Study angle between density matrices"""
rho1 = rho1.permute(rho0.qubits)
return fubini_study_angle(rho0.tensor, rho1.tensor) | 203701a38fdf0e5fe02bacaed78282d95d0e84ce | 42,220 |
def forward_solve(eqns, knowns, branching=False):
"""Returns a dict of unknowns:solutions from a simple backward solve.
Does a simple backward solver for a list of eqn given a list of unknowns.
Each equation should be an expression that equals zero. If an unknown is
not solved for, then its entr... | 401aebffd8213d9d23f7cbff7085469de3872200 | 42,221 |
def _covariance_diag(matrix, dof, mem_threshold=(10**9)/8):
"""
computes the sample covariance matrix from a 2d-array.
matrix should be demeaned before!
Computes an optimal shrinkage estimate of a sample covariance matrix
as described by the following publication:
Schäfer, J., & Strimmer, K. (... | ce5d448c0e3f053ace30ed7340d7c7cc8f549446 | 42,222 |
def get_index_of_quantile(dist_mat: np.ndarray, quantile: float):
"""Returns index of `quantile` in `dist_mat`.
Args:
dist_mat (np.ndarray): square distance matrix
quantile (float): quantile
Returns:
index (int): index of quantile
"""
flat_dist_mat = dist_mat.flatten()
... | 7eacf4bb431bc952c1ee859fe653b4e588cce7c4 | 42,223 |
def RefineBlock(high_inputs=None,low_inputs=None):
"""
A RefineNet Block which combines together the ResidualConvUnits,
fuses the feature maps using MultiResolutionFusion, and then gets
large-scale context with the ResidualConvUnit.
Arguments:
high_inputs: The input tensors that have the high... | c4e4e6883869af848de95be124205a3a0ac62011 | 42,224 |
import typing
def process_get_account_transactions(
status: int,
json: list,
network_type: models.NetworkType,
) -> typing.Sequence[models.Transaction]:
"""
Process the "/account/{public_key}/transactions" HTTP response.
:param status: Status code for HTTP response.
:param json: JSON data... | e52396610bc536fd7c2246205080f95a0358f282 | 42,225 |
import psi4
def psi4(input_data):
"""
Runs Psi4 in API mode
"""
# Insert API path if needed
psiapi = config.get_config("psi_path")
if (psiapi is not None) and (psiapi not in sys.path):
sys.path.insert(1, psiapi)
try:
except ImportError:
raise ImportError("Could not fi... | 66d4e0998441ef29d88d84a27e52417acfc115e0 | 42,226 |
import re
import functools
def in_struct(ln,FO,nesting=0):
"""Copy a top level structure over to the #define output, keeping track of
nested structures."""
if nesting == 0:
if re.match(r"(}.*);",ln):
FO.write(ln[:-1] + "\n\n");
return find_struct;
FO.write(ln + " \\\n"... | e538f1906c1e7f1817185d163f47bf4753993e97 | 42,227 |
import random
def __random_positions(max_position):
"""Generates two random different list positions given a max position.
The max position is exclusive.
...
Args:
max_position(integer): The maximum position
"""
[lhs, rhs] = random.sample(range(0, max_position - 1), 2)
return (lh... | ee35a6ed30400c885b7769962de483c34cc0ab41 | 42,228 |
def errorEllipse(fit, p1, p2, n=100):
"""
fit is a result from leastsqFit (dict)
p1, p2 are parameters name (str)
n number of point in ellipse (int, default 100)
returns ellipse of errors (x1, x2), computed from the covariance. The n values are centered
around fit['best']['p1'] and fit['best'][... | 377a687a43ad473c2107de3ac00ac71d8a0dc706 | 42,229 |
from ...commands.stacker import Stacker
import os
def get_config_directory():
"""Return the directory the config file is located in.
This enables us to use relative paths in config values.
"""
# avoid circular import
command = Stacker()
namespace = command.parse_args()
return os.path.dir... | bd7bc62953c1a4edd84bdc77271eb6b33928cb96 | 42,230 |
def app_info(app_name):
"""gets app info"""
app_path = app_installed(app_name)
try:
return readPlist(app_path + "/Contents/Info.plist")
except ExpatError:
return | d98289817310c5359f81e6dea822dda0be398525 | 42,231 |
def create_deployment(inputs,
labels,
blueprint_id,
deployment_id,
rest_client):
"""Create a deployment.
:param inputs: a list of dicts of deployment inputs.
:type inputs: list
:param labels: a list of dicts of depl... | 84b7a13c0ef6b67b20755bc92ecc6814db0be5b0 | 42,232 |
from typing import Dict
def _refine_projectlist(response: Dict, Translator=DataFields) -> ProjectList:
"""Parse the project list response.
Args:
response: Ganttic API response
Translator: Description of fields
Returns: project List Pydantic.
"""
return ProjectList(**response) | 77b77f3321e8f078087245fb1d18c62fa954e951 | 42,233 |
from typing import Union
from typing import IO
import click
from io import StringIO
from typing import cast
from pathlib import Path
from typing import TextIO
def parse(
in_data: Union[str, PathLike, IO],
encoding: str = "utf-8",
results_fname: str = _RESULTS_FNAME,
max_size: int = _MAX_SIZE,
) -> dic... | 0878a578e42b5e668315f9787784465cfd3ef162 | 42,234 |
import os
def load_dataset(args):
"""
Load UKBB or CIFAR10 datasets
Image centering statistics
/lfs/1/heartmri/coral32/flow_250_tp_AoV_bh_ePAT@c/
max: 192
mean: 27.4613475359
std: 15.8350095314
/lfs/1/heartmri/coral32/flow_250_tp_AoV_bh_ePAT@c_P/
max: 4095
... | 2bea70a15208510621d17a5728bb1e6cf08b5d17 | 42,235 |
import re
def split_sentences(text, delimiter="\n"):
""" Split a text into sentences with a delimiter"""
return re.sub(r"(( /?[.!?])+ )", rf"\1{delimiter}", text) | 7f69afaa8add8947073d1bf4133da145fba81cac | 42,236 |
def getFPSA3(ChargeSA):
"""The calculation of fractional charged partial negative surface areas
-->FPSA3
"""
temp=0.0
for i in ChargeSA:
temp=temp+i[2]
if temp == 0.0:
return 0.0
else:
return getPPSA3(ChargeSA)/temp | 88316a65865faee863ef07f9c01c49320fcbf030 | 42,237 |
def load_FF(data_files, parm_dict, h5_path, verbose=False, loadverbose=True,
average=True, mirror=False):
"""
Generates the HDF5 file given path to data_files and parameters dictionary
Creates a Datagroup FFtrEFM_Group with a single dataset in chunks
Parameters
----------
data_files : list
List of the \*.i... | 24cbd276dcc2a41e214eac8609d77b28f267ba9d | 42,238 |
def DoG1filter(a, sigma):
"""
Creates 2 1-D gaussian filters.
Parameters
----------
a : half-support of the filter.
sigma: standard deviation.
Notes
-----
2-D DoG filters can be contructed by combining 2 1-D DoG filters separably, in x and y directions
Refere... | bb63f5eb7fa4e4546d727a1443ee6209735e1ce8 | 42,239 |
def items_iterator(dictionary):
"""Add support for python2 or 3 dictionary iterators."""
try:
gen = dictionary.iteritems() # python 2
except:
gen = dictionary.items() # python 3
return gen | e3da23ad32f491958887f14aae1f4d34a5d58c4e | 42,240 |
def do_permutation(df_reference: pd.DataFrame,
df_future: pd.DataFrame,
seed: int) -> pd.DataFrame:
"""
Conducts a permutation test with the given reference classifications,
future classifications, and seed.
"""
# Permute the reference and future data.
np.... | 8abae83e0b43edcc7387319e9e4125e881370379 | 42,241 |
def control_game(cmd):
"""
returns state based on command
"""
if cmd.lower() in ("y", "yes"):
action = "pictures"
else:
action = "game"
return action | 669a7b4a9335719aa9176c32c9891f6d017a1bc0 | 42,242 |
def evaluate_metric(logger, pred_labels_list, gt_labels_list, label2class_list, test_classes):
"""
:param pred_labels_list: a list of np array, each entry with shape (n_queries*n_way, num_points).
:param gt_labels_list: a list of np array, each entry with shape (n_queries*n_way, num_points).
:param test... | 3cdc058d34713e92c463114d4b2217450edc75d9 | 42,243 |
import re
def answer_problem(problem):
""" 回答问题 """
problem_context = re.findall(r'(\d+)(\w+)(\d+)', problem)[0]
expression = '%s%s%s' % (problem_context[0], _operators[problem_context[1]], problem_context[2])
return int(eval(expression)) | c9f4ed16ae542ba7074c90264db86eccadd311cd | 42,244 |
def Extrema_Curve2dTool_Parabola(*args):
"""
:param C:
:type C: Adaptor2d_Curve2d &
:rtype: gp_Parab2d
"""
return _Extrema.Extrema_Curve2dTool_Parabola(*args) | df03eece6537847a8fc98dc04709fa403a73ef0c | 42,245 |
def _get_argnames_argvalues(argnames=None, argvalues=None, **args):
"""
:param argnames:
:param argvalues:
:param args:
:return: argnames, argvalues - both guaranteed to be lists
"""
# handle **args - a dict of {argnames: argvalues}
if len(args) > 0:
kw_argnames, kw_argvalues = ... | 4958f038f00fa17acb6930adc9fa406e8d96125c | 42,246 |
import yaml
import math
def new_vnfd_v3(mydb, tenant_id, vnf_descriptor):
"""
Parses an OSM IM vnfd_catalog and insert at DB
:param mydb:
:param tenant_id:
:param vnf_descriptor:
:return: The list of cretated vnf ids
"""
try:
myvnfd = vnfd_catalog.vnfd()
try:
... | 3b51952e0270794ed897b8ff02ab6718dd2cd26b | 42,247 |
def clip(x, a_min, a_max):
"""Clip (limit) the values in an array. Given an interval, values
outside the interval are clipped to the interval edges.
Parameters
----------
x : tvm.Tensor
Input argument.
a_min : int or float
Minimum value.
a_max : int or float
Maximum ... | 45993469a5bab1474c5682a0e9a053507d4b01cb | 42,248 |
def sprints_needed(data):
""" sprints needed """
clus = StackCluster()
for j in range(data[1]):
clus.add_stack(True)
init = int(data[2] / max(data[0]) / data[1])
for j in range(data[1]):
sim = np.random.choice(data[0], init, replace=True)
for k in range(init):
... | 36caa57cf89ee9448b07d88efdde266de25755c1 | 42,249 |
import requests
def get_ipo_calendar(from_date: str, to_date: str) -> pd.DataFrame:
"""Get IPO calendar
Parameters
----------
from_date : str
from date (%Y-%m-%d) to get IPO calendar
to_date : str
to date (%Y-%m-%d) to get IPO calendar
Returns
-------
pd.DataFrame
... | 194319d01a4327037d1742dadeae97c37a9d7225 | 42,250 |
import timeit
def run_trial(rep, num):
"""Sleep for 100 milliseconds, 'num' times; repeat for 'rep' attempts."""
sleep = 'sleep(0.1)'
return min(timeit.repeat(stmt=sleep, setup = 'from time import sleep', repeat=rep, number=num)) | fcdcea9e63531b7de12ccbf27ab584829b8354b9 | 42,251 |
def cholesky(A):
"""
# A is positive definite mxm
"""
assert A.shape[0] == A.shape[1]
# assert all(A.eigenvals() > 0)
m = A.shape[0]
N = deepcopy(A)
D = ones(*A.shape)
for i in range(m - 1):
for j in range(i + 1, m):
N[j, i] = N[i, j]
D[j, i] = D[i, j]... | 593b9adcbdac3721e314a377b68982fb0d44d3c7 | 42,252 |
def apply_sprite(image, sprite,w,x,y, angle, ontop = True):
"""
image: array or image like object
sprite: array or image like object
w:int
x:int
y:int
"""
sprite = rotate_image(img = sprite, angle = angle, scale = 1.0)
sprite, y_final = adjust_sprite2head( sprite , w, ... | b8d32323f691732ef57b3a95d4b1da9c5fe1a6cb | 42,253 |
import os
import re
import torch
def load_embeddings(xlm_path = "data/xlm-embeddings/", save=False):
""" Load data from all tensors into single dataframe"""
# embeddings = pd.concat([
# pd.DataFrame(torch.load(xlm_path+"xlm-embeddings-0_499.pt").data.numpy(), index=range(0,500)),
# pd.DataFrame(torch... | 15850ca204c6ea508c55d375d93ffbd7bb803962 | 42,254 |
def basic_style(color=None, size=None, opacity=None, stroke_color=None, stroke_width=None):
"""Helper function for quickly creating a basic style.
Args:
color (str, optional): hex, rgb or named color value.
Defaults is '#FFB927' for point geometries and '#4CC8A3' for lines.
size (in... | e607c9f04e085367900393804f7ce119524da81c | 42,255 |
def git_errors_message(git_info):
"""Format a list of any git errors to send as slack message"""
git_msg = [
{
"color": "#f2c744", "blocks": [
{
"type": "divider"
},
{
"type": "section", "text": {"type": ... | 192c1f5c85c4615828873795eb8f71d8ced4080e | 42,256 |
import sqlite3
def get_avg_score(num_moves=None, num_trials=None):
"""Get the average score for a specified configuration of num_moves and num_trials
Args:
num_moves (int, optional): The value for num_moves which printed trials must match. Defaults to None.
num_trials (int, optional): The val... | e75c7865b7bd49edf9fd2b73561734482e28cfd2 | 42,257 |
def sort_sentence(sentence):
"""Takes in a full sentence and returns the sorted words."""
words=break_words(sentence)
return sort_words(words) | 23d0f3b5b554ddb405e79c95b1e663cb50ec4047 | 42,258 |
from iotbx.pdb import fetch
def get_pdb_file(file_name, print_out=True):
""" (file_name) -> file_path
This function will check if a pdb file_name exist.
If it is not, it will either fetch it from the RCSB website
or find it on LBLs pdb mirror folder
:param file_name (str): a pdb file name
:return file_na... | 1e28309f4c3fcb59295ec305c32e8cff46f5014e | 42,259 |
def create_knx_exposure(
hass: HomeAssistant, xknx: XKNX, config: ConfigType
) -> KNXExposeSensor | KNXExposeTime:
"""Create exposures from config."""
address = config[KNX_ADDRESS]
expose_type = config[ExposeSchema.CONF_KNX_EXPOSE_TYPE]
attribute = config.get(ExposeSchema.CONF_KNX_EXPOSE_ATTRIBUTE)
... | b3bb96eba5968e3e3b85719c7324d216de451029 | 42,260 |
def normalize_vector(v):
"""
Takes in a vector in list form, concatenates it to form a single vector,
normalizes it to unit length, then returns it in list form together with its norm.
"""
norm_val = np.linalg.norm(np.concatenate(v))
norm_v = [a / norm_val for a in v]
return norm_v, norm_val | 99c8755a53169967eceac997df662d19a436301f | 42,261 |
def clean_data(df):
"""Clean categories and merge to messages
Args:
df => DataFrame of merged categories and messages csv files
Returns:
df => Dataframe of cleaned categories and dropped duplicates
"""
categories = pd.Series(df.categories).str.split(';', expand=True)
row = catego... | 45c3bdb4aa0fef4b5e5a2f8665ddfc10dd846e2f | 42,262 |
def vote():
"""
/vote
description: Seconds the proposal
vote: Vote on a Referendum either "yes" or "no"
ref_index: the value returned from /get_ref or use PropIndex
Request payload
{
'spider_id' : 'xxxx',
'phrase' : '...',
'ref_index' : '4',
'vote': 'ye... | 7a92a6276accbf471882c97c4503fb8ed61179f8 | 42,263 |
def getAllModules():
"""
Returns a list of all modules that should be checked.
@rtype: list of L{pcmodules.PyCheckerModule}
"""
modules = []
for module in pcmodules.getPCModules():
if module.check:
modules.append(module)
return modules | c8a2112138b663471023228fd7499fd36e015389 | 42,264 |
from pathlib import Path
def load_matrix_flexible(matrix_file: str) -> ndarray:
"""Load a matrix data from .tiff, .npy or .txt file."""
path = Path(matrix_file)
if path.suffix in (".tiff", ".tif"):
return load_img(matrix_file)
elif path.suffix == ".npy":
return np.load(matrix_file)
... | 4cc33e1d545568b12f138682386092770777add6 | 42,265 |
import torch
def sp2torch(sparse_mx):
"""Convert a scipy sparse matrix to a torch sparse tensor."""
sparse_mx = sparse_mx.tocoo().astype(np.float32)
indices = torch.from_numpy(np.vstack((sparse_mx.row, sparse_mx.col)).astype(np.int64))
values = torch.from_numpy(sparse_mx.data)
shape = torch.Siz... | 5546a8d0ee691818e65186f08494176ce6ccc781 | 42,266 |
def Distribution_of_masses(**kwds):
"""
输出双黑洞质量的分布。(ratio_step 不能小于 0.01,可以通过增大 doa=100 提高精度)
Input:
共有三种输入方式,如下面的例子:
Eg1: mass1_scope = (5,75), mass2_scope = (5,75), mass_step = 2
Eg2: mass1_scope = (5,75), mass_step = 2, ratio_scope = (0.1,1), ratio_step = 0.1
Eg3: Mass_scope = (5, 30... | aaef2ddcf589f9a299685344f1ee076e469150bf | 42,267 |
import os
import logging
import subprocess
def run_command(command, cwd=None):
# type: (List[str], str) -> List[str]
""" Run a given command and report the execution.
:param command: array of tokens
:param cwd: the working directory where the command will be executed
:return: output of the comman... | 5755a5474939796bfee7be73f3759df6f29b0f03 | 42,268 |
def DecodePublic(curve, bb):
"""
Decode a public key from bytes. Invalid points are rejected. The
neutral element is NOT accepted as a public key.
"""
pk = curve.Decode(bb)
if pk.is_neutral():
raise Exception('Invalid public key (neutral point)')
return pk | 7bf8d7eb129fe640475fbf404354c204f3242954 | 42,269 |
def parse_result_page(html):
"""
"""
dfs = []
for df in pd.read_html(html, thousands=' '):
grouper = df.columns[0]
value_cols = df.columns[1:].tolist()
df.columns = ["group"] + value_cols
df_long = pd.melt(df, id_vars="group", value_vars=df.columns[1:],
... | e539531e8832c0a80992e4239d792e00b8e1ac31 | 42,270 |
def _read_schema(proto_path):
"""Reads a TF Metadata schema from the given text proto file."""
result = schema_pb2.Schema()
with open(proto_path) as fp:
text_format.Parse(fp.read(), result)
return result | 2f9301d1ce0e478a83fee6c433702bf25092d591 | 42,271 |
def compact(it):
"""Filter false (in the truth sense) elements in iterator."""
return filter(bool, it) | 0d84d2e7c35447969bfb3b357389e416c71b40bd | 42,272 |
import os
from io import StringIO
def export(export_file_type, filename, exporter_name=None):
""" Convert a file to another type and download that file.
:param export_file_type: the type to export a file as
:param filename: file to be exported
:param exporter_name: optional name of the specific expor... | c5ba9cc5effaf1316ef5ef891fd78e1968beb1d9 | 42,273 |
def session_capabilities(session_capabilities):
"""Log browser (console log) and performance (request / response headers)
data.
They will appear in `Links` section of pytest-html's html report.
"""
session_capabilities["loggingPrefs"] = {
"browser": "ALL",
"performance": "ALL"
}
return session... | ab87146f815dffa905a60d143f7aebf4a64d3ad0 | 42,274 |
def find_nearest(arr, val):
"""Find index(es) of "nearest" value(s).
Parameters
----------
arr : array_like (ND)
The array to search in (nd). No need to be sorted.
val : scalar or array_like
Value(s) to find.
Returns
-------
out : tuple
The index (or tuple if nd... | 3c2271efc6178332a885f80d419b319fd2cb21e5 | 42,275 |
def calculate_overlap_rate(inventor_class_nbr_group_count_dict):
"""
计算交叠率
:param inventor_class_nbr_group_patent_count:
:return:
"""
#发明家的总数
inventor_cnt = len(inventor_class_nbr_group_count_dict.keys())
#无法分组的发明家数量
cant_group_inventor = 0
for inventor, class_nbr_group_count_dic... | 0c59c8ffaf8407b4f1ede86c8a3b5b4202f211fc | 42,276 |
import ast
def _parse_mock_imports(mod_ast, expanded_imports):
"""Parses a module AST node for import statements and resolves them against
expanded_imports (such as you might get from _expand_mock_imports).
If an import is not recognized, it is omitted from the returned dictionary.
Returns a dictionary suit... | 50cb8e4e2469b7bf63deacf0a5085afcded0b5e3 | 42,277 |
from typing import Union
def to_numpy(array: Union[pa.Array, pa.ChunkedArray]):
"""For non-chunked arrays, need to pass zero_copy_only=False."""
if isinstance(array, pa.ChunkedArray):
return array.to_numpy()
return array.to_numpy(zero_copy_only=False) | c2fcb61b79056183e0606ace886bc2a0f3c1d7a1 | 42,278 |
import os
import numpy as np
def merge_coord_and_label_files(ROI_coords_dir):
"""
utils for merging different label and coord file before computing label masks if necessary
should be rewritten to more more general with glob("Coord*.txt) and glob("Labels*.txt)...
"""
list_coords = []
... | 0e6965aa1c7f3699f1e5f0b7fef957f09e680e85 | 42,279 |
def get_model(inputs, max_length, dim=25):
"""
input - vocabulary size, a number of unique words in
our data set
max_length - the maximum length of each sequence of words
(a document)
dim - word embedding dimension, the lenght of word vector
that will be produced... | 1901225c5dc078f49f7c9b6a1a3c41cf0f6c8d95 | 42,280 |
def calc_field_size(field_type, length):
"""
Рассчитывает размер данных поля
:param field_type: Тип поля
:type field_type: string
:param length: Длина поля
:type length: int
:return: Длина поля в байтах
:rtype: int
"""
if field_type == 'B':
return length
elif field_t... | 677b28d03d02e45d2f7a771c3c895c16060c229a | 42,281 |
def local_channel(obj):
"""
Return the parallel region local channel number `obj` is executing in.
The channel number is in the range of zero to ``local_max_channel(obj)``.
Args:
obj: Instance of a class executing within Streams.
Returns:
int: Parallel region local channel num... | 315c8a0c1a3f908e756672a752ae053e540fbe61 | 42,282 |
def import_results(file_name):
"""Import scientific instrument data. The routine is as follows:
1. Read in all the excel sheets at one time.
2. Get the sample name.
3. Get and tidy the compound data from the compound sheet.
4. Add the analyte names and measurements to a list of resul... | 018827e5ea14cb3db436e081ebc7a328bd603281 | 42,283 |
def SortByName(list_response):
"""Return the list_response sorted by name."""
return sorted(list_response, key=lambda x: x.name) | 5cb48e536790c9f246aebe2a38bba77f329c5ae9 | 42,284 |
def calculateTetTwt(C):
"""Calculate tetanus/twitch ratio.
Calculate the tetanus/twitch ratio for every sigmoid with
parameter c in vector C.
Parameters
----------
C : 1-D array, float
Sequence of values to be used as parameter of a sigmoid function.
Returns
------... | 66c2f8ebea6f62dc2c74f8017ffc830f00170e90 | 42,285 |
from typing import Optional
def jwt_encode(
payload: dict[str, any],
secret: Optional[str] = None,
algo: Optional[str] = None,
) -> str:
"""Encode payload into a JWT"""
return jwt.encode(
payload,
secret or current_app.config["SECRET_KEY"],
algorithm=algo or current_app.con... | fac8b91962f4d187853f167a671052cd28f5d4bb | 42,286 |
def specs_free_photoz_info(my_photoz_info):
"""specs_free_photoz_info(user_pz_info my_photoz_info)"""
return _ccllib.specs_free_photoz_info(my_photoz_info) | c428f32113d2de0aaaa22f216d2ecb09fcd281fa | 42,287 |
from Bio.File import _IndexedSeqFileDict
def index(filename, format=None, key_function=None, **kwargs):
"""Indexes a search output file and returns a dictionary-like object.
- filename - string giving name of file to be indexed
- format - Lower case string denoting one of the supported format... | 8cb3ff1455b01ef9a462a726395aad587cf3c358 | 42,288 |
def equal_two_arrays(array1, array2, eps, tolerance, throwError=True):
"""
This function will compare the values of two python tuples. First, if the values are below
eps which denotes the significance level that we care, no comparison is performed. Next,
False is returned if the different between any ... | 781e567860bc6058c34ee5b689eeebfcaa49d009 | 42,289 |
def additive_attention(query, memory, mem_mask, hidden_size,
ln=False, proj_memory=None, num_heads=1,
dropout=None, scope=None):
"""
additive attention model
:param query: [batch_size, dim]
:param memory: [batch_size, seq_len, mem_dim]
:param mem_mask: [... | 13c24facf1ea585de54c5bf8d98c9e7294e9dda3 | 42,290 |
def radec_to_xyz(ra_deg, dec_deg):
""" Convert RA and Dec to xyz positions on a unit sphere.
Parameters
----------
ra_deg, dec_deg : float or arrays of floats, shape (N,)
RA and Dec in degrees.
Returns an array of floats with shape (N, 3).
"""
ra = np.asarray(ra_deg) * RAD_PER_DE... | ba9d34a71abed2c9185a0d7ae2c296d77a246497 | 42,291 |
from sampling import MetropolisGauss
def sample_hybrid_zprior_xmetro(network, niter, nprior, nmetro, prior_std=1.0, noise=0.02, z0=None, x0=None,
mapper=None, verbose=0):
""" Samples iteratively using Prior MCMC in z-space and Metropolis MCMC in z-space
Parameters
-------... | 30417bfd27a1b1793cc063a220113290fe20d9aa | 42,292 |
def multiplex_modularity(B, mu, membership):
"""Calculates a multiplex modularity score.
Calculates the modularity from a given modularity matrix and membership
vector.
Args:
B (scipy.sparse.csr_matrix): An n by n sparse modularity matrix where
n is the number of vertices across al... | c4bdb8ebd60179eee1e4ee217ace2ff31bd090f1 | 42,293 |
import re
def unindent(string):
"""Remove the initial part of whitespace from string.
>>> unindent("1 + 2 + 3\\n")
'1 + 2 + 3'
>>> unindent(" def fun():\\n return 42\\n")
'def fun():\\n return 42'
>>> unindent("\\n def fun():\\n return 42\\n")
'def fun():\\n return 42'
>>> u... | 1179d4d4a67380b95d46b3234e4b09fb83f36041 | 42,294 |
def unpackdict(table, field, keys=None, includeoriginal=False,
samplesize=1000, missing=None):
"""
Unpack dictionary values into separate fields. E.g.::
>>> import petl as etl
>>> table1 = [['foo', 'bar'],
... [1, {'baz': 'a', 'quux': 'b'}],
... ... | faee5dab08972b942a0ec1d966584e0b1ea27aae | 42,295 |
from typing import Collection
def is_collection(path):
"""Check if the collection exists"""
return Collection.find(path) is not None | 3c44153649f78794e5233fef8523de45690ed692 | 42,296 |
def download_file(url, download_dir: str):
"""
https://stackoverflow.com/a/53153505/12988588
"""
response = calls.ping_url(url)
filename = url.split("/")[-1]
if len(download_dir) > 0:
os_makedirs(download_dir, exist_ok=True)
out_filepath = os_path.join(download_dir, filename)
wi... | e74a0b08f0892befdea5bf7cab0d218e25511932 | 42,297 |
from typing import Union
from typing import Tuple
import math
def conv2d_padding_size(
h_w_in: Union[int, Tuple[int, int]],
h_w_out: Union[int, Tuple[int, int]],
kernel_size: int = 1,
stride: int = 1,
dilation: int = 1,
) -> Tuple[Tuple[int, int], Tuple[int, int]]:
"""
:param h_w_in:
... | f0fa3b515f495b9f8b385c97f13adcded00d623f | 42,298 |
def register_user(email, name, password, password2):
"""
Register the user to the database
:param email: the email of the user
:param name: the name of the user
:param password: the password of user
:param password2: another password input to make sure the input is correct
:return: an error ... | 3f898d5a13610ebc8a0f31902dae6d0be268b003 | 42,299 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.