content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def normalize_scopes(scopes):
"""
Given a list of public-facing scope names from a CAS token, return the list of internal scopes
This is useful for converting a single broad scope name (from CAS) into the small constituent parts
(as used by views)
:param list scopes: a list public facing scope... | e5250cacf06edb8def758c02230c9aee81b1d347 | 60,600 |
def service_del(svc_rec=None, ipaddr=None, proto=None, port=None):
"""Deletes a service to the database"""
host_rec = get_host_record(ipaddr)
if svc_rec:
query = (db.t_services.id == svc_rec)
elif host_rec:
query = (db.t_services.f_hosts_id == host_rec.id)
if proto:
q... | 4a64fbf1cbb505fe9f64773afac10b052710e68c | 60,601 |
import json
def data_to_html_diff(data_1, data_2):
"""
Description: Core bootstrap of parsing double string JSON data to HTML data.
Integrated with humanized visual data difference.
:param data_1: Base/Original string JSON data
:param data_2: Fresh/New string JSON data
:return: HTML styled dat... | 3102b20e4c21955185d8df8c017a34340f00530a | 60,602 |
from typing import Optional
from typing import Dict
def get_pt_tempo_backend(
name: Optional[Text] = None,
config: Optional[Dict] = None) -> BasePtTempoBackend:
"""Returns a backend class and configuration. """
# input checks
if name is None:
name = PT_TEMPO_BACKEND
assert name... | 26f50a49ddfb68e3ef3ce306ee2ff274a17719f0 | 60,603 |
def pv_anomalies_to_nan(df_pv, model=GradientBoostingRegressor(), tolerance=0.1):
"""
Run this function to identify places where predicted values for pv_power_mw are much larger
than true values and where the true value is 0 (we expect these are anomalies) and make these values nan.
"""
df_power_fe... | a7ab856bfb6aa5d7084d830928b14a13ee514784 | 60,604 |
def distribute_srcs_1D(X, n_src, ext_x, R_init):
"""Distribute sources in 1D equally spaced
Parameters
----------
X : np.arrays
points at which CSD will be estimated
n_src : int
number of sources to be included in the model
ext_x : floats
how much should the sources exte... | d6249faf0b27ad0cfbabe3e4f606e94122b6f9d2 | 60,605 |
import sys
import re
def gen_colors(img, color_count):
"""Format the output from imagemagick into a list
of hex colors."""
magick_command = has_im()
for i in range(0, 20, 1):
raw_colors = imagemagick(color_count + i, img, magick_command)
if len(raw_colors) > 16:
break
... | 14511147a0a1fc6a5a504fdf950d88f431227078 | 60,606 |
def clip(threshold=0.5):
"""
clip the tensor
"""
dict_binarize = {'name': 'scale_range',
'kwargs': {'threshold': threshold}
}
return dict_binarize | 5b2ccc5d543173e44c8a48eec054391e7332ca35 | 60,607 |
def prepare_data(word2id, token_sentences, max_sentence_words = 12 ):
""" Prepares dataset for the model
Args:
word2id: dictionary to convert from words to id
token_sentences: a python array of sentences
max_sentence_words: maximum number of words in a senetnce
Return:
X: Pyt... | caf0f459e8840126842e27874b17c23b5a59377c | 60,608 |
import json
def list_project_nodes(project):
"""List all nodes belonging the given project.
Returns a JSON array of strings representing a list of nodes.
Example: '["node1", "node2", "node3"]'
"""
db = model.Session()
project = _must_find(db, model.Project, project)
nodes = project.node... | 05abda37f6e9e4ba733522081a9e4454be6b003b | 60,609 |
def fetch_california_gps():
"""
Fetch sample GPS velocity data from California (the U.S. West coast).
Velocities and their standard deviations are in meters/year. Height is
geometric height above WGS84 in meters. Velocities are referenced to the
North American tectonic plate (NAM08). The average ve... | 827b3dd5fe8834ce188567584217eb52c878c731 | 60,610 |
def calculate_enrichment_in_all_sliding_window_positions(output_file, enriched_positions, non_enriched_positions, seed_positions, maximum_rank=500):
"""
Calculate the enrichment in all the positions of the sliding window.
"""
num_seeds = len(seed_positions)
# Calculate all the central positions of... | 0fe0aad054377cef9a8981711568180e9056462f | 60,611 |
def read_bands_window(area_dict, area, window):
"""
Reads the bands for each image of each area and calculates
the derived indices.
Args:
area_dict (dict) : Python dictionary containing the file paths per area
area (str) : The area of interest (AOI)
Returns:
d... | f3d5b285d02d4f70cd9fa5381b59dc9505baa48c | 60,612 |
def CESS_SMC(initial_particles, log_prior, log_likelihood, annealed_log_posterior, thresh=0.99, resample_thresh=0.5, n_mcmc_steps=5,
initial_stepsize=0.01, stepsize_adaptation=0.5):
"""Select the next lambda increment based on an estimate of the conditional effective sample size
Question to think ... | 1003b53e30d611e35203fad00f3125cb932939f5 | 60,613 |
def format_datetime(value):
"""Return a datetime string in the "YYYY-MM-DDTHH:MM:SSZ" format,
out of a datetime-like `value`.
"""
iso = _to_datetime(value).isoformat()
return f'{iso[:-6]}Z' | a83201213c5f3a440c8784b889952e9507e811ca | 60,614 |
def calc_weights(df, PLOT=False):
"""Calculate weights for the fittiing procedure based on the standard deviations at each time point.
If there is more than one replicate, use the standard deviations as weight.
Warn about NaN and infinite values.
Parameters
----------
df : pandas.DataFrame
... | 80c1b682cb62c27a39a29fbb903cd759213a3d2f | 60,615 |
def normalize_data_mpii(data, dim_to_use):
"""
Normalize the 2d pose data
Args
data:
dim_to_use: list of dimensions to keep in the 2d pose data
Returns
data_out: normalized data, mean and standard deviation
"""
data_mean = np.mean(data, axis=0)
data_std = np.std(data,axis=0)
data_out = np.... | 3756e57e724c3b83a707c3399b66671615ad74c6 | 60,616 |
import torch
def compute_gradient_penalty(critic, real_samples, fake_samples):
"""Calculates the gradient penalty loss for WGAN GP"""
# Random weight term for interpolation between real and fake samples
BATCH_SIZE, C, H, W = real_samples.shape
alpha = torch.rand((BATCH_SIZE, 1, 1, 1), device=device).r... | 412a05abb47f9b09798756ff085732e418ba50aa | 60,617 |
def get_person_chi_square_values(preference_distribution_df, recommendation_distribution_df,
n=RECOMMENDATION_LIST_SIZE):
"""
Pearson Chi-Square (p,q)
:return A Pandas DataFrame with m lines (distribution lines) and n columns
"""
global LOCAL_PREFERENCE_DISTRIBUT... | 99290f25709c11ed522a99d8690a88ef367d2f4c | 60,618 |
from pathlib import Path
def load_data(path_X=DATA_SPECTRA,
path_y=DATA_MEASUREMENTS):
""" Returns all available data amenable to DL models as numpy arrays."""
path_X = Path(path_X)
path_y = Path(path_y)
X = load_spectra(path_X)
y = load_measurements(path_y)
common_ids = _get_co... | 1bc2a15d4b40c6d2c79ba6fb7920e97f28a52685 | 60,619 |
def find_stim_channel(raw):
""" Finds the appropriate stim channel from raw.
Heuristically just looks for STI101 or STI014.
Parameters
----------
raw : mne.io.Raw
The raw object
Returns
-------
str
Channel name of the stimulus channel.
"""
channels = raw.info.g... | 1a4014a09ef7050e90f29151b1ff56ac4d5abe89 | 60,620 |
def parse_chunk_header_file_range(file_range):
"""Parses a chunk header file range.
Diff chunk headers have the form:
@@ -<file-range> +<file-range> @@
File ranges have the form:
<start line number>,<number of lines changed>
Args:
file_range: A chunk header file range.
Returns:
A tuple (ran... | 1af8c8750707c29171373ff4ed03de155d8a1cf1 | 60,621 |
def statistic_research_data(ws1, researches):
"""
res - результат выборки SQL
порядок возврата:
napr, date_confirm, time_confirm, create_date_napr, create_time_napr,
doc_fio, coast, discount, how_many, ((coast + (coast/100 * discount)) * how_many)::NUMERIC(10,2) AS sum_money,
ist_f, time_confirm... | 0f8fd49d52e51c5ace198b76bf770c1e03e4a689 | 60,622 |
def remove_defaults(d, fn):
"""
Remove keys in d that are set to the default values from
fn. This method is used to unclutter the _repr_attrs()
return value.
d will be modified by this function.
Returns d.
>>> class Foo(object):
... def __init__(self, a=1, b=2):
... ... | 739d316fd61caee4ede7ff4a149ba69c5e63fb94 | 60,623 |
def parse_KO(df4parse, org_list):
"""
parse the KEGG part in eggNOG annotation file
:param df4parse: the pd.Dataframe object directly comes from the eggNOG annotation file(skip the comment lines, of course)
:return:the parsed KEGG annotation in pd.Dataframe.
"""
KO2map, KEGGmap = get_KEGGmap(own... | 1f1db1d686ce5c6fa81604f9d34f5d916c20cba9 | 60,624 |
def smooth_saliency_maps(saliency_matrices, smoothing_radius_grid_cells):
"""Smooths saliency maps via Gaussian filter.
T = number of input tensors to the model
:param saliency_matrices: length-T list of numpy arrays.
:param smoothing_radius_grid_cells: e-folding radius (number of grid cells).
:re... | 1b19b1ddc5a27f7c7ade86124bedf902ba2cec7f | 60,625 |
def s_i(d, input_, output, output_value):
"""
Compute the specific mutual information I(input_ : output=output_value)
Parameters
----------
d : Distribution
The distribution from which this quantity is to be calculated.
input_ : iterable
The input aggregate variable.
output ... | 25c03b2f4c7424fd210d8eea770d15cf85ae0b92 | 60,626 |
def _measure_valued_normal_scale_grad(
function, dist_samples, dist, coupling=True):
"""Computes the measure valued gradient wrt the `scale of the Normal `dist`.
For details, see Section 6 of
"Monte Carlo Gradient Estimation in Machine learning".
Args:
function: A function for which to compute stoch... | e6ec2bc32a1247568a79be28fc9cfe0ad9e14419 | 60,627 |
def add_to_dict(d, grads_o, volume, _3d_to_numeric_pos_dict):
"""
volume: volume to add to the dictionary
"""
outfile_pos = list()
for dim in range(3):
# logger.debug("dim: " + str(dim))
for i, upper_border in enumerate(grads_o[dim]):
if i != 0 :
low... | 91279d573a3202147897c552e1b00382e3b8cefd | 60,628 |
def cofactor(*args):
"""
Get the (i,j) cofactor matrix.
cofactor(IM x, int i, int j) -> IM
cofactor(DM x, int i, int j) -> DM
cofactor(SX x, int i, int j) -> SX
"""
return _casadi.cofactor(*args) | f8d904b30fa07dbccd45678b5864cae2930d75aa | 60,629 |
def parse_namespacepath(tt):
"""
<!ELEMENT NAMESPACEPATH (HOST, LOCALNAMESPACEPATH)>
"""
check_node(tt, 'NAMESPACEPATH')
if len(kids(tt)) != 2:
raise ParseError('Expecting (HOST, LOCALNAMESPACEPATH) '
'got %s' % kids(tt).keys())
host = parse_host(kids(tt)[0])
... | d1471d8dbbb60f96a37b92d7af8955d0b7b92172 | 60,630 |
def getTrainDataset(paths):
"""
loads data and labels, computes fpfh
:param paths: list of paths to train data
:return: fpfh, xyz coordinates, labels
"""
labels = np.array([])
histograms = np.array([])
xyz = np.array([])
for p in paths:
# loading data, downsampling it and ... | 4a683819c71170a49f5a8ae421bb7f652f06100f | 60,631 |
def arrow(axis, x, y, dx, dy, **kwargs):
"""Draws arrow on specified axis from (x,y) to (x+dx,y+dy)."""
a = FancyArrow(x, y, dx, dy, **kwargs)
axis.add_artist(a)
return a | 26e51c88b928f2e38cc7650d4caa07d34c2c9c4b | 60,632 |
from typing import Any
def raise_if_incorrect_type(obj: object, expected_type: Any):
"""
general function to check obj type
raise error when it is incorrect
Parameters
----------
obj: Object
any object
expected_type: Any
any class or type
Returns
-------
true... | 923636a3ef1c3fdefbe29bbf12d522ce84acedaf | 60,633 |
from typing import Optional
def default_primitive_serializer(obj: object,
cls: Optional[type] = None,
**kwargs) -> object:
"""
Serialize a primitive; simply return the given ``obj``.
:param obj: the primitive.
:param cls: the type of ``... | 220dd315caf0a8c2c15e7ebe678c7bc08b8c3e2b | 60,634 |
def nco_electrolyte_exchange_current_density_Ecker2015(c_e, c_s_surf, T):
"""
Exchange-current density for Butler-Volmer reactions between NCO and LiPF6 in
EC:DMC [1, 2, 3].
References
----------
.. [1] Ecker, Madeleine, et al. "Parameterization of a physico-chemical model of
a lithium-i... | aa3e47df9dacee73ad2f4beb78257c30b860393e | 60,635 |
def _get_df_rokker_history(rokker_history):
"""Process raw history and return clean dataframe"""
dates = list(rokker_history['date'])
users = list(rokker_history['user_id'])
ages = list(rokker_history['age'])
countries = list(rokker_history['country'])
genders = list(rokker_history['gender'])
... | ce963cd5fa72b72708cfb14f29086c4da147a72a | 60,636 |
def put_job(scheduled_jobs_object, et_scanner_sqs, request_body_str):
"""
the request body should be a dictionary (so \*\*request_body are kwargs),
and it with the following required keys:
* log_name
* log_schema_version
* redshift_id
* start_date
:param scheduled_jobs_object: the Sche... | a3595373dc50b1dc4ff9c6cee1cf251b0a8a23e3 | 60,637 |
from pathlib import Path
def sandbox(request, tmpdir_factory, monkeypatch):
""" Provide tmp dirs for project/envs and update CWD/NPMENV_DIR respectively
NOTE Apply to all tests to avoid accidental filesystem changes
WARN Even if some methods don't touch filesystem now, they may in future!
"""
#... | 5a312477318d37dbb84f5b4cd17a0e238f797bb6 | 60,638 |
from datetime import datetime
def filename_now(sep="-"):
"""
Return the current date and time as iso format suitable for filename.
"""
now = datetime.now().isoformat(sep=sep, timespec="seconds")
return now.replace(":", sep) | 4ceb1eb0dfa401af66a6398955d733b086f6b056 | 60,639 |
def addOneContraints(d, Ca):
""" Ajoute une conditions de Robinson qui ne sont pas encore satisfaites à Ca """
addedConstraints = False
precision=0.0001
# print 'Contraintes ajoutees'
for i in range(d.n-2):
for j in range(i+2, d.n):
if (d[i,j] < d[i,j-1] - precision) and ([i,j,i... | d5f3f5ed9d214bac19c288f62a1ec478b02200f7 | 60,640 |
from typing import Dict
def simulate_order(
order: Order,
balances: Dict[str, float],
) -> Dict[str, float]:
"""TODO: Docstring, state assumptions going into this simulation
We can get fancier with this later, observe trends in actual trades we
propose vs execute, and use that to make more realis... | 17e2ac061b7a751132e8dd86d8326a9d4f1c5ad9 | 60,641 |
def _https(base_uri, *extra):
"""Combine URL components into an https URL"""
parts = [str(e) for e in extra]
str_parts = ''.join(parts)
str_base = str(base_uri)
if str_base.startswith("https://"):
return "{0}{1}".format(str_base, str_parts)
elif str_base.startswith("http://"):
... | 6a88314a9f9d069083e2e0ec5350ab3ef8abe987 | 60,642 |
def obsv(A, C):
"""Observability matrix
Parameters
----------
A, C: np.array
Dynamics and output matrix of the system
Returns
-------
O: matrix
Observability matrix
Examples
--------
>>> O = obsv(A, C)
"""
return ctrb(A.T, C.T).T | ab458ad8eacae02602e750bf9b0248db3f5cf4d7 | 60,643 |
def zoom(Z, ratio):
""" Bilinear image zoom """
nrows, ncols = Z.shape
x,y = np.meshgrid(np.linspace(0, ncols, int(ratio*ncols), endpoint=False),
np.linspace(0, nrows, int(ratio*nrows), endpoint=False))
return bilinear_interpolate(Z, x, y) | 4b2e5418ffe7f8b9bf8fb91c9d0d6d3fe00d659b | 60,644 |
def get_model(request, model, model_serializer, pk):
"""
Retrieve a model by id/pk
"""
model = get_model_by_pk(model, pk)
serializer = model_serializer(model, context={'request': request})
return Response(serializer.data) | ecd9a6f4090f2ae07125bf6360a647529d162dea | 60,645 |
import random
def getCactusInputs_random(regionNumber=0, tempDir=None,
sequenceNumber=None,
avgSequenceLength=None,
treeLeafNumber=None):
"""Gets a random set of sequences, each of length given, and a species
tree relating them. ... | 5d4c70ca015369f48590238f5bd01278b268ad47 | 60,646 |
def _get_sel_lvardata(cfg, dataname, lvarnames):
"""Get filenames from cfg for one model and differen variable(s)."""
selection = []
for lvar in lvarnames:
for hlp in select_metadata(cfg['input_data'].values(), long_name=lvar,
dataset=dataname):
select... | ebb3ac77fc158b739874f9be2549eef2964b6ff4 | 60,647 |
def login_user(request):
"""
Handles loading the login page and authenticating the user
:param request:
:return:
"""
if request.method == "GET":
# Log out user if one is logged in already
if request.user.is_authenticated:
print "logging in"
logout(reque... | 0a5da665844d37bcc33ba860a4365c722a9e4f3e | 60,648 |
def poster(request, videoid):
"""Generate a still frame for a video (if needed) and
generate a redirect to the static server for this frame"""
video = get_object_or_404(GlossVideo, pk=videoid)
if 'view_dataset' not in get_perms(request.user, video.gloss.dataset):
# If user has no permissions to... | cafaea9f876c7331b590df846499c85b13f89bbc | 60,649 |
def next_quote(str, i):
"""
Finds the next substring ``str[k:j]`` of ``str[i:]`` enclosed by
non-escaped double-quotes and returns the tuple ``j, res`` where
``res`` is ``str[k:j]`` with escaped double-quotes replaced by
single-quotes.
"""
# Find the opening quote. This is simple becaus... | ba3aef496b271c994d63c069859056ca9b9e99ac | 60,650 |
from typing import Dict
from typing import Any
from typing import Callable
import itertools
import os
import pickle
def grid_search(
tune_config: Dict[str, Any],
base_config: Dict[str, Any],
iterations: int,
early_stop: Dict[str, int],
trials_per_config: int,
fitness_fn: Callable,
search_p... | fd4be7e7236a991d1eeb10fa4d85ec81aa976df1 | 60,651 |
from pathlib import Path
from typing import Optional
import os
import subprocess
import time
import pprint
def vector_info(
path: Path,
task_description=None,
layer: Optional[str] = None,
readonly: bool = False,
report_summary: bool = False,
sql_stmt: Optional[str] = None,
sql_dialect: Opt... | c77590299462dca832882f36062f506dd0526908 | 60,652 |
from typing import Dict
from typing import Any
from typing import List
import sys
import os
def get_docker_command(
image: str,
launch_project: _project_spec.LaunchProject,
api: Api,
workdir: str,
docker_args: Dict[str, Any] = None,
) -> List[str]:
"""Constructs the docker command using the im... | a571587dbbf134263b40d51fb3dfa3d169272eb8 | 60,653 |
import re
def remove_puncatuation(review_str:str)->str:
"""remove puncatuation of a string
"""
return re.sub(r'[^\w\s]', '', review_str) | 99381b5b6573f0a20466c5de21d7a3b3c65f6ef8 | 60,654 |
def cmake_cache_string(name, value, comment=""):
"""Generate a string for a cmake cache variable"""
return 'set({0} "{1}" CACHE STRING "{2}")\n'.format(name, value, comment) | a9ecbc4bf88b495f9c3bd65379ec12afb244f723 | 60,655 |
from typing import Dict
from typing import Any
from typing import Optional
from typing import Callable
def try_get_from_dict(data: Dict[str, Any], key: str, original_value: Any, conversion: Optional[Callable[[Any], Any]] = None) -> Any:
"""Try to get value from dict, otherwise set default value"""
if not key ... | 354be2365af69dd5169aa3d74bf45cf8d095ed4d | 60,656 |
def get_feature_importance(booster, features=None, plot=False):
"""
Extract all the importance measures from the XGBoost Model
"""
# Extract importances from the booster
importance = pd.concat([
pd.DataFrame([list(i) for i in booster.get_score(importance_type=importance_type).items()],
... | bb118025636f974db37e385e2ba6d9c9546ca722 | 60,657 |
def causal_linear(x, n_inputs, n_outputs, name, filter_length, rate, batch_size):
"""Summary
Parameters
----------
x : TYPE
Description
n_inputs : TYPE
Description
n_outputs : TYPE
Description
name : TYPE
Description
filter_length : TYPE
Descripti... | 9898a47b384c1da72e7b0b1b4ef9f5970b66e38c | 60,658 |
def random_subinterval(key, interval, reduce_rate):
"""Generate a reduced interval from a base interval.
Args:
key: PRNG key for jax.random.
interval: (2,) shaped array of min and max values of the interval.
reduce_rate: interval reduction rate in (0, 1].
Returns: (2,) shaped array of min and max va... | f88fbe4271da9e5c4e6900ef2725566b45616764 | 60,659 |
def evaluate_constants(expressions, constants):
"""
Evaluate a list of constant expressions - each one can depend on the one before
it. These are usually used for the coefficients which have relationships
to each other. So ivt=.7 and then ivt_lr=ivt*.9.
Parameters
----------
expressions :... | 3cfa8e43abf13ffcccc8bf3c4e1912ed7888f10e | 60,660 |
import traceback
def user_error_to_message(e, error_statement, error_detail, return_code, rows = None):
"""ユーザー型サーバーエラーレスポンス(メッセージ付き) user server error response with message
Args:
e (Exception): 例外 exception
error_statement (str): エラー情報(処理内容)error info. process contents
error_detail (... | 65929bb45360cdf7a329b46b40c867fd360c8a78 | 60,661 |
def error_message(errors, key=None):
"""
Display one or more error messages
"""
output = ""
if isinstance(errors, dict):
if key and errors and key in errors:
message = errors[key]
output = f'<span id="{key}_error" class="error-message">{message}</span>'
elif e... | 920708758d152cb4bebfdf46b6d1c1e3d55687ad | 60,662 |
from corehq.apps.userreports.sql import IndicatorSqlAdapter
def _get_distinct_values(data_source_configuration, column_config, expansion_limit=DEFAULT_MAXIMUM_EXPANSION):
"""
Return a tuple. The first item is a list of distinct values in the given
ExpandedColumn no longer than expansion_limit. The second ... | 373266b5c93bfca2e9746d3933cb775341367306 | 60,663 |
def apply_ccm(image, ccm):
"""Applies a color correction matrix."""
ori_shape = image.shape
image = np.reshape(image, [-1, 3])
image = np.tensordot(image, ccm, axes=[[-1], [-1]])
return np.reshape(image, ori_shape) | 99da3993ab438b5ef4afd420b97f6b67a0a0a637 | 60,664 |
import numpy
def rasterize(geom, rast, burn_value=1):
"""
Rasterize a geometry. The result is aligned with the input raster.
"""
# Create in memory target raster
rasterized = rast.warp({'name': 'rasterized.MEM', 'driver': 'MEM'})
rasterized.bands[0].data(numpy.zeros(rast.width * rast.height))
... | 6c5ace18307978bc3c2975095225aa519513dae6 | 60,665 |
def spectral_pars_from_catalog(cat):
"""Create spectral parameters from 3FGL catalog columns."""
spectrum_type = cat['SpectrumType']
pars = get_function_defaults(cat['SpectrumType'])
par_idxs = {k: i for i, k in
enumerate(get_function_par_names(cat['SpectrumType']))}
for k in pars:... | d5a9e1f971a7fb4e5546228fcbb4787b6447b989 | 60,666 |
import board
import pimoroni_physical_feather_pins
import displayio
from adafruit_st7735r import ST7735R
def Screen(backlight_control=True, baudrate=100000000, spi=None):
"""__init__
:param bool backlight_control: determines whether this class should handle the screen's backlight (default True)
(this is u... | aca84026fce1d9b0cf8f44706cc8d75c1dc140bc | 60,667 |
import asyncio
async def async_setup_entry(hass, entry):
"""Set up a config entry."""
def token_updater(token):
"""Handle from sync context when token is updated."""
run_callback_threadsafe(
hass.loop,
partial(
hass.config_entries.async_update_entry,
... | 1169b2d8c768067cf2a930d9a0b70c5b8918d00c | 60,668 |
import pathlib
def get_root_dir():
"""Return the root directory, as a :class:`pathlib.Path`.
This tries to smart-detect the best location to host PythonUp. It tries
`~/Library`, which likely only exists on Macs; if that does not exist, use
the Linux standard `~/.local/share` instead.
"""
maco... | 583bd479367aabdc89eabd084fac41b39751a55e | 60,669 |
import torch
def image_scale_transformer(observation, fields=None, min=-1.0, max=1.0):
"""Scale image to min and max (0->min, 255->max).
Args:
observation (nested Tensor): If observation is a nested structure, only
``namedtuple`` and ``dict`` are supported for now.
fields (list[st... | 033e922cd903e2e2690cf121c7ff229049424bb3 | 60,670 |
import time
def keys(host, port, db):
"""
List keys for one database
"""
s = time.time()
try:
password = request.args.get('password', default = '', type=str)
sentinel = request.args.get('sentinel', default = 'off', type=str)
r = get_redis(host, port, db, password, sentinel)... | 577d4fecaf88e312436fca06c66df22cdd4b5074 | 60,671 |
import random
def proxy():
"""随机获取一个代理"""
proxys = mongo.db.proxy.find({'checked': 1})
proxy = random.choice(list(proxys))
proxy_type = 'http'
try:
proxy_type = 'https' if proxy['is_ssl'] else 'http'
except:
pass
return jsonify(
dict(ip=proxy['ip'], port=proxy['port... | 743b4a4e8b637f49d14ec9d260b0022a56336674 | 60,672 |
def default_trans_model():
"""Return the default transaction model."""
return {
'addresses': {'SingleLocation': {'city': 'Irvine',
'country': 'US',
'line1': '123 Main Street',
'post... | e55c453be31a4309f304f29081dfb109932ec28c | 60,673 |
from io import StringIO
def prepare_fixture_download(table_ids, domain, task, download_id):
"""Prepare fixture data for Excel download
"""
data_types_book, excel_sheets = _prepare_fixture(table_ids, domain, task=task)
header_groups = [("types", excel_sheets["types"]["headers"])]
value_groups = [(... | 8bde6690e9ef41c60ece828bd0661256873ce7fd | 60,674 |
def winsorize(data, cutoff=None, replace_with_cutoff=True):
"""Winsorize a Pandas DataFrame or Series with the largest/lowest value not considered outlier
Args:
data: (pd.DataFrame, pd.Series) data to winsorize
cutoff: (dict) a dictionary with keys {'std':[low,high]} or
{'quanti... | 17f793825a456977a7f65f4891b5afbb81bef7a9 | 60,675 |
def set_debug(enable):
"""Set debug enable and return old value."""
global _debug_on
old = _debug_on
_debug_on = enable
return old | 149ad4009167692ec67f8cec96dfcb937ccc3bee | 60,676 |
def vec_normalize(vec: Tensor, vec_dim: str or tuple or list or Shape = None):
""" Normalizes the vectors in `vec`. If `vec_dim` is None, the combined channel dimensions of `vec` are interpreted as a vector. """
return vec / vec_abs(vec, vec_dim=vec_dim) | 0192c3c276f9b586dc91717fade8b285ba3082b1 | 60,677 |
def tran_xywha_to_rbox(xywha):
"""包装opencv的cv.boxPoints函数
Args:
xywha: ((xy),(wh),angle)形式tuple或list, xy为中心点
"""
if len(xywha) != 3:
xywha = (xywha[:2], xywha[2:4], xywha[4])
return cv.boxPoints(xywha) | b232683fe4f126c0f604359863d1e1de2fe1898a | 60,678 |
def _func_speedup(param, p, n, overhead):
"""
Model function to calculate the speedup without overhead.
:param fparam: Actual parameters values
:param p: Numbers of cores used on model data
:param n: Problems size used on model data
:return: calculated speedup value
"""
if overhead:
... | b486de72fb839fa2a34781c0c0ba935e349f7cd6 | 60,679 |
import os
import json
def get_data_paths():
"""
The data paths dictionary that you mounted for the job/experiment.
{'data1': '/data/1/', 'data-foo': '/data/foo'}
"""
ensure_in_custer()
data_path = os.getenv('POLYAXON_RUN_DATA_PATHS', None)
try:
return json.loads(data_path) if data_... | f92902372a553e0c04ff3bb22ee7eb7d3ade902f | 60,680 |
import os
def filter_channel_or_video(ids: list, path: str) -> list:
"""
Checks if there exists data for the provided channel or video ids in the
directory (path arg), assuming the directory contains files of format
<id>.<ext>
Args:
- ids: a list of channel or video ids
- path: path to the... | 7705f249e94cbb910ef0ba6c653d39dd7052200e | 60,681 |
def timeseries_train_test_split(X, y, test_size):
"""
Perform train-test split with respect to time series structure
"""
# get the index after which test set starts
test_index = int(len(X)*(1-test_size))
X_train = X.iloc[:test_index]
y_train = y.iloc[:test_index]
X_test = X.iloc[te... | 83c72c880fa910d38d6a01fffc23427fd7eeab7e | 60,682 |
def PIsA (inUD):
""" Tells if the input really is a Python Obit UVDesc
returns true or false (1,0)
inUD = Python UVDesc to test
"""
################################################################
# Checks
if not isinstance(inUD, UVDesc):
return False
#
return Obit.UVDescIs... | 9263348dff54508a1cf46101f5f440544989a148 | 60,683 |
from typing import Tuple
def predict(data, label_map, batch_size):
"""
Args:
sentences (list[str]): each string is a sentence. If have sentences then no need paths
paths (list[str]): The paths of file which contain sentences. If have paths then no need sentences
Returns:
res (list(... | af1156d5354d35834ab40a9acd38b005312e729f | 60,684 |
from typing import Optional
import re
def split_str(source, sep: Optional[str] = None):
"""
warning: does not yet work if sep is a lookahead like `(?=b)`
usage:
>> splitStr('.......A...b...c....', sep='...')
<generator object splitStr.<locals>.<genexpr> at 0x7fe8530fb5e8>
>> list(... | b82d1693cd1fc14bec2c566408b100fda6a1a27c | 60,685 |
def combine_hyphenated_word(text: str) -> str:
"""
Combine words in text that contain hyphen.
Example: e-email to email
Args:
text: A sentence
Returns:
Processed sentence
"""
return " ".join(
w.replace("-", "") if _re_hyphen_word.match(w) else w for w in text.split... | 8174713dee3249feef70cb04628dde2a406df948 | 60,686 |
import ast
def _condition_as_text(lambda_inspection: icontract._represent.ConditionLambdaInspection) -> str:
"""Format condition lambda function as reST."""
lambda_ast_node = lambda_inspection.node
assert isinstance(lambda_ast_node, ast.Lambda)
body_node = lambda_ast_node.body
text = None # typ... | 5e529d122b855733489c3afcf6825e7f2e101881 | 60,687 |
import os
import functools
import tarfile
import shutil
def get_file(fname, origin, save_path, untar=False,
md5_hash=None, cache_subdir='datasets'):
"""Downloads a file from a URL if it not already in the cache.
Passing the MD5 hash will verify the file after download
as well as if it is alre... | ce748f7e834c66e5bfd390b6ac0f8c7484b93a4b | 60,688 |
def memoize(obj):
"""Memoize function parameters and their output."""
cache = {}
def memoizer(*args, **kwargs):
if args not in cache:
cache[args] = obj(*args, **kwargs)
return cache[args]
return memoizer | 2960010d1cc3f2851e28056ed57694a63ce33dcc | 60,689 |
import os
def getDeviceInfo() -> dict:
"""Return info of all appliances."""
__checkBase()
global __deviceInfo
if __deviceInfo is None:
__deviceInfo = __openJson(os.path.join(FIRED_BASE_FOLDER, INFO_FOLDER_NAME, DEVICE_INFO_FILENAME))
return __deviceInfo | b24d3be145214872c2e6a76b2223494c3dbb6f5f | 60,690 |
def __ensure_provisioning_reads(
table_name, table_key, gsi_name, gsi_key, num_consec_read_checks):
""" Ensure that provisioning is correct
:type table_name: str
:param table_name: Name of the DynamoDB table
:type table_key: str
:param table_key: Table configuration option key name
:typ... | beaedab7d323b3a2ed975cf02a32d11b9092e101 | 60,691 |
import functools
import operator
def df_filter_task_ids(df, task_ids, pid_col='pid', comm_col='comm', invert=False, comm_max_len=TASK_COMM_MAX_LEN):
"""
Filter a dataframe using a list of :class:`lisa.trace.TaskID`
:param task_ids: List of task IDs to filter
:type task_ids: list(lisa.trace.TaskID)
... | a61f325f3147c18900793dbb0c6245128ce1573e | 60,692 |
import math
def modpath_cell_prop(ml, head, xll, yll, x, y, rotation, depth):
"""
ml: MODFLOW loaded model
head: head data to find out water surface elevation
x, y coordinates
depth: Depth from water surface
This function returns an array [intersected row, intersected col, local x, local y, l... | 218bf34a1d1130bcc4adb6a7829f3410c3dda1d3 | 60,693 |
def bytescaling(data, cmin=None, cmax=None, high=255, low=0):
"""
Converting the input image to uint8 dtype and scaling
the range to ``(low, high)`` (default 0-255). If the input image already has
dtype uint8, no scaling is done.
:param data: 16-bit image data array
:param cmin: bias scaling of... | aa2dd1e007b41293005bd07f9d8b4c42dc26b2c4 | 60,694 |
def userbadges():
""" WIP: Assign user badges. """
if not current_user.is_admin():
abort(404)
form = AssignUserBadgeForm()
form.badge.choices = [(badge.bid, badge.name) for badge in badges]
ct = UserMetadata.select().where(UserMetadata.key == "badge").count()
return render_template(
... | 33f3eddd5b21fb8bc8652c6c17cdf152dc1cf156 | 60,695 |
def games(category):
"""遊戲列表頁
"""
items = Game.query.distinct(Game.name)
if category == "named":
items = items.filter(Game.name_tw is not None)
elif category:
items = items.filter(Game.name_tw == category or Game.name == category)
return render_template('games.html', items=item... | 4506681e244a5647b0c9086b14390b32c9f51f50 | 60,696 |
from typing import Optional
from typing import Callable
from typing import Dict
import tqdm
def network_interaction_2d(*,
n_permutations: int,
elements: list,
pairs: Optional[list] = None,
objective_function: C... | e2111a4b8ccec2515647f0be9629f308b0833ac2 | 60,697 |
def generate_size_differences(data, sizes):
"""
Since the intersections are nested,
e.g. a 0.9 intersection is always nested inside a 0.5 intersection,
we can extract differences of intersections to assess which intersections are relevant.
So if we have the 0.9 and the 1 intersection, we know what n... | 35046347e45556817cc3a5695656e9a86da06a70 | 60,698 |
import json
def _ReadFullDockerConfiguration():
"""Retrieve the full contents of the Docker configuration file.
Returns:
The full contents of the configuration file, and whether it
is in the new configuration format.
"""
path, new_format = GetDockerConfig()
with open(path, 'r') as reader:
retur... | 05f08d1c83904ce0a3a97cdbe8faccd6ac694d3e | 60,699 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.