content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
import re
def parse_value(line,key_word):
"""finds value in line by parsing keyword"""
value = re.sub(key_word,'',line,1)
return value.strip() | eb093da1577f10f9f7a271985b62b35ff3bf906e | 69,477 |
def calc_pr(positive, proposal, ground):
"""
Calculate precision and recall
:param positive: number of positive proposals
:param proposal: number of all proposals
:param ground: number of ground truths
:return:
"""
if not proposal or not ground:
return 0, 0
return positive / ... | 277456d2c7c5d4352b925931342030663f1a541b | 69,478 |
def user_has_view_permission(user, page=None):
"""
This code largely duplicates Page.has_view_permission(). We do this because
the source method requires a request object, which isn't appropriate in
this case. Fortunately, the source method (and its dependencies) use the
request object only to get t... | 146b72878d023f8c76781eac855a000ff3f141ad | 69,479 |
def broadcast_shape(shape, comm=MPI.COMM_WORLD, root=0):
""" Broadcast shape to all processes
Parameters
----------
shape : int, tuple of int
Shape representation of numpy.ndarray object
comm : MPI Communicator, optional
MPI process communication object. If none specified
d... | 504624db0b8fb7e70e912262ef95d274c8d2f607 | 69,480 |
def noz3d(P, Y, y, m, c, o, plm):
"""
This is equivalent to Draper-Stoneman, as when there is no Z
Y remains unchanged.
"""
Mr = P @ plm.X[y][m][c][o]
return Mr, Y | b239bd250b79eee5c64eb10c0cff06ebf7ace458 | 69,481 |
import torch
from typing import Union
import math
import warnings
def get_kwta_threshold(tensor: torch.Tensor,
sparsity: Union[float, SparsityPredictor]):
"""
Returns the threshold for kWTA activation function as if input tensor is a linear (batch x embedding_dim).
:param tensor: (... | 8c32fde3bf655dd7e1af57b1b36fa0c81a18866f | 69,482 |
def merge_list(this, other, cb, comp=lambda o: type(o)):
"""
Merge two lists by their children's type,
for each given list, their children must be unique in type.
:param this:
:param other:
:param cb:
:param comp: a function to get children's type, defaults to type()
:return:
"""
... | e6d5a5c8082a7b622eb2b025b10788a49cf512ae | 69,483 |
def _preprocess_for_cut(x):
"""
handles preprocessing for cut where we convert passed
input to array, strip the index information and store it
seperately
"""
x_is_series = isinstance(x, Series)
series_index = None
name = None
if x_is_series:
series_index = x.index
na... | dfbb61122693e6e84a1280a16395b1df76782bfe | 69,486 |
def fetch_splice_motif_code(chrom, start_pos, end_pos, strand, genome):
""" Use Pyfasta to extract the splice motif sequence based on the start
and end of the splice junction. Then, convert this sequence motif
to a numeric code. """
start_motif = get_splice_seq(chrom, start_pos, 0, genome)
... | 4abe9c9f4c28573302426185337cd9fcfbe7e9cf | 69,487 |
import json
def read_template(client, template):
"""Read the template from a file or the stack object"""
if template.endswith(tuple(['.yaml', '.yml', '.json'])):
validate_template(client, template)
tmpl = read_file(template)
if template.endswith('.json'):
tmpl = json.dumps(... | 2e1db6ed135a9e7f5e5b470dcb5207d8289249f1 | 69,488 |
def largest_product(series: str, size: int) -> int:
"""Largest Series Product from strings
:param series: str: takes a series of digits
:param size: int: size of slices / groups / chunks
:returns: int: the largest product within groups of n size
"""
series_slices = slices(series, size)
ret... | 25055736741075d718eb78dfd75df3c6f564b233 | 69,490 |
import requests
def netbox_is_responsive(url):
"""Chack if the HTTP service is up and responsive."""
try:
response = requests.get(url)
if response.status_code == 200:
return True
except (
ConnectionError,
ConnectionResetError,
requests.exceptions.Connect... | cd71140a40f01c536b315790c4c1d581c67891e8 | 69,491 |
from typing import Any
import random
def getKeyByWeights(array: dict, item: int = 0) -> Any:
"""
Returns a weighted random key from array
:param array: dict[Any: int | float]
:param item: int
:return:
- key - Any
"""
return random.choices(list(array.keys()), weights=list(array.valu... | 8f1d474c97466407ff643abce1ea0b12b3ebd951 | 69,492 |
def get_partner_theme_list():
"""
grabbing MFI Partner and Loan Theme
"""
themes = Theme.query.filter_by(active=True).all()
partners = Partner.query.filter_by(active=True).all()
data = {'themes':[x.loan_theme for x in themes], 'partners':[x.partner_name for x in partners]}
return create_... | 921cf800040ee180974fce50096d99b381d7e30f | 69,493 |
def get_ymal_data(data):
"""Get metadata and validate them
:param data: metadata in yaml format
"""
try:
format_data = yaml.load(data)
except yaml.YAMLError, e:
msg = "Yaml format error: {}".format(
unicode(str(e), "utf-8")
)
logging.error(msg)
sy... | fbd11985090c77bb24f0434a10325548d235b161 | 69,494 |
def convert_base(arg, from_base, to_base):
"""
Convert number (as integer or string) from one base to another
Parameters
----------
arg : string or integer
from_base : integer
to_base : integer
Returns
-------
converted : string
"""
return _ops.BaseConvert(arg, from_bas... | 0a765a83734fa7e0574059eb961f357542de499b | 69,495 |
def sinhm(A):
"""
Compute the hyperbolic matrix sine.
This routine uses expm to compute the matrix exponentials.
Parameters
----------
A : (N, N) array_like
Input array.
Returns
-------
sinhm : (N, N) ndarray
Hyperbolic matrix sine of `A`
Examples
--------... | c4ccf9fcfab5982b9bd1bb41984b5763ce3adb22 | 69,496 |
import logging
def init_altimeter(configuration: Configuration):
"""Initialize the sensor for pressure, temperature, and altitude"""
try:
logging.info("Initializing altimeter")
assignments = configuration.get_pin_assignments("bmp3xx")
if not assignments:
return None
... | 004eb7c41bf133cd8b0e74c2f53218510f98829c | 69,497 |
def create_learning_rate(hparams, global_step):
"""Creates a learning rate Tensor.
Args:
hparams: ConfigDict containing the learning rate configuration.
global_step: The global step Tensor.
Returns:
A learning rate Tensor.
"""
if hparams.get("learning_rate_decay_factor"):
learning_rate = tf.... | d12fbfd5f13be8a9c8479a791bfd6b4cd2e1d712 | 69,499 |
import tqdm
def eval_clustering(X, Xdist_dict, Y_true, cluster_type, params, target_metric='silhouette'):
"""
Evaluate a single clustering configuration (algorithm + hyperparameters).
@param X: feature matrix (scipy.sparse.csr_matrix, (n_reports x n_features))
@param Xdist_dict: dict of distance matri... | 96cc57b589c0ce7fb7dc2bcb394ccb136c13dda8 | 69,500 |
import random
def generate_random_fp_value(precision, inf, sup):
""" Generate a random floating-point value of format precision """
assert isinstance(precision, ML_FP_Format)
value = random.uniform(0.5, 1.0) * S2**random.randrange(precision.get_emin_normal(), 1) * (sup - inf) + inf
rounded_value = pre... | afc7ea0cfc449b8e5bcb2cd216e6d136746b2c2b | 69,501 |
from typing import Optional
from typing import List
def _parse_args_schema(query_args: Optional[List[ArgDef]]):
"""
Parse query args schema
"""
parameters = []
for query_arg in (query_args or []):
arg_name = _arg_name(query_arg)
arg_type, arg_format, arg_req = _arg_type(query_arg)
... | 0c184dae1fa68d21b551c3701cecb09d63907089 | 69,502 |
def check_bee_nectar_eq_hive_nectar(landed_bees, game):
""" Check the sum of all the nectar in the hives equals the sum of the nectar
carried by bees that have landed
returns: True if they are same
"""
hive_nectar = sum(sum(hive.nectar for hive in board.hives) for board in game.boards)
l... | 86f8045c5639ca73edad7273e58bbc5fbf112220 | 69,503 |
def encrypt(plaintext, key):
"""
:param plaintext: string
:param key: int
:return:
"""
ciphertext = ""
for char in plaintext:
oNum = ord(char)
if oNum > 127: # not a ASCII character
new_char = char
else:
if(oNum + key > 127): # If value is t... | 855e941e73cf15b00d3c2fa94eefaaf3c3ad31a4 | 69,504 |
def as_index(keys, axis=semantics.axis_default, base=False, stable=True, lex_as_struct=False):
"""
casting rules for a keys object to an index object
the preferred semantics is that keys is a sequence of key objects,
except when keys is an instance of tuple,
in which case the zipped elements of the... | a3f1151d165bb05ff6f190744aad1b7570ddb7ba | 69,505 |
def series2shp(series, filepath):
"""Writes a ``pandas.Series`` of PySAL polygons to a file
Parameters
----------
series : pandas.Series
The data to write out.
Returns
-------
filepath : str
Path to the file.
"""
f = ps_open(filepath, "w")
for pol... | c8060881433d4f8dae107adab9df3f3233705468 | 69,506 |
def unit_format_suffix_handle_exc(value, suffix, precision=2):
"""Print a given value but handle None and exceptions during processing."""
if value is None:
# TRANSLATORS: do not translate {unit}; "None" is equivalent to "Not Applicable" or "No Value"
return _("[None] {unit}").format(unit=suffi... | 6cebcd18298594e1b0eb46005f18456518635537 | 69,507 |
def PrePlot(num=None, rows=None, cols=None):
"""Takes hints about what's coming.
num: number of lines that will be plotted
rows: number of rows of subplots
cols: number of columns of subplots
"""
if num:
_Brewer.InitIter(num)
if rows is None and cols is None:
return
if... | 680839d139813c4d0b74050997465cb6f75b9678 | 69,508 |
def index(request):
"""
show index page
:param :
:return:
:rtype:
"""
return render_to_response('index.html') | 3d55b0f308bb94158f5f38cd1a86ee1b9c377bfa | 69,510 |
import re
def sequence_objects(module: ModuleType, items: BindingSeq) -> BindingSeq:
"""
:param module: The module to extract callable definitions from.
:type module: ModuleType
:param items: The callables and bindings for extraction.
:type items: Iterator[Tuple[str, object]]
:returns: a list ... | 0dbf096b262046493ebbe5d03a59baa7e4d78557 | 69,511 |
def selection_probs(utilities, market_share):
"""Customer selection probability for all products and 'do not fly'
Parameters
----------
utilities: dict
Utilities of products based on choice model parameters
market_share: float
Host's market share
Returns
-------
tuple
... | b4f994b421ff97aeee90808358436590a1feb43e | 69,512 |
def remove_pc(X, npc=1):
"""
Remove the projection on the principal components
:param X: X[i,:] is a data point
:param npc: number of principal components to remove
:return: XX[i, :] is the data point after removing its projection
"""
pc = compute_pc(X, npc)
if npc == 1:
XX = X -... | 6b1a369904580dd881c5d4dba7753328b6e8168e | 69,513 |
def zeros(shape,name=None):
"""
zeros tensors
"""
initial = tf.zeros(shape,dtype=tf.float32)
return tf.compat.v1.Variable(initial) | f291ae0dd8c5afe2115bcf54c92b224b8355761f | 69,514 |
def solucion_c(imc: float) -> str:
"""Devuelve una categoría de acuerdo al imc
:param imc: Índice de masa corporal
:imc type: float
:return: Categoría
:rtype: str
"""
categorias = {
imc < 16 : "criterio de ingreso hospitalario",
16 <= imc < 17 : "infrapeso",
17... | ca05b9b7af9df3237e8aa1170638e7e695e6bcad | 69,515 |
import re, string
def clean_text(orig_text,verbose=False):
"""Prepare for NLP by removing problematic characters.
Adapted from code kindly provided by Dr. Brian Powell at WVU.
"""
if verbose: print("ORIGINAL")
if verbose: print(orig_text)
if verbose: print("REMOVE URLS")
clean_text = re.s... | 1ac8b6baff72fc72db748a699975da818781f215 | 69,516 |
def melscale(f):
""" Converts f (in Hertz) to the melscale defined according to Huang-Acero-Hon (2.6) """
return 1125.0 * np.log(1 + f / 700.0) | 996870454615e71fbb2d7cac0b4142c878b7d452 | 69,517 |
from typing import Optional
def default_shape_importer(_: ShExJ.IRIREF, cntxt: "Context") -> Optional[ShExJ.Schema]:
""" Resolve an import declaration """
return None | 079882761b928ad3ad06419892ad9d979cc5e678 | 69,518 |
def make_jitter_plots(data, names, ylabel, dx=0.1, offset=0.0,
xlabels=None, ax_handle=None, alpha=1, color=None,
marker=None, markersize=12, return_plot_pointer=False):
"""
Make a jitter plot of columns from a pandas dataframe
Parameters
----------
data:... | 3efe6c530dacbedd583f62d4104c2d5f43b15098 | 69,519 |
def gen_split_idx(num_all, num_train, num_val, num_test, seed=1234):
"""Generate train/val/test split indices
Args:
num_all: total number of data
num_train: number of training data
num_val: number of validation data
num_test: number of testing data
seed: seed of random number generator
Retu... | aa33ff25a0eaa20091035f4ee1597c2971e4aa81 | 69,520 |
import numpy
from typing import Mapping
from typing import Iterator
def _get_redundant_cluster_cnv_cpx_vids(
cluster: numpy.ndarray,
is_carrier: Mapping[Text, numpy.ndarray],
cnv_cpx_sample_overlap: float
) -> Iterator[Text]:
"""
Find CNVs that are redundant with CPX events
for eac... | 421008b9c648a985fa7d573b0b9565eebb627292 | 69,521 |
def link_menus(*menu_items):
"""
Links a list of menu items into a loop of menu items
:param menu_items:
:return: the first menu item
"""
def link(a, b):
a[NEXT] = b
b[PREV] = a
prev = menu_items[-1]
for menu_item in menu_items:
link(prev, menu_item)
prev... | 57342c8f458ffe186c59b365375e73a65273ee6d | 69,522 |
import math
import random
def solve(simulation_api: SimulationAPI, reward_threshold: float, timeout_s: float = 60, num_hof=1):
"""
Run a genetic algorithm on the current simulation_control scenario until reward exceeds the threshold or timeout is reached
"""
# need to have a reward function, and to im... | fcd7f40127fa77fb91566f3eeadae61a3152b599 | 69,523 |
import binascii
def des_descrypt(s):
"""
DES 解密
:param s: 加密后的字符串,16进制
:return: 解密后的字符串
"""
secret_key = KEY
iv = secret_key
k = des(secret_key, CBC, iv, pad=None, padmode=PAD_PKCS5)
de = k.decrypt(binascii.a2b_hex(s), padmode=PAD_PKCS5)
sessionID = de.split('_')
openid = ... | 449976440bbabdedd80028fe1434cf478ad3fbf0 | 69,524 |
def splitter(model):
"""
Splits model parameters into multiple groups to allow fine-tuning
"""
params = list(model.parameters())
return [
# weights and biases of the first linear layer
params[:2],
# weights and biases of the second linear layer
params[2:],
] | 2ac16b536bd50884c50ade3fb67f6ca43a16799d | 69,525 |
def render_static(request, template):
"""
Takes an html file and renders it Commcare HQ's styling
"""
return render(request, "hqwebapp/blank.html", {'tmpl': template}) | 1b629d0b9186b23b6b5aefa9b78cc9235171767b | 69,527 |
def read_fits_header(filename, **kwargs):
""" Read the FITS header for a given filename.
Args:
filename (str): The filename.
**kwargs: Parsed to fits.getheader.
Returns:
astropy.header.Header: The header object.
"""
return fits.getheader(filename, **kwargs) | 0b8401817d169ca0cff198dedd05abfd2065e2e7 | 69,529 |
from typing import Dict
from typing import Any
from typing import Optional
import math
def sequential_colors(
node_and_value: Dict[Any, float],
light_background: bool = True,
use_log_scale: bool = False,
theme_path: Optional[str] = None,
) -> Dict[Any, str]:
"""
Generates a node -> color mappi... | e25133ee1fe761618748a48664675e7556573cb8 | 69,530 |
def dup_normal(f, K):
"""
Normalize univariate polynomial in the given domain.
Examples
========
>>> from sympy.polys.domains import ZZ
>>> from sympy.polys.densebasic import dup_normal
>>> dup_normal([0, 1.5, 2, 3], ZZ)
[1, 2, 3]
"""
return dup_strip([ K.normal(c) for c in f... | ba67c492e3a2cbf7844aa3aede4b5fef775b0a91 | 69,532 |
def create_c3nn_classifier(ninput=100, nfilters=32, kernel_size=4, ndense=128, pool_size=2, dropout_rate=0.2,
noutput=1, pooling=False):
""" An easy way of creating a CNN with 3 convolutional layers and 2 dense layers
Parameters
----------
ninput:
input shape
nfil... | 04f37c440951b0671f3cb0f219c8d1fcad391e5f | 69,533 |
def get_setup_fabric_dirs_string():
"""
Returns the commands required to set up the fabric directories. This is not in the env, because modifying this
is likely to break FabSim in most cases.
This is stored in an individual function, so that the string can be appended in existing commands, reducing
... | a73f3da5b7c20c588f71320f0089066ce54bf93e | 69,535 |
def _fit_shift(
Z, y, f, f_s, w, max_shift, periodic, n_iter, init_shift, Ww):
"""
Z : matrix, M x T
y : float
f : vector, length M
f_s : vector, length M
w : vector, length T
"""
M, T = Z.shape
best_loss = np.inf
best_shift = 0.0
for i in range(n_iter):
... | 79eba28f490c3aecd77befba19714b4990f79731 | 69,536 |
from datetime import datetime
def to_timedelta(src, cal=None, is_duration=False):
"""
converts a string to a datetime.timedelta. If cal is specified
it will be used for getting the working times. if is_duration=True
working times will not be considered. Valid units are
d for Days
w for Weeks
... | 01bcbad90d1f5335a6620b93d4eb24eac890f916 | 69,537 |
def Dust(C, **kwargs):
"""
SulfurDioxide RGB:
(See `Quick Guide <http://rammb.cira.colostate.edu/training/visit/quick_guides/Dust_RGB_Quick_Guide.pdf>`__ for reference)
.. image:: /_static/Dust.png
Parameters
----------
C : xarray.Dataset
A GOES ABI multichannel file opened with xa... | 4e36f4b2f66d9caf361e8d6208225367262b219b | 69,538 |
def slant_stack_frequency(traces, dx, cmax, fmax):
"""
Slant stack method after McMechan and Yedlin 1981
"""
nr = len(traces)
dt = traces[0].stats.delta
nt = traces[0].stats.npts
t = np.linspace(0.0, nt*dt, nt)
traces.detrend()
traces.taper(0.05,type='hann')
U, f = get_fft(trace... | 42310963e0244c72287cf3e8909e6f088fb668de | 69,539 |
from typing import List
import random
def algo_chao(s: List, k: int) -> List:
"""Chao weighted random sampling
"""
n = len(s)
assert len(s) >= k
wsum = 0
r = s[:k]
assert len(r) == k
for i in range(0, n):
wsum = wsum + s[i]["priority"]
if i < k:
continue
... | 788007e08129c79c49128874be4da64b21cbff22 | 69,540 |
def get_arch(os_list):
"""
根据os_list判断需要下载哪些架构的包
"""
arm, x86 = 0, 0
for os_item in os_list:
if not arm and "aarch64" in os_item:
arm = 1
if not x86 and "x86_64" in os_item:
x86 = 1
if arm and x86:
break
if arm and not x86:
arc... | 1522db842d971a30fb54c05919f98da83aaf1d0a | 69,541 |
def getOptions():
"""Generates arguments for specifying database and other parameters"""
options = {}
options['lexical_kb'] = ["https://raw.githubusercontent.com/chapmanbe/pyConTextNLP/master/KB/lexical_kb_05042016.tsv"]
options['domain_kb'] = ["https://raw.githubusercontent.com/chapmanbe/pyConTextNLP/m... | ecd193161645419b241679b2496f76d26e0468fd | 69,542 |
def get_protein_coding_read_count(pcgenes, count_file):
"""
Extract the counts of fragments mapped to protein coding genes.
:param pcgenes: set of protein coding gene IDs
:param count_file: HTSeq count file
:returns: number of fragments on protein coding genes
:returns: dictionary of gene ids a... | d2ce448472a4c6773d69bad260b9088558ddb1d5 | 69,543 |
def checkIPIsValid(ip):
"""
Method used to check a selected IP is possible to use with a Qt's QHostAddress.
The IP can be either IPv4 address or *"localhost"* string with possible capital
letters anywhere. IPv6 is not supported for now.
Args:
ip: A str with an IP address selected.
"""
if ip.upper() ==... | 8b3f0a5f7ae079a0461d45efcafd0f8ce3e859ce | 69,544 |
import urllib
def graphql(obj,query_ids=None):
""" access to /graphq/query/ """
if not type(obj) is dict:
raise TypeError("Expecting dict type variable")
if type(query_ids) is list:
query_ids="\n".join(query_ids)
if query_ids is None:
f=open("query_id",'r')
query_ids=f.read()
f.close()
args = urlli... | 7fdd37e82bbb015928e7bbca6cb18b61297c9a73 | 69,545 |
def tile_pauli_fidpairs(base_fidpairs, nQubits, maxweight):
"""
Tiles a set of base fiducial pairs on `maxweight` qubits to a
set of fiducial pairs on `nQubits` qubits such that every set
of `maxweight` qubits takes on the values in each base pair in
at least one of the returned pairs.
Paramete... | e3e62678287adfa522d287022d13334a76bde820 | 69,546 |
def gen_color_dict(bundles):
"""
Helper function.
Generate a color dict given a list of bundles.
"""
def incr_color_idx(color_idx):
return (color_idx + 1) % 20
custom_color_dict = {}
color_idx = 0
for bundle in bundles:
if bundle not in custom_color_dict.keys():
... | 74ad30fc71a4316de4aa91f68eee7a1fb0029ba2 | 69,547 |
def simulation_step(x, dt, rates):
"""
Returns the boolean vector x(t+dt) from x(t). Time unit is day, rates are per day and per nucleotide.
Rates is a dict containing keys ["consensus", "non_consensus"].
rates["consensus"] and rates["non_consensus"] are dict containing the rates for the keys ["first", ... | 658e9e71e5451c3b759539d9e0c27becdc0d9ffd | 69,548 |
def _read_md5_sum_file(path):
""" Reads a MD5 checksum file and returns hashes as a dictionary.
"""
with open(path, "r") as f:
hashes = {}
while True:
line = f.readline()
if not line:
break
h, name = line.rstrip().split(' ', 1)
... | 5f5cfce0f8774baf17041a05b017ba9967d43267 | 69,549 |
def get_data_2g(args, infoMiss=None):
"""
Generate synthetic data with 2 groups.
Parameters
----------
args : local namespace
Arguments selected to run the model.
infoMiss : dict | None, optional.
Parameters to generate data with missing values.
Returns
-------
... | 9b5d875612f09706b37f1c7e87ff83db9ef06398 | 69,550 |
from typing import List
def device_types() -> List[xcrun.simctl.device_type.DeviceType]:
"""Return all available device types."""
device_type_info = _list(xcrun.simctl.SimulatorControlType.device_type.list_key())
return xcrun.simctl.device_type.from_xcrun_info(device_type_info) | cac646e85aad4ba3c78ce245dae7129c029946a8 | 69,551 |
def process_sample_data(sample_data, config):
"""
sample_data is a top level config map that has two types of entries
- samples: keyed on sample name and containing paths and other data
- 'reads_patterns': list of patterns to find samples. These are passed to
collect_sample_reads() below
... | e27a0a376c6cc91bbc88ccfa6aa0b77fa04f503c | 69,552 |
from typing import Sequence
def to_dot(*models: type, termini: Sequence[type] = []) -> str:
"""Generate Graphviz [DOT language](https://graphviz.org/doc/info/lang.html) representation of
entity relationship diagram for given data model classes.
Args:
*models (type): Data model classes to diagram.... | 9fd5eeb6c9abb5f34115f2362c2ebabdcdca7443 | 69,553 |
def _GetValue(parent_element):
"""Get the text nested inside an XML element's value element.
Args:
parent_element: An ElementTree element
Returns:
String inside value tag inside parent or, if no such tag can be found, None
"""
if parent_element is not None:
value_element = parent_element.find(_D... | 20e4c2f1cef7ecba4055d533459dd8c83d348e7e | 69,554 |
def abs_area(x):
"""Calculate the area under the absolute values of the given points.
The integral is done using the trapezoid rule.
Parameters
----------
x : ndarray
The input points to use for the calculationss
Returns
-------
abs_area : float
The absolute area u... | 2dacea58c9217d2091b72a451f826d060c7165e6 | 69,558 |
def feature_count_near(INPUT, cloud, clust_centers):
"""Compute the "count-near" feature.
For each cluster, the number of landmarks within a neighborhood radius
arround them is counted. The neighborhood radius is defined as the mean of
all distances computed in `feature_distEuclidean_kNN`.
Paramet... | 96e8a5e5dc14298a3f35f958b851c1cda1026a68 | 69,559 |
import math
def make_bonds(pdb1):
""" create bonded list based on overlap of vdw radii """
margin = 1.3
bond_list = []
nbond = 0
for i in range(pdb1.natom):
for j in range(i+1,pdb1.natom):
dist2 = 0.
for k in range(3):
dist2 += (pdb1.coords[i][k] - pdb1.coords[j][k])**2
dist = ... | 4ca098e15f912c7d7658562992c502c2271cc1bd | 69,560 |
def _decode_csv(line):
"""Takes the string input tensor and returns a dict of rank-2 tensors."""
# Takes a rank-1 tensor and converts it into rank-2 tensor
row_columns = tf.expand_dims(line, -1)
columns = tf.decode_csv(row_columns, record_defaults=CSV_COLUMN_DEFAULTS)
features = dict(zip(CSV_COLUMN... | 4bd8c2731f1f2f13ff8d797d56c6aea78254afcd | 69,561 |
def impz(b, a=1, FS=1, N=1, step=False):
"""
Calculate impulse response of a discrete time filter, specified by
numerator coefficients b and denominator coefficients a of the system
function H(z).
When only b is given, the impulse response of the transversal (FIR)
filter specified by b is c... | 994142a203e017d5ba3fbe6cbc4535420b4fa61e | 69,562 |
async def present(
hub,
ctx,
name,
resource_group,
virtual_network,
ip_configurations,
gateway_type=None,
vpn_type=None,
sku=None,
enable_bgp=None,
active_active=None,
bgp_settings=None,
address_prefixes=None,
tags=None,
connection_auth=None,
**kwargs,
):
... | 2cc3d4f60d7032af6e945e2861be133a3aecd40c | 69,563 |
def get(identifier: str) -> 'BaseRenderer':
"""Gets the `BaseRenderer` that matches the identifier.
Parameters
----------
identifier : str
The identifier for the `BaseRenderer`
Returns
-------
`BaseRenderer`
The renderer associated with the `identifier`.
Raises
---... | 99e220b878ff381c5a1478cf91e7536b22f8520f | 69,564 |
import torch
def stratified_sum_pooling(values: torch.Tensor,
labels: torch.LongTensor) -> (torch.Tensor):
"""Group-wise sum."""
winning_values = stratify_with(
values,
labels,
fn=lambda x: torch.sum(x, dim=1, keepdim=True).squeeze(),
fill_value=0.0)
... | fdd3b62f8bb8942882338f11e62e88d1f0dcf0f1 | 69,566 |
def is_wl():
"""Whether the model point is whole life
``True`` if the model point is whole life, ``False`` if other wise.
By default, the value is read from the ``is_wl`` column
in :func:`model_point`.
This attribute is used to determin :func:`policy_term`.
If ``True``, :func:`policy_term` is d... | 4eb618afdfd063f61c1d3a2322b2ca91aea36a71 | 69,567 |
from typing import List
from typing import Any
def klue_ner_char_macro_f1(preds: np.ndarray, labels: np.ndarray, label_list: List[str]) -> Any:
"""KLUE-NER character level macro f1 (except O tag)"""
label_indices = list(range(len(label_list)))
preds = np.array(preds).flatten().tolist()
trues = np.arra... | 049c90957517962a442edaa5ab6804aa03856c6e | 69,569 |
def parse_id(text):
""" Parse and return the <job>:<id> string.
Args:
text String to parse
Returns:
This node's job name, this node's id
"""
sep = text.rfind(":")
if sep < -1:
raise ValueError("Invalid ID format")
nid = int(text[sep + 1:])
if nid < 0:
raise ValueError("Expected non-negat... | 23dbc417abf7fb799da78e63acf18b2d0ffc450f | 69,574 |
def reconstruct_grid_volume(grid, n_block=(4, 4, 4)):
"""
Reconstruct the warped grid volume with its blocks.
:param grid: A dictionary of grid blocks, with the key (i, j, k) referring to the block indices, the values are of
shape [n_batch, nx_block, ny_block, nz_block, 3].
:param n_block: The ... | 916bee093a26d9d16b12ca135aa7e8596997a8fb | 69,575 |
import glob
def spncci_slurp (directory):
"""
Arguments:
directory (string): Location of the SpNCCI results files.
Should be of the form '/location/of/files/*.res'
Returned:
data (nested dictionary): Maps from (Nmax, Nsigmamax) to hw to
SpNCC... | 6f9c0d3c4dfd0f231f943d16813855fb19e28a6a | 69,577 |
import copy
def pyramidal_solve_kt(slice3d,\
slice3d_orig,\
slice3d_shape,\
weights_list,\
factors,\
rp):
"""Solves a k-t slice: dim0=receivers,dim1=kx,dim2=t
"""
#init
lmafit_tol_list = vj.config['lma... | 7c36f3b42c93813a849dc2a7cb56257ea516a2e0 | 69,578 |
def read_DF_from_path(resultFile):
"""Read daylight factor values from a radiance .res result file."""
result = []
resultFile = open(resultFile, "r")
for line in resultFile:
res = float(line)
if res > 100:
res = 100
result.append(res)
return result | 583ec1892d26038fdd43d9acf152a9b7c65dc364 | 69,579 |
def get_real_sms_messages_data(domains, datespan, interval,
datefield='date', is_commtrack=False, additional_params_es={}):
"""
Returns SMS sent in timespan.
Returned based on date SMS was sent
"""
sms_after_date = (SMSES()
.domain(domains)
.received(gte=datespan.star... | ee27034e9f31d0804ac6243dc9f93c913a10917e | 69,580 |
def _get_target_directory(yaml_path):
"""Get target directory to copy appengine yaml to."""
return SRC_DIR_GO if _is_go_yaml(yaml_path) else SRC_DIR_PY | 62c8a6b5caccca8855409400332de3c9dca41b09 | 69,581 |
def directories(name, dirs, **kwargs):
"""
type dir {
path string [required]
user string
group string
mode string
}
type dirs []dir
"""
results = {"name": name, "result": False, "changes": {}, "comment": []}
for d in dirs:
# path is require... | c610e97fd58755bd9cd21cc6962028ddc726fd1d | 69,583 |
def add_metpy_logo(fig, x=10, y=25, zorder=100, size='small', **kwargs):
"""Add the MetPy logo to a figure.
Adds an image of the MetPy logo to the figure.
Parameters
----------
fig : `matplotlib.figure`
The `figure` instance used for plotting
x : int
x position padding in pixels
... | 49e87a6d64d257614e0370b27dca9283470d90c7 | 69,584 |
import configparser
def process_config(conf_file):
"""
read configuration from files and saved to a dict
"""
params = {}
config = configparser.ConfigParser()
config.read(conf_file)
for section in config.sections():
if section == 'database':
for option in config.options(section):
params[option] = eval... | 204077bbade5203267a6719d9fb559ef5f0ee126 | 69,585 |
async def handle_stream_changed_get(request: request.Request):
"""Route receiving the challenge requests for the topic StreamChanged
Parameters
----------
request: sanic.request.Request
The challenge request received from Twitch
"""
return dispatcher().accept_subscription(request, Topic... | 6c5cab4578e64a35b60fb80cdf14453229b15701 | 69,586 |
def parse_phone_number(phone_number):
"""Parse phone number.
Args:
phone_number (str): Phone number. ie. 050xxxxxxx
Returns:
str: E164 formatted phone number. ie. +23350xxxxxxx
Raises:
InvalidPhoneNumberError: If `phone_number` is not successfully
parsed as a local... | 3359322dff4645b50b6da6e5490d127340f8da34 | 69,587 |
def getRootHelp():
"""帮助文档"""
max_l = 0
for a in action_names:
if len(a[0]) > max_l:
max_l = len(a[0])
max_l += 4
msg_help = "<pre>API Version " + config['version']
msg_help += "\n\nSupport Functions:\n\t" + "\n\t".join([a[0]+(" "*(max_l-len(a[0])))+a[1] for a in action_name... | 3e363adc65b6f5c9d91e7ec12df6021b302ba17d | 69,588 |
def cutout_image(image, offsetx, offsety, size, output_size=224):
"""Computes (square) cutouts of an image given x and y offsets and size."""
(c, h, w) = image.shape
scale = jnp.stack([output_size / size, output_size / size])
translation = jnp.stack([-offsety * output_size / size, -offsetx * output_siz... | f82d10299e9a9580bbddf5e3fc213d48d1188df7 | 69,589 |
def path_to_import(path):
"""Convert a path to import."""
if path.name == '__init__.py':
import_path = str(path.parent)
else:
import_path = str(path)[:-len(PY_EXTENSION)]
return import_path.replace('/', '.') | 780f345a0fbbfdc6df5cc4916253c0e7acb1f736 | 69,590 |
def unexpected(parser, at_token=None):
"""Helper function for creating an error when an unexpected lexed token
is encountered."""
token = at_token or parser.token
return LanguageError(
parser.source,
token.start,
u'Unexpected {}'.format(get_token_desc(token))
) | c450aa592f63a84171294c19fdf1ac43245a760a | 69,591 |
from typing import Sequence
from typing import Mapping
from typing import Any
from typing import Optional
import functools
import collections
def transcription_metrics(
targets: Sequence[Mapping[str, Any]],
predictions: Sequence[Mapping[str, Any]],
codec: event_codec.Codec,
spectrogram_config: spectro... | 33ad1c21c4a6b5119dd1ef1127d248be4fd2d3f1 | 69,592 |
def resnet50_learning_rate_schedule(base_learning_rate, steps_per_epoch):
"""Creates a piecewise LR schedule for the common ResNet-50 ImageNet setup."""
boundaries = [
int(40 * steps_per_epoch),
int(60 * steps_per_epoch),
int(80 * steps_per_epoch),
int(90 * steps_per_epoch),
]
values = [... | f74a148be20452643fad4a938d106ccb14bf1f21 | 69,593 |
import torch
def setdiff(A, B):
"""
Returns the set difference tensor with all the elements in A not belonging to B
Parameters
----------
A : Tensor
the first input tensor
B : Tensor
the second input tensor
Returns
-------
Tensor
the set difference tensor
... | a2f16aaf74a0f74c56b897989ac86074998b5569 | 69,594 |
def is_empty(text: str) -> bool:
"""Determine if XML string is empty.
The XML string is considered empty if it only contains processing
instructions and comments.
:param text:
XML text to check for being empty.
:return:
True if the given XML `text` is empty.
"""
return (
... | 251a8a09c69a84f7574573211c8eb8ae4a0a53df | 69,595 |
def vectorise_data(raw):
"""Converts a list of [x,y,z] data to Vector(x,y,z)"""
temp = []
for vert in raw:
temp.append(Vector(vert[0], vert[1], vert[2]))
return temp | 77eabee827d8e5c820b4b4edf4b53167b3d6671f | 69,596 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.