content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def max_tb(collection): # pragma: no cover
"""Returns the maximum number of TB recorded in the collection"""
max_TB = 0
for doc in collection.find({}).sort([('total_TB',-1)]).limit(1):
max_TB = doc['total_TB']
return max_TB | 5,356,600 |
def prep_im_for_blob(im, pixel_means, target_size_1, target_size_2, max_size_1, max_size_2):
"""Mean subtract and scale an image for use in a blob."""
im = im.astype(np.float32, copy=False)
im -= pixel_means
im_shape = im.shape
im_size_min = np.min(im_shape[0:2])
im_size_max = np.max(im_shape[0:2])
im_sca... | 5,356,601 |
def bandit_run_bandit_scan(attr_dict, path_package, package_name, path_sdk_settings=None, **__):
"""
Run Bandit Scan on whole package using the settings defined in ``constants.BANDIT_DEFAULT_ARGS``.
Raises a SDKException if ``bandit`` isn't installed. In use with ``validate``, this method should
o... | 5,356,602 |
def plotann(annotation, title = None, timeunits = 'samples', returnfig = False):
""" Plot sample locations of an Annotation object.
Usage: plotann(annotation, title = None, timeunits = 'samples', returnfig = False)
Input arguments:
- annotation (required): An Annotation object. The sample att... | 5,356,603 |
def test_dummy_ucc_finder(employees):
"""Test unique column combination finder."""
assert UCCDummy().run(employees) is not None | 5,356,604 |
async def test_activate_client(mqtt_client):
"""Test activate client method."""
route = respx.post(f"http://{HOST}:80/axis-cgi/mqtt/client.cgi")
await mqtt_client.activate()
assert route.called
assert route.calls.last.request.method == "POST"
assert route.calls.last.request.url.path == "/axis-... | 5,356,605 |
def match_assignments(nb_assignments, course_id):
"""
Check sqlalchemy table for match with nbgrader assignments from a specified course. Creates a dictionary with nbgrader
assignments as the key
If match is found, query the entry from the table and set as the value.
Else, set the value to None
... | 5,356,606 |
def xr_login_handler(spawn, context, session):
""" handles xr login prompt
"""
credential = get_current_credential(context=context, session=session)
if credential:
common_cred_username_handler(spawn=spawn, context=context, credential=credential)
else:
spawn.sendline(context['username... | 5,356,607 |
def tan(input):
"""Computes tangent of values in ``input``.
:rtype: TensorList of tan(input). If input is an integer, the result will be float,
otherwise the type is preserved.
"""
return _arithm_op("tan", input) | 5,356,608 |
def test_epipolar_angle():
"""
test epipolar angle computation
"""
# First case : same column, positive direction [row, col, alt]
start_line_1 = np.array([1, 0, 0])
end_line_1 = np.array([2, 0, 0])
reference_alpha_1 = math.pi / 2.0
alpha = compute_epipolar_angle(end_line_1, start_line_1... | 5,356,609 |
def recall_from_IoU(IoU, samples=500):
"""
plot recall_vs_IoU_threshold
"""
if not (isinstance(IoU, list) or IoU.ndim == 1):
raise ValueError('IoU needs to be a list or 1-D')
iou = np.float32(IoU)
# Plot intersection over union
IoU_thresholds = np.linspace(0.0, 1.0, samples)
r... | 5,356,610 |
def _GetImage(options):
"""Returns the ndvi regression image for the given options.
Args:
options: a dict created by _ReadOptions() containing the request options
Returns:
An ee.Image with the coefficients of the regression and a band called "rmse" containing the
Root Mean Square E... | 5,356,611 |
async def test_migrate_unique_id(hass):
"""Test migrate unique_id of the air_quality entity."""
registry = er.async_get(hass)
# Pre-create registry entries for disabled by default sensors
registry.async_get_or_create(
AIR_QUALITY_DOMAIN,
DOMAIN,
123,
suggested_object_id=... | 5,356,612 |
def get_registered_plugins(registry, as_instances=False, sort_items=True):
"""Get registered plugins.
Get a list of registered plugins in a form if tuple (plugin name, plugin
description). If not yet auto-discovered, auto-discovers them.
:param registry:
:param bool as_instances:
:param bool s... | 5,356,613 |
def datetime_to_timestamp(d):
"""convert a datetime object to seconds since Epoch.
Args:
d: a naive datetime object in default timezone
Return:
int, timestamp in seconds
"""
return int(time.mktime(d.timetuple())) | 5,356,614 |
def test_update__endtoend__4(
address_book, FieldFactory, UpdateablePersonFactory,
PostalAddressFactory, browser):
"""A user defined choice field can be updated."""
field_name = FieldFactory(
address_book, IPostalAddress, 'Choice', u'distance',
values=[u'< 50 km', u'>= 50 km'])._... | 5,356,615 |
def gumbel_softmax(logits, temperature):
"""From https://gist.github.com/yzh119/fd2146d2aeb329d067568a493b20172f
logits: a tensor of shape (*, n_class)
returns an one-hot vector of shape (*, n_class)
"""
y = gumbel_softmax_sample(logits, temperature)
shape = y.size()
_, ind = y.max(dim=-1)
... | 5,356,616 |
def in_whitelist(address):
"""
Test if the given email address is contained in the list of allowed addressees.
"""
if WHITELIST is None:
return True
else:
return any(regex.search(address) for regex in WHITELIST) | 5,356,617 |
def decomposePath(path):
"""
:example:
>>> decomposePath(None)
>>> decomposePath("")
>>> decomposePath(1)
>>> decomposePath("truc")
('', 'truc', '', 'truc')
>>> decomposePath("truc.txt")
('', 'truc', 'txt', 'truc.txt')
>>> decomposePath("/home/... | 5,356,618 |
def BSCLLR(c,p):
"""
c: A list of ones and zeros representing a codeword received over a BSC.
p: Flip probability of the BSC.
Returns log-likelihood ratios for c.
"""
N = len(c)
evidence = [0]*N
for i in range(N):
if (c[i]):
evidence[i] = log(p/(1-p))
else:
... | 5,356,619 |
def start_serving(app_name='mms', args=None):
"""Start service routing.
Parameters
----------
app_name : str
App name to initialize mms service.
args : List of str
Arguments for starting service. By default it is None
and commandline arguments will be used. It should follow
... | 5,356,620 |
def java_fat_library(name=None,
srcs=[],
deps=[],
visibility=None,
tags=[],
resources=[],
source_encoding=None,
warnings=None,
exclusions=[],
... | 5,356,621 |
def _res_dynamics_fwd(
real_input, imag_input,
sin_decay, cos_decay,
real_state, imag_state,
threshold, w_scale, dtype=torch.int32
):
""" """
dtype = torch.int64
device = real_state.device
real_old = (real_state * w_scale).clone().detach().to(dtype).to(device)
imag_old = (imag_state... | 5,356,622 |
def make_json_error(error):
"""
Handle errors by logging and
"""
message = extract_error_message(error)
status_code = extract_status_code(error)
context = extract_context(error)
retryable = extract_retryable(error)
headers = extract_headers(error)
# Flask will not log user exception... | 5,356,623 |
def tokenize_finding(finding):
"""Turn the finding into multiple findings split by whitespace."""
tokenized = set()
tokens = finding.text.split()
cursor = 0
# Note that finding.start and finding.end refer to the location in the overall
# text, but finding.text is just the text for this finding.
for token ... | 5,356,624 |
def main():
"""
Take a folder with mridata.org .h5 files, read them, load to np matrices and save as pickle for convenience
:return: None
"""
file_list = sorted([f for f in os.listdir(f'{data_path}') if f.endswith('h5')])
for f in file_list:
filename = os.path.join(f'{data_path}', f)
... | 5,356,625 |
def gaussian_filter_density(gt):
"""generate ground truth density map
Args:
gt: (height, width), object center is 1.0, otherwise 0.0
Returns:
density map
"""
density = np.zeros(gt.shape, dtype=np.float32)
gt_count = np.count_nonzero(gt)
if gt_count == 0:
return densit... | 5,356,626 |
def RGBfactorstoBaseandRange(
lumrange: list[int, int],
rgbfactors: list[float,
float,
float]):
"""Get base color luminosity and
luminosity range from color
expressed as r, g, b float
values and min and max byte
... | 5,356,627 |
def mean_by_orbit(inst, data_label):
"""Mean of data_label by orbit over Instrument.bounds
Parameters
----------
data_label : string
string identifying data product to be averaged
Returns
-------
mean : pandas Series
simple mean of data_label indexed by start of each orbit
... | 5,356,628 |
def quantile_constraint(
column: str,
quantile: float,
assertion: Callable[[float], bool],
where: Optional[str] = None,
hint: Optional[str] = None,
) -> Constraint:
"""
Runs quantile analysis on the given column and executes the assertion
column:
Column to run the assertion on
... | 5,356,629 |
def test_activate_ruleset(setup, create_deactivated_ruleset, rulesengine_db):
"""
tests activate_ruleset functionality. Requires that setup is run and there is a ruleset inactive.
"""
from src.praxxis.rulesengine import activate_ruleset
from tests.src.praxxis.util import dummy_object
import os
... | 5,356,630 |
def _compute_rank(
kg_embedding_model,
pos_triple,
corrupted_subject_based,
corrupted_object_based,
device,
) -> Tuple[int, int]:
"""
:param kg_embedding_model:
:param pos_triple:
:param corrupted_subject_based:
:param corrupted_object_based:
:param device... | 5,356,631 |
def _get_bool_argument(ctx: ClassDefContext, expr: CallExpr,
name: str, default: bool) -> bool:
"""Return the boolean value for an argument to a call or the
default if it's not found.
"""
attr_value = _get_argument(expr, name)
if attr_value:
ret = ctx.api.parse_bool(at... | 5,356,632 |
def assess_month(pred, valid, skill_name, model_description, lead_time, save_path):
""" Assesses the performance of a model for a given month
Parameters
----------
pred : xr.Dataset
Predictions
valid : xr.Dataset
Observations
skill_name : str
Skill to evaluate
mo... | 5,356,633 |
def validate_filter_parameter(string):
""" Extracts a single filter parameter in name[=value] format """
result = ()
if string:
comps = string.split('=', 1)
if comps[0]:
if len(comps) > 1:
# In the portal, if value textbox is blank we store the value as empty str... | 5,356,634 |
def test_filter_features_multi_point():
"""MultiPoints should be turned into multiple Points"""
features = [
{
"type": "Feature",
"geometry": {
"type": "MultiPoint",
"coordinates": [[0, 0], [1, 0]]
}
}
]
expected = [
... | 5,356,635 |
def delightLearn(configfilename):
"""
:param configfilename:
:return:
"""
threadNum = 0
numThreads = 1
#parse arguments
params = parseParamFile(configfilename, verbose=False)
if threadNum == 0:
logger.info("--- DELIGHT-LEARN ---")
# Read filter coefficients, c... | 5,356,636 |
def ones(distribution, dtype=float):
"""Create a LocalArray filled with ones."""
la = LocalArray(distribution=distribution, dtype=dtype)
la.fill(1)
return la | 5,356,637 |
def stderr(tag, component):
"""Look at the stderr for a map component."""
click.echo(_cli_load(tag).stderr[component]) | 5,356,638 |
def draw_and_save_grid(
mol_list,
names,
subImgSize,
mol_per_row,
filename
):
"""
Draw RDKit molecules and save SVG.
"""
img = Draw.MolsToGridImage(
mol_list,
molsPerRow=mol_per_row,
subImgSize=subImgSize,
legends=names,
useSVG=True
)
... | 5,356,639 |
def reseta_status_e_ofertas_dos_proponentes():
"""
Exclui todos os itens de ofertas de todos os proponentes;
Aplica o status inscritos para os proponentes;
"""
print('### >>> Limpa as ofertas de uniforme')
limpa_ofertas_de_uniforme()
print('### >>> Seta os proponentes com status de inscrito... | 5,356,640 |
def build(target, format, source, output, stringparam, xsl, publication, webwork, diagrams, diagrams_format, only_assets, clean):
"""
Process [TARGET] into format specified by project.ptx.
Also accepts manual command-line options.
For many formats, images coded in source (latex-image, etc) will only be... | 5,356,641 |
def update_podcast_url(video):
"""Query the DDB table for this video. If found, it means
we have a podcast m4a stored in S3. Otherwise, return no
podcast.
"""
try:
response = PODCAST_TABLE_CLIENT.query(
KeyConditionExpression=Key('session').eq(video.session_id) & Key('year').eq(v... | 5,356,642 |
def translate(filename):
"""
File editing handler
"""
if request.method == 'POST':
return save_translation(app, request, filename)
else:
return open_editor_form(app, request, filename) | 5,356,643 |
def read_fileset(fileset):
"""
Extract required data from the sdoss fileset.
"""
feat_data = {
'DATE_OBS': [],
'FEAT_HG_LONG_DEG': [],
'FEAT_HG_LAT_DEG': [],
'FEAT_X_PIX': [],
'FEAT_Y_PIX': [],
'FEAT_AREA_DEG2': [],
'FEAT_FILENAME': []}
for c... | 5,356,644 |
def p_command_print2(p):
"""com : PRINT LPAREN expr RPAREN SEMI_COLON"""
p[0] = ('PRINT',p[3]) | 5,356,645 |
def get_branch_index(edge_index, edge_degree, branch_cutting_frequency=1000):
"""Finds the branch indexes for each branch in the MST.
Parameters
----------
edge_index : array
The node index of the ends of each edge.
edge_degree : array
The degree for the ends of each edge.
branc... | 5,356,646 |
def update_coverage(coverage, path, func, line, status):
"""Add to coverage the coverage status of a single line"""
coverage[path] = coverage.get(path, {})
coverage[path][func] = coverage[path].get(func, {})
coverage[path][func][line] = coverage[path][func].get(line, status)
coverage[path][func][li... | 5,356,647 |
def main(
argv: Optional[list[str]] = None,
*,
stdin=None,
stdout=None,
stderr=None,
):
"""Gada main:
.. code-block:: python
>>> import gada
>>>
>>> # Overwrite "gada/test/testnodes/config.yml" for this test
>>> gada.test_utils.write_testnodes_config({
... | 5,356,648 |
def cross_product(v1, v2):
"""Calculate the cross product of 2 vectors as (x1 * y2 - x2 * y1)."""
return v1.x * v2.y - v2.x * v1.y | 5,356,649 |
def loadData(fname='Unstra.out2.00008.athdf'):
"""load 3d bfield and calc the current density"""
#data=ath.athdf(fname,quantities=['B1','B2','B3'])
time,data=ath.athdf(fname,quantities=['vel1'])
vx = data['vel1']
time,data=ath.athdf(fname,quantities=['vel2'])
vy = data['vel2']
time,data=ath.athdf(fname,qu... | 5,356,650 |
def list():
"""List nonebot builtin drivers."""
search_driver("") | 5,356,651 |
def text_iou(ground_truth: Text, prediction: Text) -> ScalarMetricValue:
"""
Calculates agreement between ground truth and predicted text
"""
return float(prediction.answer == ground_truth.answer) | 5,356,652 |
def divisors(num):
"""
Takes a number and returns all divisors of the number, ordered least to greatest
:param num: int
:return: list (int)
"""
# Fill in the function and change the return statment.
return 0 | 5,356,653 |
def space_oem(*argv):
"""Handle oem files
Usage:
space-oem get <selector>...
space-oem insert (- | <file>)
space-oem compute (- | <selector>...) [options]
space-oem list <selector>... [options]
space-oem purge <selector>... [--until <until>]
space-oem list-tags <... | 5,356,654 |
def pytest_addoption(parser):
"""Describe plugin specified options.
"""
group = parser.getgroup("syslog", "plugin syslog notifier")
group.addoption("--syslog", action="store_true", dest="syslog",
default=False,
help="Enable syslog plugin. %default by default.") | 5,356,655 |
def main():
"""Main entry point of script"""
parser = argparse.ArgumentParser(description='Generate training input')
# Required arguments
parser.add_argument('roads_shp', help='Path to shapefile containing OSM road data')
parser.add_argument('records_csv', help='Path to CSV containing record data')
... | 5,356,656 |
def compare_distance(tree,target):
"""
Checks tree edit distance. Since every node has a unique position, we know that the node is the
same when the positions are the same. Hence, a simple method of counting the number of edits
one needs to do to create the target tree out of a given tree is equal to the number of... | 5,356,657 |
def header(name='peptide'):
"""
Parameters
----------
name
Returns
-------
"""
with open('{}.pdb'.format(name), 'r') as f:
file = f.read()
model = file.find('\nMODEL')
atom = file.find('\nATOM')
if atom < 0:
raise ValueError('no ATOM entries found in... | 5,356,658 |
def test_credit_card_recognizer_with_template(
pii_csv, utterances, dictionary_path, num_of_examples, acceptance_threshold
):
"""
Test credit card recognizer with a dataset generated from
template and a CSV values file
:param pii_csv: input csv file location
:param utterances: template file loca... | 5,356,659 |
def move_tower(disks, from_pole, to_pole, with_pole):
"""
side note, I hate the tower of hanoi and anyone who thinks this should be used
to teach recursion should not be allowed to teach recursion.
if I ever see someone had a pr to do recursion by using itself I would reject it immediately
"""
i... | 5,356,660 |
def test_fst_ap_remove_session_bad_session_id(dev, apdev, test_params):
"""FST AP remove session - bad session id"""
fst_remove_session(apdev, test_params, remove_scenario_bad_session_id, True) | 5,356,661 |
def test_domain_js_xrefs(app, status, warning):
"""Domain objects have correct prefixes when looking up xrefs"""
app.builder.build_all()
def assert_refnode(node, mod_name, prefix, target, reftype=None,
domain='js'):
attributes = {
'refdomain': domain,
... | 5,356,662 |
def isoUTC2datetime(iso):
"""Convert and ISO8601 (UTC only) like string date/time value to a
:obj:`datetime.datetime` object.
:param str iso: ISO8061 string
:rtype: datetime.datetime
"""
formats = ["%Y-%m-%d %H:%M:%S", "%Y-%m-%d %H:%M:%S.%f"]
if 'T' in iso:
formats = ["%Y-%m-%dT%H:%... | 5,356,663 |
def groupstatus(aid: int, state: int = 0) -> EndpointResult:
"""Retrieve anime release status for different groups.
:param aid: anidb anime id
:type aid: int
:param state: release state. int 1 to 6. Example: zenchi.mappings.group_status.ONGOING
:type state: int, optional
:return: a tuple (data,... | 5,356,664 |
def schedule_credit_card_purchase_creation(workspace_id: int, expense_group_ids: List[str]):
"""
Schedule credit card purchase creation
:param expense_group_ids: List of expense group ids
:param workspace_id: workspace id
:return: None
"""
if expense_group_ids:
expense_groups = Expen... | 5,356,665 |
def get_communities_codes(communities, fields=None, community_field='Community'):
"""From the postal code conversion file, select entries for the `communities`.
This function is similar to get_community_codes, but works if
`communities` and `fields` are strings or lists of strings.
"""
if not ... | 5,356,666 |
def GLMFit_(file, designMatrix, mask, outputVBA, outputCon,
fit="Kalman_AR1"):
"""
Call the GLM Fit function with apropriate arguments
Parameters
----------
file
designmatrix
mask
outputVBA
outputCon
fit='Kalman_AR1'
Returns
-------
glm, a vba.VBA ins... | 5,356,667 |
def _load_blocks_txt():
"""Load block name from Blocks.txt."""
with open_unicode_data_file("Blocks.txt") as blocks_txt:
block_ranges = _parse_code_ranges(blocks_txt.read())
for first, last, block_name in block_ranges:
for character_code in xrange(first, last+1):
_block_data[char... | 5,356,668 |
def test_wpas_mesh_open(dev, apdev):
"""wpa_supplicant open MESH network connectivity"""
check_mesh_support(dev[0])
add_open_mesh_network(dev[0], freq="2462", basic_rates="60 120 240")
add_open_mesh_network(dev[1], freq="2462", basic_rates="60 120 240")
check_mesh_joined_connected(dev, connectivity... | 5,356,669 |
def get_stoch_rsi(quotes: Iterable[Quote], rsi_periods: int, stoch_periods: int, signal_periods: int, smooth_periods: int = 1):
"""Get Stochastic RSI calculated.
Stochastic RSI is a Stochastic interpretation of the Relative Strength Index.
Parameters:
`quotes` : Iterable[Quote]
Histori... | 5,356,670 |
def view_client_account(account):
"""Узнать состояние своего счета"""
print(account.full_info())
print(account.show_history()) | 5,356,671 |
def send_syslog(msg):
"""send a log message to AlienVault"""
Config['netsyslogger'].log(syslog.LOG_USER, syslog.LOG_NOTICE, msg, pid=True) | 5,356,672 |
def PUtilHann (inUV, outUV, err, scratch=False):
""" Hanning smooth a UV data set
returns smoothed UV data object
inUV = Python UV object to smooth
Any selection editing and calibration applied before average.
outUV = Predefined UV data if scratch is False, ignored if
scrat... | 5,356,673 |
def test_example_8_22__block_collection_nodes():
"""
Example 8.22. Block Collection Nodes
Expected:
%YAML 1.2
---
!!map {
? !!str "sequence"
: !!seq [
!!str "entry",
!!seq [ !!str "nested" ],
],
? !!str "mapping"
... | 5,356,674 |
def str2bytes(seq):
""" Converts an string to a list of integers """
return map(ord,str(seq)) | 5,356,675 |
def __downloadFilings(cik: str) -> list:
"""Function to download the XML text of listings pages for a given CIK
from the EDGAR database.
Arguments:
cik {str} -- Target CIK.
Returns:
list -- List of page XML, comprising full listing metadata for CIK.
"""
idx = 0 # Curr... | 5,356,676 |
def test_payment_dates_br():
"""
Test routine: payment_dates_br(settle, maturity)
Reference: http://www.tesouro.fazenda.gov.br/documents/10180/258262/NTN-F/1d23ed84-4921-49f4-891b-fececd3115f9
Expected Result:
['01/07/2004',
'01/01/2005',
'01/07/2005',
'01/01/2006',
'01/07/2006'... | 5,356,677 |
def KK_RC43_fit(params, w, t_values):
"""
Kramers-Kronig Function: -RC-
Kristian B. Knudsen (kknu@berkeley.edu / kristianbknudsen@gmail.com)
"""
Rs = params["Rs"]
R1 = params["R1"]
R2 = params["R2"]
R3 = params["R3"]
R4 = params["R4"]
R5 = params["R5"]
R6 = params["R6"]
... | 5,356,678 |
def vconstant(value, length, dtype=None, chunk_size=1024):
"""Creates a virtual column with constant values, which uses 0 memory.
:param value: The value with which to fill the column
:param length: The length of the column, i.e. the number of rows it should contain.
:param dtype: The preferred dtype f... | 5,356,679 |
def getsize(filename):
"""Return the size of a file, reported by os.stat()."""
return os.stat(filename).st_size | 5,356,680 |
def get_all_nsds_of_node(logger, instance):
"""
This function performs "mmlsnsd -X -Y".
Args:
instance (str): instance for which disks are use by filesystem.
region (str): Region of operation
Returns:
all_disk_names (list): Disk names in list format.
... | 5,356,681 |
def gen_color_palette(n: int):
""" Generates a hex color palette of size n, without repeats
and only light colors (easily visible on dark background).
Adapted from code by 3630 TAs Binit Shah and Jerred Chen
Args:
n (int): number of clouds, each cloud gets a unique color
"""
pal... | 5,356,682 |
def absolute_vorticity(u, v, dx, dy, lats, dim_order='yx'):
"""Calculate the absolute vorticity of the horizontal wind.
Parameters
----------
u : (M, N) ndarray
x component of the wind
v : (M, N) ndarray
y component of the wind
dx : float or ndarray
The grid spacing(s) i... | 5,356,683 |
def run(adeg=30,bdeg=15) :
"""
Generate pstricks code for drawing a diagram
to demonstrate the angle addition formulas.
"""
a,b = map(lambda _ : _*pi/180.0, (adeg,bdeg))
ca, cb, cab = map(cos, (a,b,a+b))
sa, sb, sab = map(sin, (a,b,a+b))
#
# Here are the points, vaguely where they s... | 5,356,684 |
def drop_path(input, drop_prob=0.0, training=False, scale_by_keep=True):
"""
Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks).
"""
if drop_prob == 0.0 or not training:
return input
keep_prob = 1 - drop_prob
shape = (input.shape[0],) + (1,) * (input.... | 5,356,685 |
def ask_user_config() -> Dict[str, Any]:
"""
Ask user a few questions to build the configuration.
Interactive questions built using https://github.com/tmbo/questionary
:returns: Dict with keys to put into template
"""
questions: List[Dict[str, Any]] = [
{
"type": "confirm",
... | 5,356,686 |
def generate_menusystem():
""" Generate Top-level Menu Structure (cached for specified timeout) """
return '[%s] Top-level Menu System' % timestamp() | 5,356,687 |
def describe_node_association_status(NodeAssociationStatusToken=None, ServerName=None):
"""
Returns the current status of an existing association or disassociation request.
A ResourceNotFoundException is thrown when no recent association or disassociation request with the specified token is found, or when t... | 5,356,688 |
def main():
""" main loop """
#TODO: enable parallezation to use multiple cores
N = int(1e18)
def sum(N):
start = time.time()
result = 0
for i in range(N):
if i % int(1e9) == 0:
print("** step %i **" % int(i/1e9))
result += i
end ... | 5,356,689 |
async def simple_post(session, url: str, data: dict, timeout: int = 10) -> Optional[dict]:
"""
A simple post function with exception feedback
Args:
session (CommandSession): current session
url (str): post url
data (dict): post data
timeout (int): timeout threshold
Retur... | 5,356,690 |
def test_builder_schema(tmp_path: Path, samples: Path):
"""generate the global ibek schema"""
schema_path = tmp_path / "schema.json"
result = runner.invoke(cli, ["ibek-schema", str(schema_path)])
assert result.exit_code == 0, f"ibek-schema failed with: {result}"
expected = json.loads(open(samples / ... | 5,356,691 |
def test_check_libgmt():
"""
Make sure check_libgmt fails when given a bogus library.
"""
libgmt = FakedLibGMT("/path/to/libgmt.so")
msg = (
# pylint: disable=protected-access
f"Error loading '{libgmt._name}'. "
"Couldn't access function GMT_Create_Session. "
"Ensure ... | 5,356,692 |
def gnomonic_proj(lon, lat, lon0=0, lat0=0):
"""
lon, lat : arrays of the same shape; longitude and latitude
of points to be projected
lon0, lat0: floats, longitude and latitude in radians for
the tangency point
---------------------------
Returns the gnomonic ... | 5,356,693 |
def local_pluggables(pluggable_type):
"""
Accesses pluggable names
Args:
pluggable_type (Union(PluggableType,str)): The pluggable type
Returns:
list[str]: pluggable names
Raises:
AquaError: if the type is not registered
"""
_discover_on_demand()
if isinstance(plu... | 5,356,694 |
async def test_migrator_existing_config(hass, store, hass_storage):
"""Test migrating existing config."""
with patch("os.path.isfile", return_value=True), patch("os.remove") as mock_remove:
data = await storage.async_migrator(
hass, "old-path", store, old_conf_load_func=lambda _: {"old": "co... | 5,356,695 |
def view_folio_contact(request, folio_id=None):
"""
View contact page within folio
"""
folio = get_object_or_404(Folio, pk=folio_id)
if not folio.is_published and folio.author_id != request.user:
return render(
request,
'showcase/folio_is_not_published.html'
... | 5,356,696 |
def faom03(t):
"""
Wrapper for ERFA function ``eraFaom03``.
Parameters
----------
t : double array
Returns
-------
c_retval : double array
Notes
-----
The ERFA documentation is below.
- - - - - - - - - -
e r a F a o m 0 3
- - - - - - - - - -
Fundamental ... | 5,356,697 |
def get_dtindex(interval, begin, end=None):
"""Creates a pandas datetime index for a given interval.
Parameters
----------
interval : str or int
Interval of the datetime index. Integer values will be treated as days.
begin : datetime
Datetime index start date.
end : datetime, op... | 5,356,698 |
def asanyarray(a, dtype=None, order=None):
"""Converts the input to an array, but passes ndarray subclasses through.
Parameters
----------
a : array_like
Input data, in any form that can be converted to an array. This includes scalars,
lists, lists of tuples, tuples, tuples of tuples, t... | 5,356,699 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.