content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def weighted_moments(values, weights):
"""Return weighted mean and weighted standard deviation of a sequence"""
w_mean = np.average(values, weights=weights)
sq_err = (values - w_mean)**2
w_var = np.average(sq_err, weights=weights)
w_std = np.sqrt(w_var)
return w_mean, w_std | 84775550c54f285f9a032641cf27976eebf94322 | 6,400 |
def forestplot(data, kind='forestplot', model_names=None, var_names=None, combined=False,
credible_interval=0.95, quartiles=True, r_hat=True, n_eff=True, colors='cycle',
textsize=None, linewidth=None, markersize=None, joyplot_alpha=None,
joyplot_overlap=2, figsize=None):
... | e2170c4bdbfc2fbf5c3db24688e8ab09a2ec498c | 6,401 |
def tf_dtype(dtype):
"""Translates dtype specifications in configurations to tensorflow data types.
Args:
dtype: String describing a numerical type (e.g. 'float'), numpy data type,
or numerical type primitive.
Returns: TensorFlow data type
"""
if dtype == 'float... | 0c51804974e7e1bb36fcc32f181cfab713fca263 | 6,404 |
from typing import Tuple
import timeit
def decode_frame(raw_frame: bytes, frame_width: int, frame_height: int) -> Tuple[str, np.ndarray]:
"""
Decode the image bytes into string compatible with OpenCV
:param raw_frame: frame data in bytes
:param frame_width width of the frame, obtained from Kinesis pay... | a38d7362997701756767cf466bb3fbb76b77a92e | 6,405 |
def preprocess(picPath):
"""preprocess"""
#read img
bgr_img = cv.imread(picPath)
#get img shape
orig_shape = bgr_img.shape[:2]
#resize img
img = cv.resize(bgr_img, (MODEL_WIDTH, MODEL_HEIGHT)).astype(np.int8)
# save memory C_CONTIGUOUS mode
if not img.flags['C_CONTIGUOUS']:
i... | ae44fdbf3613e159f28db0d9417470872439f76d | 6,406 |
import requests
def live_fractal_or_skip():
"""
Ensure Fractal live connection can be made
First looks for a local staging server, then tries QCArchive.
"""
try:
return FractalClient("localhost:7777", verify=False)
except (requests.exceptions.ConnectionError, ConnectionRefusedError):
... | b121e33a2294edc80d336abbb07c9a12f3301aea | 6,407 |
def get_legendre(theta, keys):
"""
Calculate Schmidt semi-normalized associated Legendre functions
Calculations based on recursive algorithm found in "Spacecraft Attitude Determination and Control" by James Richard Wertz
Parameters
----------
theta : array
Array of colatitudes in ... | 8afd34e7e4805fab9393c2efff15c0cffcb9466a | 6,408 |
def table_4_28(x_t, c_):
"""
Вывод поправочного коэффициента, учитывающего влияние толщины профиля
arguments: относительное положение точки перехода ламинарного пограничного слоя в турбулентный (Х_т_),
относительная толщина профиля
return: Значение поправочного коэффициента"""
nu_t_00 = [1.00, ... | 954c272bde503363f354b33f6af4f97bee5ad740 | 6,409 |
def random_spectra(path_length, coeffs, min_wavelength, max_wavelength, complexity):
"""
"""
solution = random_solution(coeffs, complexity)
return beers_law(solution, path_length, coeffs, min_wavelength, max_wavelength) | a82a0d638473d63cd768bfdc0318f5042a75ae12 | 6,410 |
def data_prep(data,unit_identifier,time_identifier,matching_period,treat_unit,control_units,outcome_variable,
predictor_variables, normalize=False):
"""
Prepares the data by normalizing X for section 3.3. in order to replicate Becker and Klößner (2017)
"""
X = data.loc[data[time_ident... | 6f13cc083973d5bd7ac7d2ca239741aaf067fede | 6,411 |
import numpy
def kabsch_superpose(P, Q): # P,Q: vstack'ed matrix
"""
Usage:
P = numpy.vstack([a2, b2, c2])
Q = numpy.vstack([a1, b1, c1])
m = kabsch_superpose(P, Q)
newP = numpy.dot(m, P)
"""
A = numpy.dot(numpy.transpose(P), Q)
U, s, V = numpy.linalg.svd(A)
tmp = numpy.identi... | 56b7b9c3168e644ad71bee2146af3e4ae455c648 | 6,413 |
def add(a_t, b_t):
"""
add operator a+b
"""
return add_op(a_t, b_t) | be4e5bad6deb651af8e8f084cbefd185c1f9781f | 6,414 |
def GetExtensionDescriptor(full_extension_name):
"""Searches for extension descriptor given a full field name."""
return _pool.FindExtensionByName(full_extension_name) | 5e0088f785809e38d306d7416129114ac09a5135 | 6,416 |
from operator import sub
def parse_args():
"""
Parses command-line arguments and returns username, title of specified
repository and its' branch.
Returns: tuple (username, repo_name, branch).
Used only once in `main` method.
"""
DESC = 'Automatic license detection of a Github repository.'
... | f7bf4b0cc27a87add8f65f82bebbabb6a4b9ca06 | 6,418 |
import itertools
def collect_inventory_values(dataset, inventory_list, parameter_map):
"""
Collect inventories from a dataset.
"""
# Collect raw/unicode/clts for all relevant inventories
to_collect = []
for catalog in inventory_list.keys():
to_collect += list(
itertools.ch... | 1c59e0784b6fc4db24f994440990e46a0ba2b1f0 | 6,420 |
def flatten_list(a_list, parent_list=None):
"""Given a list/tuple as entry point, return a flattened list version.
EG:
>>> flatten_list([1, 2, [3, 4]])
[1, 2, 3, 4]
NB: The kwargs are only for internal use of the function and should not be
used by the caller.
"""
if parent_list... | dd6c9c66a370e65744ede40dfdc295b0ec63379a | 6,423 |
from typing import List
def list_to_csv_str(input_list: List) -> Text:
"""
Concatenates the elements of the list, joining them by ",".
Parameters
----------
input_list : list
List with elements to be joined.
Returns
-------
str
Returns a string, resulting from concate... | 4c172b0ce3daba01f2d976bc60739846b852c459 | 6,424 |
def scheme_listp(x):
"""Return whether x is a well-formed list. Assumes no cycles."""
while x is not nil:
if not isinstance(x, Pair):
return False
x = x.second
return True | e5001695035d2d24e2914295e8ae2f86d8ead0b3 | 6,425 |
def list_to_dict(config):
"""
Convert list based beacon configuration
into a dictionary.
"""
_config = {}
list(map(_config.update, config))
return _config | 3d7ace7612e67a0c406a2a400ad3147f99dbef0a | 6,426 |
def get_model(model_name, in_channels = 3, input_size = 224, num_classes = 1000):
"""Get model
Args :
--model_name: model's name
--in_channels: default is 3
--input_size: default is 224
--num_classes: default is 1000 for ImageNet
return :
--model: model instance
"... | 0380a19e2a063382920b7986d1087aaf70f05eda | 6,427 |
def check_edge_heights(
stack, shifts, height_resistance, shift_lines, height_arr, MIN_H, MAX_H,
RESOLUTION
):
"""
Check all edges and output an array indicating which ones are
0 - okay at minimum pylon height, 2 - forbidden, 1 - to be computed
NOTE: function not used here! only for test purpose... | f73c6fd0396967e2a5ecfa89d52f1468d2005967 | 6,428 |
def linear_int_ext(data_pts, p, scale=None, allow_extrap=False):
"""
Interpolate data points to find remaining unknown values absent from
`p` with optionally scaled axes. If `p` is not in the range and
`allow_extra` == True, a linear extrapolation is done using the two data
points at the end corresp... | f69cc25d4610987a5f76f21e23df49efad5c6a7f | 6,429 |
def eval_in_els_and_qp(expression, ig, iels, coors,
fields, materials, variables,
functions=None, mode='eval', term_mode=None,
extra_args=None, verbose=True, kwargs=None):
"""
Evaluate an expression in given elements and points.
Parameter... | b71a20f0806ac03f9f995ffa41f317bc2c029d1c | 6,430 |
def tracks2Dataframe(tracks):
"""
Saves lsit of Track objects to pandas dataframe
Input:
tracks: List of Track objects
Output:
df: Pandas dataframe
"""
if(len(tracks) == 0):
print("Error saving to CSV. List of tracks is empty")
return
#... | 9d25e7f9535cfefc5b6faf791555b382edf12a07 | 6,431 |
def sift_point_to_best(target_point, point, sift_dist):
"""
Move a point to target point given a distance. Based on Jensen's inequality formula.
Args:
target_point: A ndarray or tensor, the target point of pca,
point: A ndarray or tensor, point of pca,
sift_dist: A float, distance w... | a14216998631f22d6c8d4e98112672608b8477e5 | 6,432 |
def jrandom_counts(sample, randoms, j_index, j_index_randoms, N_sub_vol, rp_bins, pi_bins,
period, num_threads, do_DR, do_RR):
"""
Count jackknife random pairs: DR, RR
"""
if do_DR is True:
DR = npairs_jackknife_xy_z(sample, randoms, rp_bins, pi_bins, period=period,
jtags1=j... | dce697b11f1d66b61aef46982c40b0310a292a92 | 6,433 |
from typing import Any
def process_not_inferred_array(ex: pa.ArrowInvalid, values: Any) -> pa.Array:
"""Infer `pyarrow.array` from PyArrow inference exception."""
dtype = process_not_inferred_dtype(ex=ex)
if dtype == pa.string():
array: pa.Array = pa.array(obj=[str(x) for x in values], type=dtype,... | c2d84f436dbd1123e38e1468101f8910e928e9ba | 6,434 |
def start_end(tf):
"""Find start and end indices of running streaks of True values"""
n = len(tf)
tf = np.insert(tf, [0, len(tf)], [False, False])
# 01 and 10 masks
start_mask = (tf[:-1] == 0) & (tf[1:] == 1)
end_mask = (tf[:-1] == 1) & (tf[1:] == 0)
# Locations
start_loc = np.whe... | 592a55da0d1c02259676444d2dd640f759dfb62d | 6,435 |
def remove_provinces(data, date_range):
"""
REMOVE PROVINCES
:param data: The Data received from the API
:param date_range: the date range of the data
:return: data after removing provinces
"""
countries_with_provinces = []
names_of_countries_with_prov = []
# get countries with prov... | 05e973254402fb2c9873fa065d45a6a5dd3da353 | 6,436 |
def plot_publish(families, targets=None, identifiers=None, keys=None):
"""Parse and plot all plugins by families and targets
Args:
families (list): List of interested instance family names
targets (list, optional): List of target names
identifiers (list, optional): List of interested di... | de2dc8cf3184fdd4d883e340256b55153346a3a9 | 6,437 |
import torch
def mdetr_resnet101_refcocoplus(pretrained=False, return_postprocessor=False):
"""
MDETR R101 with 6 encoder and 6 decoder layers.
Trained on refcoco+, achieves 79.52 val accuracy
"""
model = _make_detr("resnet101")
if pretrained:
checkpoint = torch.hub.load_state_dict_fro... | 30f73654fbabccc35629c9adb3d7ac91c5fe368d | 6,439 |
import re
def readConfigFile(filePath):
""" Read the config file and generate a dictionnary containing an entry for
every modules of the installation. """
modules_attributes_list = []
confFile = open(filePath, "r")
for i, line in enumerate(confFile.readlines()):
# Remove everything that is written after "#... | fadaec4dd005d6337eb5950b8782d5db944fb4cc | 6,441 |
def unpad_pkcs7(data):
"""
Strips PKCS#7 padding from data.
Raises ValueError if padding is invalid.
"""
if len(data) == 0:
raise ValueError("Error: Empty input.")
pad_value = data[-1]
if pad_value == 0 or pad_value > 16:
raise ValueError("Error: Invalid padding.")
for i ... | 27e59b8a880c130997f19814135c09cb6e94354d | 6,442 |
def create_output_channel(
mgr: sl_tag.TagManager, group: str, name: str, data_type: sl_tag.DataType
) -> sl_tag.TagData:
"""Create a FlexLogger output channel."""
# "Import" the channel into FlexLogger.
full_name = get_tag_prefix() + ".Import.Setpoint.{}.{}".format(group, name)
mgr.open(full_name, ... | 40bf2f6f555993deb4433d00768a3241dc8d72f6 | 6,443 |
import re
def slugify(value, allow_unicode=False):
"""
adapted from https://github.com/django/django/blob/master/django/utils/text.py
Convert to ASCII if 'allow_unicode' is False. Convert spaces or repeated
dashes to single dashes. Remove characters that aren't alphanumerics,
underscores, or hyphe... | f87a54f124a06fde2163fec39ba41881032db569 | 6,444 |
import torch
def data_process(raw_text_iter: dataset.IterableDataset) -> Tensor:
"""Converts raw text into a flat Tensor."""
data = [torch.tensor(vocab(tokenizer(item)), dtype=torch.long) for item in raw_text_iter]
return torch.cat(tuple(filter(lambda t: t.numel() > 0, data))) | 1c4bb8cf9997f6a6205c7c4f1122892b528f5c0e | 6,445 |
def rna_view_redirect(request, upi, taxid):
"""Redirect from urs_taxid to urs/taxid."""
return redirect('unique-rna-sequence', upi=upi, taxid=taxid, permanent=True) | 7a45b8b75e2cffb7573a7856c74d8e7b21e70543 | 6,446 |
from typing import AbstractSet
def skip_for_variants(meta: MetaData, variant_keys: AbstractSet[str]) -> bool:
"""Check if the recipe uses any given variant keys
Args:
meta: Variant MetaData object
Returns:
True if any variant key from variant_keys is used
"""
# This is the same behav... | 89bc8bf82431043cc4c6b42b6f8385df14c8d7d1 | 6,447 |
def _is_safe_url(url, request):
"""Override the Django `is_safe_url()` to pass a configured list of allowed
hosts and enforce HTTPS."""
allowed_hosts = (
settings.DOMAIN,
urlparse(settings.EXTERNAL_SITE_URL).netloc,
)
require_https = request.is_secure() if request else False
retu... | e1a8779c72b6d5adfa3fe01b478783d81ef515de | 6,448 |
def _server():
"""
Reconstitute the name of this Blueprint I/O Server.
"""
return urlparse.urlunparse((request.environ.get('wsgi.url_scheme',
'https'),
request.environ.get('HTTP_HOST',
... | 122457aa7f2a5e301299ccaaed4bba75cf273f5a | 6,450 |
def get_range_api(spreadsheetToken, sheet_id, range, valueRenderOption=False):
"""
该接口用于根据 spreadsheetToken 和 range 读取表格单个范围的值,返回数据限制为10M。
:return:
"""
range_fmt = sheet_id + '!' + range
get_range_url = cfg.get_range_url.format(spreadsheetToken=spreadsheetToken, range=range_fmt)
headers = {
... | 0c226caaa64e1bab09ac9b3af6a839609d62d5a3 | 6,451 |
def rotate_rboxes90(rboxes: tf.Tensor,
image_width: int,
image_height: int,
rotation_count: int = 1) -> tf.Tensor:
"""Rotate oriented rectangles counter-clockwise by multiples of 90 degrees."""
image_width = tf.cast(image_width, dtype=tf.float32)
image_h... | 7c21d6ea3bf8454af9aabd0f4408c9de593432ac | 6,452 |
def get_wrong_user_credentials():
"""
Monkeypatch GithubBackend.get_user_credentials to force the case where
invalid credentias were provided
"""
return dict(username='invalid',
password='invalid',
token='invalid',
remember=False,
remem... | 3598f00b05a53cdb13543642048fc8c333eebe52 | 6,453 |
def get_points(coords, m, b=None, diagonal=False):
"""Returns all discrete points on a line"""
points = []
x1, y1, x2, y2 = coords[0], coords[1], coords[2], coords[3]
# vertical line
if m is np.nan:
# bottom to top
y = min(y1, y2)
while y <= max(y1, y2):
points.a... | 23d6d4002c5625b8ea6011c26a0419c2a2710b53 | 6,454 |
def get_region_geo(region_id):
"""Get Geo/TopoJSON of a region.
Args:
region_id (str): Region ID (e.g. LK-1, LK-23)
Returns:
Geo-spatial data as GeoPandasFrame
"""
region_type = get_entity_type(region_id)
region_to_geo = _get_region_to_geo(region_type)
return region_to_geo... | 0493aa9e521c6d27cad6e6be07662449b6768a20 | 6,455 |
def load_vocabulary(f):
"""
Load the vocabulary from file.
:param f: Filename or file object.
:type f: str or file
:return: Vocabulary
"""
v = Vocabulary()
if isinstance(f, str):
file_ = open(f, 'r')
else:
file_ = f
for line in file_:
wordid, word, word... | 7a7cdf44016eccd1ceefd4fcc9e19f8f50caece2 | 6,456 |
def populate_objects(phylodata_objects, project_name, path_to_species_trees, path_to_gene_trees, path_to_ranger_outputs):
"""
this function will try and associate each phylodata object with the correct
species_besttree
gene_bootstrap_trees
and rangerDTL output files (if they exist)
args:
... | 5813981113be0513920fed0bc21bd6eedd6890f3 | 6,457 |
def xml_ind(content):
"""Translate a individual expression or variable to MathCAD XML.
:param content: str, math expression or variable name.
:return: str, formatted MathCAD XML.
"""
ns = ''' xmlns:ml="http://schemas.mathsoft.com/math30">''' # name space as initial head
sub_statement = xml_sta... | 67e82cbfd2796e31eaef7305e240fc9e3d93c08e | 6,459 |
from typing import Any
def read_slug(slug: str, db: Session = Depends(get_db)) -> Any:
"""
Get a post by slug
"""
db_slug = get_post(db, slug)
if db_slug is None:
raise HTTPException(status_code=404, detail="Post not found")
return db_slug | 347dfd32aa87417cecfbb5b192288fdc0585a071 | 6,460 |
from typing import List
def left_join_predictions(anno_gold: pd.DataFrame, anno_predicted: pd.DataFrame, columns_keep_gold: List[str],
columns_keep_system: List[str]) -> pd.DataFrame:
"""
Given gold mention annotations and predicted mention annotations, this method returns the gold a... | c34785e255940f69375ee64674186b0b7e8bdf1f | 6,461 |
import json
def get_users_data(filter):
"""
Returns users in db based on submitted filter
:param filter:
:return:
"""
# presets - filter must be in one of the lists
filter_presets = {"RegistrationStatus": ["Pending", "Verified"], "userTypeName": ["Administrator", "Event Manager", "Alumni"]... | 568dab028a30c9c6f88de83054b6a7b3e95662fc | 6,462 |
def calAdjCCTTFromTrace(nt,dt,tStartIn,tEndIn,dataIn, synthIn):
""" calculate the cross correlation traveltime adjoint sources for one seismogram
IN:
nt : number of timesteps in each seismogram
dt : timestep of seismograms
tStartIn : float starting time for trac... | 7524d350c241ae07810b1e5c38bb3db869136804 | 6,463 |
def get_par_idx_update_pars_dict(pars_dict, cmd, params=None, rev_pars_dict=None):
"""Get par_idx representing index into pars tuples dict.
This is used internally in updating the commands H5 and commands PARS_DICT
pickle files. The ``pars_dict`` input is updated in place.
This code was factored out v... | 9be23a37884eb674b3faa67ac17342b830c123fd | 6,464 |
def COSTR(LR, R, W, S):
"""
COSTR one value of cosine transform of two-sided function
p. 90
"""
COSNW = 1.
SINNW = 0.
COSW = COS(W)
SINW = SIN(W)
S = R[0]
for I in range(1, LR):
T = COSW * COSNW - SINW * SINNW
COSNW = T
S += 2 * R[I] * COSNW
re... | c4a4ff69ac4bd2d22885fc5103e62b0d861d8ed6 | 6,467 |
def CV_SIGN(*args):
"""CV_SIGN(int a)"""
return _cv.CV_SIGN(*args) | 380758a917df6111c27e6072a72a483ac13513c9 | 6,468 |
def import_config_data(config_path):
"""
Parameters
----------
config_path : str
path to the experimental configuration file
Returns
-------
config data : dict
dict containing experimental metadata for a given session config file
"""
data = get_config(config_path)
... | c174272dfd56876f7e8dbd306248c81aa1f3bdb2 | 6,469 |
def sigmaLabel(ax, xlabel, ylabel, sigma=None):
"""Label the axes on a figure with some uncertainty."""
confStr = r'$\pm{} \sigma$'.format(sigma) if sigma is not None else ''
ax.set_xlabel(xlabel + confStr)
ax.set_ylabel(ylabel + confStr)
return ax | 8ecf5ae2defd0d67c545943ea48992906612282e | 6,470 |
def startswith(x, prefix):
"""Determines if entries of x start with prefix
Args:
x: A vector of strings or a string
prefix: The prefix to test against
Returns:
A bool vector for each element in x if element startswith the prefix
"""
x = regcall(as_character, x)
return x... | 2d41a61d5a569af1925e8df7e2218fdae2bcb7ec | 6,471 |
def create_estimator(est_cls, const_kwargs, node, child_list):
"""
Creates an estimator.
:param est_cls: Function that creates the estimator.
:param const_kwargs: Keyword arguments which do not change during the evolution.
:param child_list: List of converted child nodes - should me empty.
:par... | 306a948f11bc3f70a3c489d1740d7144bbaa4c5b | 6,472 |
def exists(hub_id):
"""Check for existance of hub in local state.
Args:
hub_id(str): Id of hub to query. The id is a string of hexadecimal sections used internally to represent a hub.
"""
if 'Hubs.{0}'.format(hub_id) in config.state:
return True
else:
return False | 4b6d333e070e1dea9300db20bcd50b58c1b9b457 | 6,473 |
import logging
def query_by_date_after(**kwargs):
"""
根据发布的时间查询,之后的记录: 2020-06-03之后,即2020-06-03, 2020-06-04, ......
:param kwargs: {'date': date}
:return:
"""
session = None
try:
date = kwargs['date'].strip() + config.BEGIN_DAY_TIME
session = get_session()
ret = ses... | b6bbf40441ae8c3f6db861e8bed025986b7373bd | 6,474 |
from skimage.feature import peak_local_max # Defer slow import
from scipy.stats import iqr
import math
def _step_4_find_peaks(
aligned_composite_bg_removed_im,
aligned_roi_rect,
raw_mask_rects,
border_size,
field_df,
sigproc_params,
):
"""
Find peaks on the composite image
TASK: ... | 1439336369681569a85ee3e8a8566e4d02cc2999 | 6,476 |
import socket
def get_reverse_host():
"""Return the reverse hostname of the IP address to the calling function."""
try:
return socket.gethostbyaddr(get_ipaddress())[0]
except:
return "Unable to resolve IP address to reverse hostname" | 48911baf6507563470cb2d34af2392b52c58ac9a | 6,477 |
def trans_stop(value) -> TransformerResult:
"""
A transformer that simply returns TransformerResult.RETURN.
"""
return TransformerResult.RETURN | c124c62a15bca1000ecdfaaa02433de405338e6c | 6,478 |
def generator(n, mode):
""" Returns a data generator object.
Args:
mode: One of 'training' or 'validation'
"""
flip_cams = False
if FLAGS.regularization == 'GRU':
flip_cams = True
gen = ClusterGenerator(FLAGS.train_data_root, FLAGS.view_num, FLAGS.max_w, FLAGS.max_h,
... | 1dc7950a4ae0f7c35a4ba788710327c2e63fae14 | 6,479 |
import re
def remove_multispaces(text):
""" Replace multiple spaces with only 1 space """
return [re.sub(r' +', " ",word) for word in text] | 0b87f6a4b0d49931b3f4bec6f9c313be05d476f0 | 6,480 |
def empirical_ci(arr: np.ndarray, alpha: float = 95.0) -> np.ndarray:
"""Computes percentile range in an array of values.
Args:
arr: An array.
alpha: Percentile confidence interval.
Returns:
A triple of the lower bound, median and upper bound of the confidence interval
with... | 8bb0ff5768c70d4e34174ea4187898513a4f841e | 6,481 |
def euclidean(a,b):
"""Calculate GCD(a,b) with the Euclidean algorithm.
Args:
a (Integer): an integer > 0.
b (Integer): an integer > 0.
Returns:
Integer: GCD(a,b) = m ∈ ℕ : (m|a ⋀ m|b) ⋀ (∄ n ∈ ℕ : (n|a ⋀ n|b) ⋀ n>m).
"""
if(a<b):
a,b = b,a
a, b = abs(a), abs(b)
while a != 0:
a, b = b % a, a
return... | 8af351e251e52336d7ef946a28bb6d666bff97c3 | 6,482 |
from typing import Union
def check_reserved_pulse_id(pulse: OpInfo) -> Union[str, None]:
"""
Checks whether the function should be evaluated generically or has special
treatment.
Parameters
----------
pulse
The pulse to check.
Returns
-------
:
A str with a specia... | d4bd89da98612031fbcc7fcde9bcf40bb0843f70 | 6,483 |
def figure(*args, **kwargs):
"""
Returns a new SpectroFigure, a figure extended with features useful for
analysis of spectrograms.
Compare pyplot.figure.
"""
kw = {
'FigureClass': SpectroFigure,
}
kw.update(kwargs)
return plt.figure(*args, **kw) | 851b02773dc974691ba6e43477244aa8e4ba0760 | 6,484 |
import six
def allow_ports(ports, proto="tcp", direction="in"):
"""
Fully replace the incoming or outgoing ports
line in the csf.conf file - e.g. TCP_IN, TCP_OUT,
UDP_IN, UDP_OUT, etc.
CLI Example:
.. code-block:: bash
salt '*' csf.allow_ports ports="[22,80,443,4505,4506]" proto='tc... | 3a14a9ea74daf4062e3bd970623284a152ffde08 | 6,485 |
def add(n1, n2, base=10):
"""Add two numbers represented as lower-endian digit lists."""
k = max(len(n1), len(n2)) + 1
d1 = n1 + [0 for _ in range(k - len(n1))]
d2 = n2 + [0 for _ in range(k - len(n2))]
res = []
carry = 0
for i in range(k):
if d1[i] + d2[i] + carry < base:
... | 098bfa9ebedf7f219a6f9910e98c4cf9cbf13aa8 | 6,486 |
from datetime import datetime
import pytz
def folder_datetime(foldername, time_infolder_fmt=TIME_INFOLDER_FMT):
"""Parse UTC datetime from foldername.
Foldername e.g.: hive1_rpi1_day-190801/
"""
# t_str = folder.name.split("Photos_of_Pi")[-1][2:] # heating!!
t_str = foldername.split("day-")[-1]... | fbbd9d9749cba6807391009e1720ca35b9dd7c7b | 6,487 |
def get_policy_profile_by_name(name, db_session=None):
"""
Retrieve policy profile by name.
:param name: string representing the name of the policy profile
:param db_session: database session
:returns: policy profile object
"""
db_session = db_session or db.get_session()
vsm_hosts = con... | 36136be7e618490bcda58799285277982bc41f71 | 6,488 |
def ecg_hrv_assessment(hrv, age=None, sex=None, position=None):
"""
Correct HRV features based on normative data from Voss et al. (2015).
Parameters
----------
hrv : dict
HRV features obtained by :function:`neurokit.ecg_hrv`.
age : float
Subject's age.
sex : str
Subj... | fe3ab5e6f97920f44b7a32928785a19a6185e3d9 | 6,489 |
import warnings
def declared_attr_roles(rw=None, call=None, read=None, write=None):
"""
Equivalent of :func:`with_roles` for use with ``@declared_attr``::
@declared_attr
@declared_attr_roles(read={'all'})
def my_column(cls):
return Column(Integer)
While :func:`with_ro... | 4128754046a18e332d5b6f8ba7e2c60d1d576c6b | 6,490 |
def _in_iterating_context(node):
"""Check if the node is being used as an iterator.
Definition is taken from lib2to3.fixer_util.in_special_context().
"""
parent = node.parent
# Since a call can't be the loop variant we only need to know if the node's
# parent is a 'for' loop to know it's being ... | f1109b22842e3e9d6306a266b0654670a9f30ac8 | 6,491 |
def to_point(obj):
"""Convert `obj` to instance of Point."""
if obj is None or isinstance(obj, Point):
return obj
if isinstance(obj, str):
obj = obj.split(",")
return Point(*(int(i) for i in obj)) | 340182f054ebac39133edb09c9e1d049f9dde9d4 | 6,492 |
def issues(request, project_id):
"""问题栏"""
if request.method == "GET":
# 筛选条件 -- 通过get来实现参数筛选
allow_filter_name = ['issues_type', 'status', 'priority', 'assign', 'attention']
condition = {} # 条件
for name in allow_filter_name:
value_list = request.GET.getlist(name)
... | 099b292e8143f1559f3e78e96ad555eaa7328449 | 6,493 |
from operator import and_
def get_30mhz_rht_data(sensor_id):
"""
Produces a JSON with the 30MHz RH & T sensor data for a specified sensor.
Args:
sensor_id - Advanticsys sensor ID
Returns:
result - JSON string
"""
dt_from, dt_to = parse_date_range_argument(request.args.get("ra... | d688850720162c33ea9bdd84eaed9ecd83a49902 | 6,494 |
import requests
def stock_em_gpzy_industry_data() -> pd.DataFrame:
"""
东方财富网-数据中心-特色数据-股权质押-上市公司质押比例-行业数据
http://data.eastmoney.com/gpzy/industryData.aspx
:return: pandas.DataFrame
"""
url = "http://dcfm.eastmoney.com/EM_MutiSvcExpandInterface/api/js/get"
page_num = _get_page_num_gpzy_indu... | 4ac0de7bdbae197c9d89dc663dbef594e2010fc6 | 6,495 |
def to_float32(x: tf.Tensor) -> tf.Tensor:
"""Cast the given tensor to float32.
Args:
x: The tensor of any type.
Returns:
The tensor casts to float32.
"""
return tf.cast(x, tf.float32) | 2c25ea5450e86139fa1c21041be73e21f01b1bff | 6,496 |
def cli_usage(name=None):
"""
custom usage message to override `cli.py`
"""
return """
{logo}
usage: signalyze [-h] [-o OUTPUT] [--show-name] [-b | -w | -all] [--show-graph | --show-extra-info]
""".format(logo=get_logo()) | f512be4404da92aff9a237cdece487a266cbf175 | 6,497 |
def unban_chat_member(chat_id, user_id, **kwargs):
"""
Use this method to unban a previously kicked user in a supergroup. The user will not return to the group automatically,
but will be able to join via link, etc. The bot must be an administrator in the group for this to work
:param chat_id: Unique id... | cc1558e1d49841e47ebf4f457e615319e47abae4 | 6,498 |
from typing import Optional
import re
def parse_progress_line(prefix: str, line: str) -> Optional[float]:
"""Extract time in seconds from a prefixed string."""
regexp = prefix + r"(?P<hours>\d+):(?P<minutes>\d{2}):(?P<seconds>\d{2}.\d{2})"
match = re.search(regexp, line)
if not match:
return N... | 690b2f0e48a5f584da646f9e4058ed75e654251e | 6,499 |
from functools import reduce
def convert_array_to_df(emission_map):
"""
This function converts the emission map dict to a DataFrame where
- 'emission_map' is a dictionary containing at least 'z_var_ave', 'count_var','std_var','q25_var' and'q75_var
"""
def reform_df(df, nr):
"""This subfun... | 171e387ca51f543b522946a213e51040463aec74 | 6,500 |
def add_missing_flows(data):
"""There are some flows not given in ReCiPe that seem like they should be there, given the relatively coarse precision of these CFs."""
new_cfs = {
"managed forest": {
"amount": 0.3,
"flows": [
"occupation, forest, unspecified",
... | e23184bb7363db4777d9f693a3fdc4ace9f8ff14 | 6,501 |
from typing import List
def cglb_conjugate_gradient(
K: TensorType,
b: TensorType,
initial: TensorType,
preconditioner: NystromPreconditioner,
cg_tolerance: float,
max_steps: int,
restart_cg_step: int,
) -> tf.Tensor:
"""
Conjugate gradient algorithm used in CGLB model. The method ... | bc00f2423c4ffdaf0494ab6e6114222cbc694915 | 6,502 |
def num_fixed_points(permutation):
"""
Compute the number of fixed points (elements mapping to themselves) of a permutation.
:param permutation: Permutation in one-line notation (length n tuple of the numbers 0, 1, ..., n-1).
:return: Number of fixed points in the permutation.
.. rubric:: Examples... | 124713cd4c90988c43630a74881e7107ff748682 | 6,505 |
import numpy
def mutate(grid):
"""
Alters the cycle by breaking it into two separate circuits, and then fusing
them back together to recreate a (slightly different) cycle.
This operation is called "sliding" in 'An Algorithm for Finding Hamiltonian
Cycles in Grid Graphs Without Holes', and it's sp... | 35cc32385d090fa8091f872858fbeb0c32ecf43d | 6,507 |
def reverse_permute(output_shape: np.array, order: np.array):
"""
Calculates Transpose op input shape based on output shape and permute order.
:param output_shape: Transpose output shape
:param order: permute order
:return: Transpose input shape corresponding to the specified output shape
"""
... | ada631cc086a1dc0d2dce05f6d97a74a1f3861f4 | 6,508 |
def recursive_bisection(block, block_queue, epsilon_cut, depth_max, theta, lamb, delta, verbose=False):
"""Random cut and random converge
Args:
block_queue (multiprocessing.Queue): Shared queue to store blocks to be executed
Returns:
[{"range": {int: (int,int)}, "mondrian_budget": float, "... | d65070c2cf64356277c4af044b97c5eaa8efdd3d | 6,509 |
def _get_global_step_read(graph=None):
"""Gets global step read tensor in graph.
Args:
graph: The graph in which to create the global step read tensor. If missing,
use default graph.
Returns:
Global step read tensor.
Raises:
RuntimeError: if multiple items found in collection GLOBAL_STEP_RE... | 46bf3b55b36216e4247d6d73226d22b20383321f | 6,510 |
from unittest.mock import Mock
def light_control() -> LightControl:
"""Returns the light_control mock object."""
mock_request = Mock()
mock_request.return_value = ""
return LightControl(mock_request) | cb135ed24d2e992eab64b298e5c9238576a37c5d | 6,511 |
def map_threshold(stat_img=None, mask_img=None, alpha=.001, threshold=3.,
height_control='fpr', cluster_threshold=0):
""" Compute the required threshold level and return the thresholded map
Parameters
----------
stat_img : Niimg-like object or None, optional
statistical image (... | ea7c1ca48641ed76eef2f2b0396b93fd522fdbaf | 6,512 |
import time
import random
def grab_features(dataframe: pd.DataFrame) -> pd.DataFrame:
"""
Attempts to assign song features using the get_features function to all songs in given dataframe.
This function creates a column that encompasses all features retuerned from Spotify in a json format for each track I... | 7a2810b68815241a62f2ce753169bd982a17a211 | 6,513 |
def _build_geo_shape_query(field, geom, relation):
"""Crea una condición de búsqueda por relación con una geometría en formato
GeoJSON.
Args:
field (str): Campo de la condición.
geom (dict): Geometría GeoJSON.
relation (str): Tipo de búsqueda por geometrías a realizar. Ver la
... | f42fe6e21da30e3d6c8466be92143b215925686c | 6,514 |
from typing import Optional
def map_symptom(symptom_name: str) -> Optional[str]:
"""
Maps a *symptom_name* to current symptom values in ID3C warehouse.
There is no official standard for symptoms, we are using the values
created by Audere from year 1 (2018-2019).
"""
symptom_map = {
'f... | c86f0694715b434b1e3b2dc3f66ddfc3afadeaf0 | 6,516 |
def get_project_details(p):
"""Extract from the pickle object detailed information about
a given project and parse it in a comprehensive dict structure."""
res = {}
project = p['projects'][0]
fields = {'Owner(s)': 'project_owners',
'Member(s)': 'project_members',
'Colla... | f8ba3debdd8be7cc7a906851a6a6fb1e3c5f039a | 6,518 |
def get_category(name: str) -> Category:
"""Returns a category with a given name"""
return Category.objects.get(name=name) | 4dc99ed672bbb3d7843692da797d0cd901c2c44c | 6,519 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.