content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def __ksunpack(bits):
"""takes an 8-bit number and returns a kset"""
ks = []
_ks = __make_ks()
for i in range(8):
if ((bits >> i) & 1) == 1:
ks.append(_ks[i])
return ks | 019b262fa8075892ac0843c5dd595fc1772a5ee9 | 73,700 |
def a (x: int, y: float) -> int:
"""
A sample
:param x: x value
:type x: int
:param y: y value
:type y: float
:return: result
:return type: int
"""
return 1
# Call tesnor flow here | 717a7b2a031040a48e6a292deca7254010cb1a1d | 73,701 |
def vector_to_midi_events(status, vector):
""" Return MIDI event parameters for given velocity vector.
Status can be specified as one of the keys in ``STATUS_BYTES``.
Args:
status: The status parameter of the returned events.
velocity_vector (np.ndarray): Vector of velocities of each MIDI ... | 24686fd433c529fb639a4e01b9fb9ef1650f1b7b | 73,702 |
def _compute_max_name_width(contracts: dict) -> int:
"""Return the maximum width needed by the function name column."""
return max(
len(function) for contract, functions in contracts.items() for function in functions
) | bc57c408a49182cdfb26a1955a4a3943c060af86 | 73,703 |
def destroy(self, request, *args, **kwargs): # pragma: no cover
"""
Shortcut method.
"""
return self.destroy(request, *args, **kwargs) | c984eae1a2abe66b9f1a015dd1212b5885f72bb6 | 73,704 |
def AcceleratorEntry_Create(*args, **kwargs):
"""
AcceleratorEntry_Create(String str) -> AcceleratorEntry
Create accelerator corresponding to the specified string, or None if
it coulnd't be parsed.
"""
return _core_.AcceleratorEntry_Create(*args, **kwargs) | 9004979f9f1a544d05aeb08d4f62553cc57d04a1 | 73,705 |
def initialize_parameters(layer_dims):
"""
Initialize parameters for different levels of the network
Arguments:
layer_dims -- python array (list) containing the dimensions of each layer in the network
Returns:
parameters -- python dictionary containing your parameters "W1", "b1", ..., "WL", "b... | 04b4e77f2d2e4f731fbc2412dce7d69c867452a4 | 73,706 |
from . import blueprint
from . import db
from sys import path
import pathlib
def create_app(test_config=None):
"""
应用工厂
:param test_config:
:return: app
"""
app = Flask(__name__, instance_relative_config=True)
app.config.from_mapping(
SECRET_KEY=urandom(20),
DATABASE=path.... | b73cd8c60730e4c45f7632aab417fa61bdcf914d | 73,707 |
def parse_ldf(path: str, capture_comments: bool = False, encoding: str = None) -> LDF:
"""
Parses an LDF file into an object
:param path: Path to the LDF file
:type path: str
:param encoding: File encoding, for example 'UTF-8'
:type encoding: str
"""
json = parse_ldf_to_dict(path, captu... | f179629c8686ea9b9c9b645c4b0313c97d7835c5 | 73,708 |
from typing import Union
from typing import Tuple
def inputs(shape: Union[Tuple[int, ...], int],
input_placeholder_label: str = 'x') -> GraphBuilderNoParam:
"""
dl.inputs layer builder
Note that this must be the first layer of any architecture.
"""
if isinstance(shape, int):
sh... | 591106835b71689a132886cdb2800ad1492a60ab | 73,709 |
from typing import Any
def login_access_token(
db: Session = Depends(deps.get_db),
form_data: OAuth2PasswordRequestForm = Depends(),
) -> Any:
"""
OAuth2 compatible token login, get an access token for future requests
"""
user = crud.user.authenticate(
db, email=form_data.username, pas... | a0281be0dd6639f6ecc8baa56ab24a575f845471 | 73,710 |
def load_dataset(path: str):
"""Loads OffensEval 2020 dataset
Args:
path (str): full path of a task_*_distant.tsv file
provided by the organiser
Returns:
pandas.DataFrame containing the data
"""
data_df = pd.read_csv(path, sep="\t", quoting=3)
# remove errenous space ... | 03fc21b2d93eb914306a7c11677dd108f03510c0 | 73,711 |
import logging
def get_logger(name):
"""Get the logger with a given name
Args:
name: name of the logger to create
"""
return logging.getLogger(name) | 0f02aba7f01c2aafbb7fafda0bb260d73fd240a1 | 73,712 |
import re
def is_valid(rut: str = None) -> bool:
"""
Checks if a Chilean RUT number is valid or not
Args:
rut (str): A Chilean RUT Number. Examples 5126663-3 or 5.126.663-3 or 512666633
Default None.
Returns:
bool: True when Chilean RUT number (rut:str) is valid
"""
... | 1c44dafa8e92a704ba42d1fdb9e64737ce2d35d2 | 73,713 |
import re
def checkContainNum(pwd):
"""
判断是否包含数字
:param pwd: 用户密码
:return: 1 -> TURE ; 0 -> FALSE
"""
pattern = re.compile('[0-9]+')
match = pattern.findall(pwd)
if match:
return 1
else:
return 0 | 0e7526616affb3f4228fcde2ebb28ae06166e5db | 73,714 |
def search_dicts(k, v, data):
"""
Search a list of dicts by key
"""
match = []
for row in data:
if k in row:
if v == row[k]:
match.append(row)
if len(match) == 1:
# If we only get one result: return just it as a dictr
return match[0]
else:... | c133ec1452f73e51c19af59b6fb49039dda28176 | 73,715 |
def get_type_tuple(df):
"""
Parameters
----------
df: data frame
Returns
-------
Return a list [(colunm name, datatype)]
"""
return([(c, df[c].dtype) for c in df.columns]) | a5c0568defbbd4a4fdc88bf1e1bce058bf8d8495 | 73,716 |
def calculate_word_strength(word: str) -> int:
"""Calculate the strength of the word."""
total = 0
try:
for letter in word:
total += LETTER_VALUE[letter]
except KeyError:
return 0
return total | 86b9d45d8334c3914d4215ca4f1c3a865379614a | 73,717 |
from typing import Iterable
def raw_corpus_rouge2(hypotheses: Iterable[str], references: Iterable[str]) -> float:
"""
Simple wrapper around ROUGE-2 implementation.
:param hypotheses: Hypotheses stream.
:param references: Reference stream.
:return: ROUGE-2 score as float between 0 and 1.
"""
... | 15df16397ab55858b36c3cfefb82afa7793027b4 | 73,718 |
def decode_enums(obj, available_enums=None):
"""
Decode enums from parsed yaml file
:param obj: object to check
:param available_enums list of available enums classes to decode
:return: decoded object
"""
if isinstance(obj, dict):
new_obj = {}
for... | e8bf3cc55363fbf13ad400bbbfd3006ce23cd3d5 | 73,719 |
def to_normal_strokes(big_stroke):
"""Convert from stroke-5 format (from sketch-rnn paper) back to stroke-3."""
l = 0
for i in range(len(big_stroke)):
if big_stroke[i, 4] > 0:
l = i
break
if l == 0:
l = len(big_stroke)
result = np.zeros((l, 3))
result[:, 0:2] = big_stroke[0:l, 0:2]
res... | 001ed00c95e534d61072c5ae06594c7049a61573 | 73,720 |
import torch
def get_word_embeddings(sentence, sentence_tokenised):
""" Get word embeddings for each word in sentence """
ids = tokenizer.encode(sentence)
ids_tensor = torch.tensor(ids).unsqueeze(0) # Batch size: 1
word_vectors = model(ids_tensor)[0].squeeze()
word_embeddings_all = []
for wor... | 59c316b1ea04e38a01782d73d8d8dec6aa05d9eb | 73,721 |
def check_code(redis, validated_data):
"""校验验证码"""
code_status = redis.check_code(validated_data.get('phone'), validated_data.get('code'))
# 验证码错误或者过期
if not code_status:
return Response(response_code.verification_code_error, status=status.HTTP_400_BAD_REQUEST) | 494b9b6605a047174d90a3f83657d6431065790e | 73,722 |
def parse_Network_Events(recording):
""" goes through Network Events folder and grabs all relevant data
"""
# search through recording for network events
network_events_dfs = []
for event_folder in recording["info"]["events"]:
if "Network_Events" in event_folder["folder_name"]:
i... | 55294a2e7a6ae653edbb02288af3a884cf5286c7 | 73,723 |
def _get_energy(gray: np.ndarray) -> np.ndarray:
"""Get backward energy map from the source image"""
assert gray.ndim == 2
gray = gray.astype(np.float32)
grad_x = sobel(gray, axis=1)
grad_y = sobel(gray, axis=0)
energy = np.abs(grad_x) + np.abs(grad_y)
return energy | 6ec3999bd342a1bb0bc9c4bcec04aec38f9e61fe | 73,724 |
import itertools
def euler4(l=3):
"""Solution for problem 4."""
# simple optimisation would be an early break
return max(n for n in (i * j for i, j in itertools.combinations(range(10 ** (l - 1), 10 ** l), 2)) if str(n) == str(n)[::-1]) | 6e0d4fbeb14b61a30b78caccf4de168fdff12efb | 73,725 |
def check_system(num: np.ndarray, den: np.ndarray) -> bool:
"""Returns true if a transfer function is causal
Parameters
----------
num : np.ndarray
numerator of the transfer function
den : np.ndarray
denominator of the transfer function
"""
try:
M, N = system_order(n... | 039cc0b7948bc236dbe29e11b96f8d878b323568 | 73,726 |
def _parse_ctab_stext(contents):
"""
"""
return {} | 03aaf4b656667b4b0fc4aa4b609d01c2b42c06da | 73,727 |
def normalize_to_rgba(var, arr, colormap):
"""
** This code was lightly edited for clarity and correctness from:
https://github.com/WikiWatershed/model-my-watershed/issues/2122
**
Normalize raster values around display values ranges and convert
to segmented linear interpolated rgba values for r... | c05f5cda3a361620e440ee2f2396bf6c4f7a51b4 | 73,728 |
def keyword_only(func):
"""A decorator that forces keyword arguments in the wrapped method.
Args:
func: A function to mark
"""
@wraps(func)
def wrapper(*args, **kwargs):
if len(args) > 0:
raise TypeError(f"Method {func.__name__} only takes keyword arguments.")
r... | bd37e11cd69bce00dea0b2681525d0f2b73f78fe | 73,729 |
import json
def getBeanstalkClient(port=None):
"""
Start up a beanstalkclient.
"""
config = {}
if not port:
with open('./bucket_validation/listener-config.json', 'r') as f:
config = json.load(f)
port = config["BeanstalkHost"].split(":")[1]
return GeneratorBeanstalkC... | 7bf9cc96bd8c0227979be30382e1197f7914acca | 73,730 |
def get_ebi_issues(redmine, other_fields=dict()):
"""
Get EBI issues from Redmine, add other fields if provided
Return a Redmine ResourceSet
"""
# Other fields replace the keys that already exist in default_fields
search_fields = { **default_fields, **other_fields }
return redmine.issu... | f8481d6721ecefb15951ba8ce9d54519c90232fe | 73,731 |
def generate_signed_request(*, data, nid_signing_key):
"""Generate and return signed request"""
node_identifier = get_verify_key(signing_key=nid_signing_key)
signature = generate_signature(
message=sort_and_encode(data),
signing_key=nid_signing_key
)
return {
'message': data,... | b817f1fa4c10c88a60630e22bb67971e84f111e7 | 73,732 |
import tempfile
import time
def setup():
"""Configures dataset, model, backend, and runner."""
if FLAGS.preprocess_outdir:
outdir = FLAGS.preprocess_outdir
elif FLAGS.outdir:
outdir = FLAGS.outdir
else:
outdir = tempfile.mkdtemp()
backend, ds, post_process, count = utils.setup(
FLAGS.datas... | 43a0db3cfdf0f034895086190e497f630aea30ef | 73,733 |
def _moffat_(r, alpha, beta, normed=False):
""" """
norm = 2*(beta-1)/alpha**2 if normed else 1
return norm * (1 + (r/alpha)**2 )**(-beta) | 6dcea83247d97c1cb52f7051fe1444c21af604c7 | 73,734 |
def cores(scale="celsius", precision=2) -> list:
"""Returns a sorted list with digital thermal sensors values for each core
:Params:
:scale (str): Return scale Celsius, Fahrenheit, Kelvin or Rankine)
:precision (int): Number of rounding decimals
"""
stat = _get_stat()
if len(sta... | a1ab84c7090b9b60f56d00daae03354a35d0d074 | 73,735 |
import math
def db10(arg):
"""
Parameters
----------
arg :
Returns
-------
type
"""
return 10.0 * math.log10(mag(arg)) | cac9afad71cb115ffb41ace851e84e469f439bb5 | 73,736 |
def label_mapping(y_data, known_labels):
"""
Maps all class index to used one. It is possible to subsample number of classes.
:param y_data: Array with labels to map
:type y_data: nd.array
:param known_labels: Labels index to map
:type known_labels: list-like
:return: label_map and y_data w... | d2db167aeb51b02167d530100652625eb44e8bbd | 73,737 |
import os
def decrypt_file(filename, key):
"""
Decrypt a file that was encrypted with AES-256-OCB encryption
`Required`
:param str filename: target filename
:param str aes_key: 256-bit key
Returns True if succesful, otherwise False
"""
try:
if os.path.isfile(filename)... | f178a3c4ab3dddd8b64063867d9841bb5c495a79 | 73,738 |
def get_coherence_len(wfr, dx, dy, VERBOSE = True):
"""
Calculate coherence length of a complex wavefield of shape
[nx, ny. nz]
:param wfr: complex wavefield
:param dx: horizontal pixel size
:param dy: vertical pixel size
:returns Jd: complex degree of coherence
:returns clen: ... | f9b47abdd23bcf16e751e2c1438460f2cf5d1939 | 73,739 |
import operator
def find_frequency(text, n=1):
"""Finds the raw frequencies of all the n-grams in text.
The n sets the size of the n gram. n=1 is a unigram,
n=2 is a bigram, etc.
>>> f = find_frequency('aba')
>>> f['a']
2
>>> f['b']
1
>>> f = find_frequency('ababa', n=2)
... | eba3b13756716994ef1a651d14c0bc53c5b0064e | 73,740 |
from shapely import geometry as geom
from shapely import ops
def alpha_shape_auto(
xys, step=1, verbose=False, return_radius=False, return_circles=False
):
"""Computation of alpha-shape delineation with automated selection of alpha.
This method uses the algorithm proposed by Edelsbrunner, Kirkpatrick &
... | 42eaeaa8d6cc19647033f58d5d5f8d1b919eff95 | 73,741 |
from Bio import SeqIO
import gzip as gz
def rename_records(f, fh, i):
"""
Prepends a number to read ids
:param f: Input fastq file (gzipped)
:param fh: Output filehandle
:param i: File index to prepend to reads
:return: Output filehandle
"""
for record in SeqIO.parse(gz.open(f, 'rt'),... | c421e02a65f9f3bb3935367358ce4b947d9f77bb | 73,742 |
def result_contains_numeric_observed_value(result):
"""
:param result:
:return:
"""
return ('observed_value' in result['result'] \
and acts_as_a_number(result['result'].get('observed_value'))) \
and set(result['result'].keys()) <= set(
['observed_value', 'element_coun... | ee420bae2b1a67cb338ccd663a92f4ba12139529 | 73,743 |
def create_periodic_dosing(timeHigh, timeLow, highVal, lowVal=0):
"""Create a Periodic dosing profile
Create a dosing profile which oscillates between high and low values.
Remains high for timeHigh and low for lowHigh each period
:param timeHigh: Time dosing remains at highVal (float)
:param timeL... | 358723ba0187ffddb91d9aa1d2c70a1f14a774b2 | 73,744 |
from typing import cast
def sr1(x, # type: _PacketIterable
promisc=None, # type: Optional[bool]
filter=None, # type: Optional[str]
iface=None, # type: Optional[_GlobInterfaceType]
nofilter=0, # type: int
*args, # type: Any
**kargs # type: Any
):
# typ... | e159d87d017c06c851d9fdf1b71356b25a5717c8 | 73,745 |
def fix_double_nodes(coor, ngroups, conns, eps):
"""
Detect and attempt fixing double nodes in a mesh.
The double nodes are nodes having the same coordinates
w.r.t. precision given by `eps`.
"""
n_nod, dim = coor.shape
cmap = find_map(coor, nm.zeros((0,dim)), eps=eps, allow_double=True)
... | c632eb4c0ece33683717a1263fcbf63fd63b912f | 73,746 |
import os
import json
from unittest.mock import patch
from unittest.mock import Mock
def test_mfa_cache(mockSnowflakeRestfulPostRequest):
"""Connects with (username, pwd, mfa) mock."""
os.environ["SF_TEMPORARY_CREDENTIAL_CACHE_DIR"] = os.getenv(
"WORKSPACE", os.path.expanduser("~")
)
LOCAL_CA... | 8e7101b0a78290b3bc0966c655c9f85f8507a0b9 | 73,747 |
import itertools
def _generate_centers_and_final_shape(img_shape,
stride,
first_center):
"""
generates final shape and centers for applying a sliding window
"""
dim_ranges = []
for dim_min, dim_max, dim_stride in zip(first... | be92aee8f844e20aa41761e6b89a9c831cd2e934 | 73,748 |
import signal
def spectra(u_i, x_i, **kwargs):
"""
Computes the kinetic energy (KE) of a n-dimensional velocity vector field such as u_i = (u, v, w) for 3D.
:param u_i: n-dimensional velocity vector field
:param x_i: n-dimensional spatial vector field
:param kwargs: k_res for the resolution of k_mod_line which d... | 28d35c8bc89dbcfa5315ca88a88b20225d7410d2 | 73,749 |
import unittest
def load_tests(loader=None, tests=None, pattern=None):
"""Load local tests
"""
if not loader:
loader = unittest.TestLoader()
suite_list = [
loader.loadTestsFromTestCase(FileStorageTests)
]
return unittest.TestSuite(suite_list) | 522e01f9ec018eaf7f30c04ac4082136e7d80051 | 73,750 |
from pathlib import Path
def get_dataloaders(path_to_clotho, input_modal='features', output_modal='words_ind', num_workers=1, shuffle_train=True, batch_size=20):
"""Get dataloaders for CLOTHO dataset.
Args:
path_to_clotho (str): Path to clotho dataset
input_modal (str, optional): Input modali... | 511e32a5484c3fe6c4ecc8988a3d95b80cc39b16 | 73,751 |
def _map_account_name_to_login_names(accounts):
"""
Maps the accounts name to the login names. this method simply groups the csv rows by the account name
:param accounts: list of accounts records
:return: dict
"""
accounts_dict = {}
for account in accounts:
columns = account.decode(... | 9553659e7a8cf4ef192e6019b603f954e242abbe | 73,752 |
def parse_str(s, start_position):
"""
If a Python string literal begins at the specified position in the
given string, then return a tuple C{(val, end_position)}
containing the value of the string literal and the position where
it ends. Otherwise, raise a L{ParseError}.
"""
# Read the open ... | b34cf55907f940479bb83926e1583a786bd3d5e4 | 73,753 |
def modify_coords(coords: dict,
indices: list,
new_value: float,
modification_type: str,
mol: Molecule = None,
) -> dict:
"""
Modify either a bond length, angle, or dihedral angle in the given coordinates.
The coordina... | 6dd73e48d33fc6b1620d18e16941e4277045241b | 73,754 |
def metric_prefix(source):
"""
Format numbers with metric prefixes.
Inspired by: https://stackoverflow.com/a/9462382
"""
prefixes = [
{"value": 1e18, "symbol": "E"},
{"value": 1e15, "symbol": "P"},
{"value": 1e12, "symbol": "T"},
{"value": 1e9, "symbol": "G"},
... | a9733b0486321561c65d122b88cb6ae591e8c0fa | 73,755 |
import os
def looks_like_a_workflow(path):
"""Return boolean indicating if this path looks like a workflow."""
if POTENTIAL_WORKFLOW_FILES.match(os.path.basename(path)):
with open(path, "r") as f:
workflow_dict = ordered_load(f)
if not isinstance(workflow_dict, dict):
#... | b264fb2e554fa90a849116e23f5a88c7c026b21b | 73,756 |
def parse_tsgf_file(content):
"""Returns (players, moves) from a list of strings from a tsgf file
Args:
content: list of strings: content from a tsgf file
Returns:
tuple: (list: players as strings, list: twixt moves)
Raises:
ValueError: if players or moves data can't be interp... | e4bf01d413923cc4099b6ebbdd36854ace32c09d | 73,757 |
import warnings
def bca_method(bootstat, stat, jackstat):
"""Calculates bootstrap confidence intervals using the bias-corrected and accelerated bootstrap interval."""
if stat.ndim == 1:
nboot = len(bootstat)
zalpha = norm.ppf(0.05 / 2)
obs = stat # Observed mean
meansum = np.z... | dc9e6c916193b4ec583fc909cc4fb5323519788f | 73,758 |
def test_cli(loop, sanic_client):
"""Used to create a fresh event loop and sanic app for each test.
Args:
loop (obj): The event loop.
sanic_client (obj): The sanic app object.
Returns:
obj: Event loop.
"""
return loop.run_until_complete(
sanic_client(sanic_app, prot... | 349fd87631f9bb89736e0c45977920b3febc9754 | 73,759 |
def require(validators: tuple):
"""Django's standard permission_required decorator does not recognize 'user' in the 'request'
received by Django rest_framework's APIView, resulting in the user being treated as anonymous.
This custom implementation solves the issue, as well as removes a redirect URL since
... | 1c223cfcb14bcf7e1a2720b5debb59f16813728c | 73,760 |
from typing import List
from typing import Dict
from typing import Union
import torch
def collate_fn(dataset_items: List[dict]):
"""
Collate and pad fields in dataset items
"""
result_batch: Dict[str, Union[list, torch.Tensor]] = defaultdict(list)
for dataset_item in dataset_items:
result... | 60c188fc51576548a53f05276cf65b1b13e414cc | 73,761 |
def match(first_list, second_list, attribute_name):
"""Compares two lists and returns true if in both there is at least one element which
has the same value for the attribute 'attribute_name' """
for i in first_list:
for j in second_list:
if i[attribute_name] == j[attribute_name]:
... | 2b7c38ef3132c5cb9e693be2995691600ac76ec7 | 73,762 |
def sum_up_vol_cluster(clu, p_thresh=0.05, tstep=1e-3, tmin=0,
subject=None, vertices=None):
"""Assemble summary VolSourceEstimate from spatiotemporal cluster results.
This helps visualizing results from spatio-temporal-clustering
permutation tests.
Parameters
----------
... | c8bae1475d584618875600078d5856780d9d1c05 | 73,763 |
import copy
def cut_segment(
source_example: dict, start: int, stop: int,
) -> dict:
"""
Cut one segment from an example. Can be applied before or after
`load_example`.
"""
if stop is None:
stop = source_example['num_samples']['observation']
if not isinstance(start, int) or no... | 5bff1cfe540d1d9f189feafb555c59ae62723ddc | 73,764 |
def email_user(profile, SUBJECT="", BODY=""):
"""
sends an email.
Arguments:
profile -- contains information related to the user (e.g., email
address)
SUBJECT -- subject line of the email
BODY -- body text of the email
"""
if not BODY:
return False... | f810ff3aae8c717f77c8cac041a55efd28a9738c | 73,765 |
def range_cond():
"""Widgets for range conditions and edge case.
Returns
-------
complementary : bool
Specifies cumulative probability or its complement
inclusive : bool
Specifies whether edge case is inclusive
out_txt : str
Output text description of range conditions
... | 8972a87cc052c5d3ac51df98dc029d47d7203395 | 73,766 |
from typing import OrderedDict
def get_major_patterns(patterns, cluster):
"""Get major patterns for each cluster
Args:
patterns: Pattern list
cluster: np.array with cluster names for each pattern
Returns:
list: (cluster, pattern)
"""
try:
df = pd.DataFrame({"n_seqlets"... | fa4ddbc5ba891a85d57ea4d59e3b9a4a522179aa | 73,767 |
def URL( uri ):
"""
Wrapper to create a URL.
This does a first-cut parse to find the scheme,
then recreates a scheme-specific URL object
if one is available.
"""
if isinstance( uri, URL_base ):
tmp = uri
else:
tmp = URL_base( uri )
if tmp.scheme in _uri_map:
r... | e88a6a9744c0d280866a95618d7e07e413e966e4 | 73,768 |
def quaternion_real(quaternion):
"""Return real part of quaternion.
>>> quaternion_real([3, 0, 1, 2])
3.0
"""
return float(quaternion[0]) | 121501c7b687adae959e83877a52d584cec98e75 | 73,769 |
from typing import Callable
def log_prob(
theta: np.ndarray,
*,
discriminator: dinf.Discriminator,
generator: Callable,
parameters: dinf.Parameters,
rng: np.random.Generator,
num_replicates: int,
parallelism: int,
) -> float:
"""
Non-vector version of dinf.dinf._log_prob()
... | a7622dcd41014a81a15d9efa4188bea2b982815c | 73,770 |
def create_valuetype_list(length, elem_shape, dtype):
"""
Return pm.ValueType with List (ListType) set.
length: length of list (int)
"""
v_type = pm.ValueType()
update_listtype(v_type.listType, length, elem_shape, dtype)
return v_type | 3a4ca49c300a5eb150c9fcf7a833f68dcaf6c859 | 73,771 |
def listProxySettings():
"""Returns list of names of all ProxySettings objects"""
return getObjectNameList( 'ProxySettings' ) | 7c0212c90a2e474162c4654c94c634236240ce1d | 73,772 |
def get_spacing_dimensions(widget_list):
"""
will be further developed
"""
space_dimensions = space_label = 0
for widg in widget_list:
space_d = widg.get('dimensions', '')
space_l = widg.get('label', '')
if space_d:
space_d_new = len(list(space_d))
if... | 8c521b1315c120173d22ff25bf3c2b41bdab8ecd | 73,773 |
def handle_form():
"""Return form response; include cookie for browser."""
fav_color = request.args["fav_color"]
# Get HTML to send back. Normally, we'd return this, but
# we need to do in pieces, so we can add a cookie first
html = render_template("response-cookie.html", fav_color=fav_color)
... | c6755e83b8df7dbc020b6f0f955b47393d325acc | 73,774 |
def make_histogram( yy, y0, y1, Nbins ):
"""! Produces a histogram from data in yy.
@param yy Data to histogram
@param y0 Lower bound of histogram
@param y1 Upper bound of histogram
@param Nbins Number of bins.
The number of bins, y0 and y1 together implicitly define
the resol... | 81b4331d66dc101740e5c914b7d68104ce94623c | 73,775 |
def point_set(dimension, N):
"""Uniform distribution of points on the unit-sphere, by partitioning the
unit-sphere into patches with equal area. This function is only a wrapper
for point_set_polar and returns Cartesian coordinates instead of polar
coordinates.
Parameters
----------
dimensio... | 557907042921a9a00c29dd0c039ddd2bdfdf5741 | 73,776 |
def inline_map(m):
"""Takes a folium instance or a html path and load into an iframe."""
if isinstance(m, Map):
m._build_map()
srcdoc = m.HTML.replace('"', '"')
embed = HTML('<iframe srcdoc="{srcdoc}" '
'style="width: 100%; height: 500px; '
... | 934aee742994f16ff256ecb8aaf4bfaa1182b894 | 73,777 |
import numbers
def is_dyad(frac):
""" Test if frac is a nonnegative dyadic fraction or integer.
Examples
--------
>>> is_dyad(Fraction(1,4))
True
>>> is_dyad(Fraction(1,3))
False
>>> is_dyad(0)
True
>>> is_dyad(1)
True
>>> is_dyad(-Fraction(1,4))
False
>>> is_d... | 3d01e13a2d97880205e59fb218881a1e487d9a40 | 73,778 |
def create_mesh(rail_part, contact_surface, z_shift, shadow_size=None, set_name=None):
"""Create dummy elements by extending the rail on one side.
:param rail_part: The part containing the rail geometry with a surface: names.rail_contact_surf
:type rail_part: Part object (Abaqus)
:param conta... | c46c8eb0258df47381f0217cd0514298aed64112 | 73,779 |
def measure_text(text: str , font_size: int)-> int:
"""Measure string width for default font"""
return _rl.MeasureText(_to_byte_str(text) , _to_int(font_size)) | 33bcd0a0ffcf15918f2b1bbba690836146ed798a | 73,780 |
from Bio import SeqIO
def get_mito_length(mito_file):
"""
Returns the length of a mitogenome
Keyword arguments:
mito_file -- the input mitogenome FASTA file
"""
num_sequences = len(list(SeqIO.parse(mito_file, "fasta")))
if num_sequences > 1:
raise Exception("failed because mitoge... | b075f243d5a18408ee8e5b3eefe4f73cc4a3e18d | 73,781 |
from typing import Tuple
def calc_velocity_stats(time: np.ndarray,
signal: np.ndarray,
direction: str = 'up',
time_scale: float = TIME_SCALE) -> Tuple[float]:
""" Calculate the velocity statistics
:param ndarray time:
The time ar... | ff9dc4fd9d7592f66a1f18a4e3cdb0234244f39e | 73,782 |
def map_window(
func, in_stream, out_stream,
window_size, step_size=1,
state=None, initial_value=None,
call_streams=None, name=None,
*args, **kwargs):
"""
Parameters
----------
func: function
function from a single element of the input stream to a
... | 9ed6530c0f76fdebde27c92cf0aadc8381c0bd6c | 73,783 |
def _check_core_match(shape1, shape2):
"""Checks shape1 and shape2 are valid shapes to perform matmul"""
ndim1, ndim2 = len(shape1), len(shape2)
if ndim1 < 1 or ndim2 < 2:
return True
if shape1[-1] == shape2[-2]:
return True
raise ValueError(f'mismatch in core dimension of input oper... | 4acb2430518b2a5c682d7894991095a98d766cc7 | 73,784 |
from auditlog.registry import auditlog
def model_instance_diff(old, new, **kwargs):
"""
Calculate the differences between two model instances. One of the instances may be None (i.e., a newly
created model or deleted model). This will cause all fields with a value to have changed (from None).
"""
... | 30c60778ba2a01e33ef4d631010265da5bb34124 | 73,785 |
from typing import Optional
from typing import Sequence
def get_snapshot(filters: Optional[Sequence[pulumi.InputType['GetSnapshotFilterArgs']]] = None,
opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetSnapshotResult:
"""
Get information about a Vultr snapshot.
## Example Usage... | 8e91949f0d6716031c9370823f8e8a6eb9a39b7d | 73,786 |
import os
import imp
def convert_bedgraph_signal(args, logger):
"""
:param args:
:param logger:
:return:
"""
assert os.path.isfile(args.chromsizes),\
'Invalid path to chromosome sizes file: {}'.format(args.chromsizes)
assert all([os.path.isfile(f) for f in args.inputfiles]),\
... | 8e48904c20a2307a5cd47fcce264573b283bfde2 | 73,787 |
import select
async def get_team_list(session: Session = Depends(get_session)):
"""Get team list"""
statement = select(Team)
results = session.exec(statement).all()
return results | fb86056805ca713c8413ab1a2d5249326a9ff39a | 73,788 |
from typing import Dict
def NDFRTDDA(
directed: bool = False,
verbose: int = 2,
cache_path: str = "graphs/yue",
**additional_graph_kwargs: Dict
) -> EnsmallenGraph:
"""Return new instance of the NDFRTDDA graph.
The graph is automatically retrieved from the Yue repository.
Parameters
... | 81dc685cf1c927d9a00dd891cdca1229aaf6d49c | 73,789 |
import os
from sys import path
import pdb
import logging
import time
def train_eval(
root_dir,
teacher_dir,
env_name=None,
eval_env_name=None,
env_load_fn=suite_mujoco.load,
num_iterations=1000000,
dim_z=None,
categorical=None,
actor_fc_layers=(2... | d301cabbc8b4c740c834497becbd90c918d775eb | 73,790 |
from typing import Union
from typing import Optional
from typing import Tuple
def fetch_schema_locations(source: Union['XMLResource', XMLSourceType],
locations: Optional[LocationsType] = None,
base_url: Optional[str] = None,
allow: str =... | b2557f7de7313317db5ba424ce0a830774f76246 | 73,791 |
import os
def setupCheckpoint(checkpoint_dir):
"""
Set up writing down checkpoints:
- Make checkpoint directory is it does not exist
- Find latest checkpoint
Parameter:
- checkpoint_dir -- Directory for writing down checkpoints
Returns:
"""
if not os.path.exists(checkpoint_dir):
... | 5a1518fb08688cba0f37ab7f18cab4a2c1cca4bd | 73,792 |
def readiob2(file, cols=('form', 'lemma', 'pos', 'att', 'gold_label', 'label', 'label/score')):
"""
Reads IOB2 file
"""
f = open(file)
sents = []
tmp = []
for line in f:
#print line
if line == "\n":
sents.append(tmp)
tmp = []
elif len(line.spli... | 69f38c5a8401450631c8a087ddc9c082577212c7 | 73,793 |
def split_train_val_partition(data,split_train_percentage, seed):
""" Partitions data into two partitions named tain and val
Args:
data (tuple): Containig two tensors one with the data samples and
the other with its correspondant labels
Returns:
... | 9c448f0f292cc32302e61f2c615d4e11475b1733 | 73,794 |
def add_polymarker(wks,plot,x,y,rlistc=None,isndc=0):
"""
Adds polymarkers to an existing plot and returns a PlotId representing
polymarkers added.
pmarker = Ngl.add_polymarker(wks, plot, x, y, res=None)
wks -- The identifier returned from calling Ngl.open_wks.
plot -- The id of the plot which you want to add the ... | a2c12ad7c148e0ad28eb94d8cb155e06998aa684 | 73,795 |
def delete(body, req):
"""Handles reqests and performs the delete on the Google Sheet"""
if req.query is not None or req.query['row_number'] is None:
raise Exception('Invalid request: missing query params.')
row_number = int(req.query['row_number'])
worksheet = get_sheet()
row = worksheet.r... | 1169ed55579e5a3b9975ba9b78f35daea250f061 | 73,796 |
import os
import shutil
import time
def _poll_server_till_success(max_attempts,
sleep_per_poll_sec,
debug_server_url,
dump_dir,
server,
gpu_memory_fraction=1.0):
"""P... | 7487bda868e72b80ccd93a1dcbb91ac401ad0628 | 73,797 |
def raw_einsum(
subscripts, *operands, keep_dims=frozenset(), out_append="{i}", einsum_kwargs=None, **kwargs
):
"""Wrap :func:`numpy.einsum` crudely.
Usage examples of all arguments is available at the
:ref:`einsum section <linalg_tutorial/einsum>` of the linear algebra module tutorial.
The descri... | b557b452618e2065b2a765edbf565e76a02b8265 | 73,798 |
def corr_coef(s_input: str) -> float:
"""
Used for parsing some inputs to this program, namely input correlation coefficients
:param s_input: String passed in by argparse
:return: Float value of correlation coefficient
"""
c = float(s_input)
if c < CORR_MIN_SCALING or c > CORR_MAX_SCALING... | 1d2da3fc29598348dfdc8be699af133b9e05314d | 73,799 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.