content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def TWM_p(pfreq, pmag, f0c):
"""
Two-way mismatch algorithm for f0 detection (by Beauchamp&Maher)
[better to use the C version of this function: UF_C.twm]
pfreq, pmag: peak frequencies in Hz and magnitudes,
f0c: frequencies of f0 candidates
returns f0, f0Error: fundamental frequency detected and... | 5,304,600 |
def iter_items(rows):
""" """
member_load = {}
for row in rows:
try:
member_load[row[0]].extend(list(row[2:]))
except KeyError:
member_load[row[0]] = list(row[2:])
return member_load | 5,304,601 |
def get_training_strategy():
"""
:return: A training strategy. It could be TPUStrategy if we are running the code in TPUs,
DistributionStrategy if the code is distributed or MirroredStrategy if the code is running
in one machine with more than one GPU. This code expects all the machines to have the same... | 5,304,602 |
def delete_site_survey_image(client: SymphonyClient, survey: SiteSurvey) -> None:
"""This function deletes image from existing site survey.
Args:
survey ( `pyinventory.common.data_class.SiteSurvey` ): site survey object
Raises:
FailedOperationException: on operation failure... | 5,304,603 |
def namespace():
""" clear namespace
"""
NamespaceList = cmds.namespaceInfo(recurse = True,listOnlyNamespaces = True)
if NamespaceList:
NamespaceList.reverse()
for NamespaceName in NamespaceList:
if NamespaceName != 'shared' and NamespaceName != 'UI':
cmd... | 5,304,604 |
def get_file_name(api_token, data_series_list, initial_date, final_date,
api_host=DEFAULT_API_HOST):
"""Combines region, items, and dates to return a string"""
client = GroClient(api_host, api_token)
logger = client.get_logger()
key_words = [client.lookup('regions', data_series_list[0]... | 5,304,605 |
def from_transform(msg):
"""
Convert a `geometry_msgs/Transform` ROS message into a numpy array (4x4
homogeneous transformation).
Parameters
----------
msg: geometry_msgs/Transform
The ROS message to be converted
Returns
-------
array: np.array
The resulting numpy array... | 5,304,606 |
def _validate_target(target, output_shape):
# type: (int, tuple) -> None
"""
Check whether ``target``,
an integer index into the model's output
is valid for the given ``output_shape``.
"""
if isinstance(target, int):
output_nodes = output_shape[1:][0]
if not (0 <= target < o... | 5,304,607 |
def check_opt_value(conf, names):
"""Check if the parameter names and values are valid."""
for name in names:
try:
getattr(conf, name)
except (cfg.NoSuchOptError, cfg.ConfigFileValueError):
with excutils.save_and_reraise_exception():
output_log(MSG.INVALID... | 5,304,608 |
def test_encode_image_as_b64():
"""Tests numpy to string encoding
"""
# ensure im is numpy
assert type(im) == np.ndarray
ans = imEn.encode_image_as_b64(im)
assert type(ans) == str | 5,304,609 |
def _read_character_at(source, pointer):
"""Reads a code point or a backslash-u-escaped code point."""
while pointer < len(source) and source[pointer] == " ":
pointer += 1
if pointer >= len(source):
raise IndexError("pointer %d out of range 0-%d" % (pointer, len(source)))
if source[poi... | 5,304,610 |
def cli(port, username, password, no_auth):
"""CLI for this package."""
from pyhassbian.server import run_server
run_server(port, username, password, no_auth) | 5,304,611 |
def test_timer_each_fall_behind_catch_up(nsproxy):
"""
Test a timer executed periodically and falling behind the period that
catches-up.
If a sequence of events takes longer to run than the time available
before the next event, the repeater will simply fall behind.
If a timer catches-up, then ... | 5,304,612 |
def get_list_of_data(filepath, col_name, geoid=None):
"""Pull a column data from a shape or CSV file.
:filepath: The path to where your data is located.
:col_name: A list of the columns of data you want to grab.
:returns: A list of the data you have specified.
"""
# Checks if you have inputed ... | 5,304,613 |
def waber(lumin, lambdaValue):
"""
Weber's law nspired by Physhilogy experiment.
"""
# lambdaValue normally select 0.6
w = lumin**lambdaValue
#w = (255*np.clip(w,0,1)).astype('uint8')
return(w) | 5,304,614 |
def valid_engine_path(path):
"""
Check if the engine path is valid
"""
path = os.path.normcase(path)
# Check that path is actually there
if not os.path.exists(path):
return False
# Check that is has an engine folder
if not os.path.exists(os.path.join(path,'engine')):
re... | 5,304,615 |
def test_parse_fasta_title_02():
"""It handles a 1 or 2 at the end of the title."""
seq_name, seq_end = blast.parse_fasta_title(
'title1 1 after', 'end_1', '1')
assert seq_name == 'title1'
assert seq_end == '1' | 5,304,616 |
def children(nodes):
"""
Search and list all the nodes childs.
:param nodes: a list with tree nodes
:return: a list with nodes childs
"""
child = []
for node in nodes:
if node.left:
child.append(node.left)
if node.right:
child.append(node.right)
r... | 5,304,617 |
def test_export_nodata(monkeypatch, statsdict):
"""Do not call exportdf() if there are no results"""
measure = stat.CountStore()
measure.start_date = s = Timestamp.now(tz='UTC')
measure.end_date = s + to_timedelta(5, unit='s')
calc = result.Total(statsdict=statsdict, countstore=measure)
called =... | 5,304,618 |
def run(ceph_cluster, **kw):
"""
Prepares the cluster to run rados tests.
Actions Performed:
1. Create a Replicated and Erasure coded pools and write Objects into pools
2. Setup email alerts for sending errors/warnings on the cluster.
Verifies Bugs:
https://bugzilla.redhat.com/show_b... | 5,304,619 |
def network_by_authors(authors):
""" Based a list of authors a network containing authors who
cited on ..
Parameters:
-----------
authors : list
Returns:
-------
network :
"""
# for every author:
dict_author_citer = {}
for item in authors:
citer = fetch_citer_by_author(item)
dict_author_citer[i... | 5,304,620 |
def process_long_strings(lexicon: lex_or_string) -> lex_or_string:
"""Process long strings in the main lexicon.
Strings marked for concatenation are indicated with a leading pipe.
"""
if isinstance(lexicon, str):
if lexicon.startswith("|"):
lexicon = (
# Remove the p... | 5,304,621 |
def component(name, prefix='', folder_name=COMPONENT_DIR, file_type=FILE_TYPE):
"""Get the image for the component of a given name.
prefix- the name of the component's feature (leg, segment, wing)
name- the feature's value
folder_name- the enclosing folder for component images
file_type- the format ... | 5,304,622 |
def deadvertizeFactory(factory_name, glidein_name, factory_collector=DEFAULT_VAL):
"""
Deadvertize all entry and global classads for this factory.
"""
tmpnam = classadSupport.generate_classad_filename(prefix="gfi_de_fact")
# TODO: use tempfile
try:
with open(tmpnam, "w") as fd:
... | 5,304,623 |
def init():
"""Admin Cell CLI module"""
@click.group(
cls=cli.make_commands(
__name__ + '.' + context.GLOBAL.get_profile_name()
)
)
@click.option(
'--cell', required=True,
envvar='TREADMILL_CELL',
is_eager=True, callback=cli.handle_context_opt,
... | 5,304,624 |
def tensor_prod(a, b):
""" Returns the tensor product using lists
"""
product = []
# loop through first tensor/vector
for a_ in a:
row = []
# multiply with each element of second tensor and add to row list
for b_ in b:
row.append(a_ * b_)
# add row lis... | 5,304,625 |
def xblock_view_handler(request, usage_key_string, view_name):
"""
The restful handler for requests for rendered xblock views.
Returns a json object containing two keys:
html: The rendered html of the view
resources: A list of tuples where the first element is the resource hash, and
... | 5,304,626 |
def invoke(request):
"""Where the magic happens..."""
transformed_request = _transform_request(request)
with monitor(labels=_labels, name="invoke"):
data_iter = mx.io.NDArrayIter(transformed_request, None, 1)
response = mod.predict(data_iter)
return _transform_response(response)
wi... | 5,304,627 |
def get_location(stmt):
"""Return the grounded geo-location context associated with a Statement."""
if not has_location(stmt):
loc = None
else:
loc = stmt.context.geo_location.db_refs['GEOID']
return loc | 5,304,628 |
def _convert_version(value):
"""Extract 3 version numbers from 2 bytes"""
# subversion bits 0.3, versin bits 4-7, type bits 8-15
type_ = value // 256
value = value % 256
version = value // 16
subversion = value % 16
return '{}.{}.{}'.format(type_, version, subversion) | 5,304,629 |
def p_funcCall_1(t):
"""
funcCall : ID S_PARIZQ paramsList S_PARDER
"""
t[0] = expression.FunctionCall(t[1], t[3], t.slice[1].lineno, t.slice[1].lexpos) | 5,304,630 |
def var_gaussian(r, levels=5, modified=False):
"""
Returns the Parametric Gaussian VaR of a Series or DataFrame
If modified is True, then the modified VaR is returned
using Cornish-Fisher modifications
"""
# compute the Z score assuming the distribution is Gaussian
z = norm.ppf(levels / 100... | 5,304,631 |
def taylor_green_vortex(x, y, z):
""" Calculates Taylor Green vortex flow velocities. """
A = 0.14
B = A
C = -2 * A
a = 1
b = 1
c = 1
# Position translated to ensure boundary flow is tangential and continuous.
x_p = x + (math.pi / (a * 2))
y_p = y + (math.pi / (a * 2))
z_p ... | 5,304,632 |
def breadcrumbs_list(links):
"""Returns a list of links to render as breadcrumbs inside a <ul> element in a HTML template.
``links`` should be a iterable of tuples (URL, text).
"""
crumbs = ""
li_str = '<li class="breadcrumb-item"><a href="{}">{}</a></li>'
li_str_active = '<li class="breadcrumb-... | 5,304,633 |
def setup(args: Arguments):
"""
Create configs and perform basic setups.
"""
cfg = get_cfg()
add_config(args, cfg)
cfg.merge_from_file(str(args.config_file))
# cfg.merge_from_list(args.opts)
cfg.merge_from_list(switch_extract_mode(args.extract_mode))
cfg.merge_from_list(set_min_max_b... | 5,304,634 |
def store_beam(beam, secret_uuid: str) -> None:
"""Save the beam to a pickle file."""
beam_dir = get_beam_cache_directory()
beam_filename = os.path.join(beam_dir, secret_uuid)
with open(beam_filename, "wb") as pfile:
pickle.dump(beam, pfile, protocol=pickle.HIGHEST_PROTOCOL) | 5,304,635 |
def parse_args():
"""
Parse command-line arguments.
"""
parser = argparse.ArgumentParser('Extract user sessions from log.')
parser.add_argument('input', help='an input file')
parser.add_argument('output', help='an output file')
parser.add_argument('-p', '--protocol', default='6', type=str,
... | 5,304,636 |
def get_lists_in_dir(dir_path):
"""
Function to obtain a list of .jpg files in a directory.
Parameters:
- dir_path: directory for the training images (from camera output)
"""
image_list = []
for filename in glob.glob(dir_path + '/*.jpg'):
image_list.append(filename)
return i... | 5,304,637 |
def get_help_string(unit, brief=False, width=None):
"""
Retrieves the help string from a given refinery unit.
"""
if brief:
return terminalfit(documentation(unit), width=width)
else:
from io import StringIO
from os import environ
try:
environ['RE... | 5,304,638 |
def new_master_yaml(project_name: str):
"""
Subroutine to create yaml file for processing master metadata
ARGS:
project_name :: Name of current project
"""
master_yaml_name = project_name + '_proj.yaml'
proj_yaml_dict = {
'source_folder': '../raw/',
'TS_folder_prefix':... | 5,304,639 |
def suffix(args):
"""
%prog suffix fastqfile CAG
Filter reads based on suffix.
"""
p = OptionParser(suffix.__doc__)
p.set_outfile()
opts, args = p.parse_args(args)
if len(args) != 2:
sys.exit(not p.print_help())
fastqfile, sf = args
fw = must_open(opts.outfile, "w")
... | 5,304,640 |
def get_files_for_package(
dir: str,
allow_git: bool = True,
ignore_patterns: Iterable[str] = (),
) -> Dict[str, PackageFileInfo]:
"""
Get files to package for ad-hoc packaging from the file system.
:param dir: The source directory. Probably a working copy root or similar.
:param allow_git:... | 5,304,641 |
def test_exp():
"""Test exp function behavior."""
strict_compare_waves(None, peng.exp, "exp", "", np.exp) | 5,304,642 |
def suppress_red_green_blue(error: Union[Red, Green, Blue]) -> bool:
"""Suppress Red, Green, and Blue exceptions."""
return True | 5,304,643 |
def exists(env):
"""Check if we're okay to load this builder"""
return MkdocsCommon.detect(env) | 5,304,644 |
def test_len(train):
"""Test if all the elements in `train=(x,y)` the same `shape[0]`
"""
l = train[1].shape[0]
if isinstance(train[0], dict):
for x in train[0].keys():
assert train[0][x].shape[0] == l
elif isinstance(train[0], (list, tuple)):
for x in train[0]:
... | 5,304,645 |
def create_new_band_directory(dest_path, band, folder_count, file_count, band_directory_map):
"""
Update band directory map then delete existing band folder (including contents) and create new one
:param dest_path: path to destination directory
:param band: band name from source directory
:param fo... | 5,304,646 |
def stop():
""" Stop telnet server """
import uos
global server_socket, last_client_socket
uos.dupterm(None)
if server_socket:
server_socket.close()
if last_client_socket:
last_client_socket.close() | 5,304,647 |
def walk_links_for_node(node, callback, direction, obj=None):
"""
Walks the each link from the given node. Raising a StopIteration will terminate the
traversal.
:type node: treestruct.Node
:type callback: (treestruct.Node, treestruct.Node, object) -> ()
:type direction: int
:type obj: Any
... | 5,304,648 |
async def test_power_sensor(hass, power_sensor, integration):
"""Test a power sensor."""
entity_id = "sensor.power_sensor_1_1"
state = hass.states.get(entity_id)
assert state.state == "1200"
assert state.attributes[ATTR_DEVICE_CLASS] == DEVICE_CLASS_POWER
assert state.attributes[ATTR_UNIT_OF_M... | 5,304,649 |
def choroplethmap(ax, region_boundaries, weights, bounding_box,
color_gradient, color_bound=None, opacity=1.0,
coordinate_system='EPSG:3857',
aggregation_type='max',
**extra_contextily_params):
"""
Render region boundari... | 5,304,650 |
def _create_openeye_pdf(molecules: List[Molecule], file_name: str, columns: int):
"""Make the pdf of the molecules using OpenEye."""
from openeye import oechem, oedepict
itf = oechem.OEInterface()
suppress_h = True
rows = 10
cols = columns
ropts = oedepict.OEReportOptions(rows, cols)
r... | 5,304,651 |
def check_match(template, meme, debug=False):
"""
This calculates how similar template is to meme
:param template: File path
:param meme: File path
:param debug: Debug
:return: [-1, Exception] if error, [0, confidence] if all ok
"""
original = cv2.imread(template)
image_to_compare = ... | 5,304,652 |
def overwrite_featuretype(original_ft: FeatureType, custom_ft: FeatureType, editor_form):
""" Overwrites the original data with the custom date
Args:
original_ft (FeatureType): THe original FeatureType object
custom_ft (FeatureType): The custom FeatureType object
editor_form: The editor... | 5,304,653 |
def dialog_create_repository(request):
"""fills the create repository dialog
"""
# nothing is needed
return {
'mode': 'CREATE',
'has_permission': PermissionChecker(request)
} | 5,304,654 |
def external_load_new_pool(request, form_acess, client):
"""
Method to call shared_load_new_pool when use by external way
"""
return facade.shared_load_new_pool(request, client, form_acess, external=True) | 5,304,655 |
def get_config_parser(filepath):
"""Create parser for config file.
:param filepath: Config file path
:type filepath: str
:return: configparser.ConfigParser instance
"""
config_parser = configparser.ConfigParser(interpolation=None)
# use read_file() instead of read() to catch possible OSErro... | 5,304,656 |
def num_concavities(prop, **kwargs):
"""Return the number of concavities for a cell
Args:
prop (skimage.measure.regionprops):
The property information for a cell returned by regionprops
**kwargs:
Arbitrary keyword arguments
Returns:
int:
The numb... | 5,304,657 |
def add_street_network_to_city(city_object, name_list, pos_list, edge_list):
"""
Add street network to city object. Based on street network functions
of uesgraphs.
Parameters
----------
city_object : object
City object of pycity_calc
name_list : list
List of street node name... | 5,304,658 |
def admin_login_req(f):
"""
登录装饰器
"""
@wraps(f)
def decorated_function(*args, **kwargs):
if "admin" not in session:
return redirect(url_for("admin.login", next=request.url))
return f(*args, **kwargs)
return decorated_function | 5,304,659 |
def vec2d(x,y):
"""A vector in 2D vector space"""
return jnp.array([x+0.,y]) | 5,304,660 |
def preview_page_version(request, revision_id):
"""
Returns GET response for specified page preview.
:param request: the request instance.
:param reversion_pk: the page revision ID.
:rtype: django.http.HttpResponse.
"""
revision = get_object_or_404(PageRevision, pk=revision_id)
if not ... | 5,304,661 |
def load_id_map(id_file):
""" Load a ids file in to a barcode -> coordinate dictionary.
"""
id_map = {}
with open(id_file, "r") as fh:
for line in fh:
bc, x, y = line.split("\t")
id_map[bc] = (int(x), int(y))
return id_map | 5,304,662 |
def map_page():
"""
Global strain map shows the locations of all wild isolates
within the SQLite database.
"""
VARS = {'title': "Global Strain Map",
'strain_listing': dump_json(get_strains(known_origin=True))}
return render_template('strain/global_strain_map.html', **VARS) | 5,304,663 |
def database_is_empty_or_contains_kombu_tables(db_url):
"""
Database is empty or contains 2 tables: kombu_message, kombu_queue.
(ref: https://github.com/galaxyproject/galaxy/issues/13689)
"""
with disposing_engine(db_url) as engine:
with engine.connect() as conn:
metadata = MetaD... | 5,304,664 |
def download(startend: tuple[datetime, datetime], site: str, odir: Path, host: str = None, wavelen: str = None) -> list[Path]:
"""
startend: tuple of datetime
"""
if not host:
host = HOST
assert len(startend) == 2
start, end = time_bounds(startend)
parsed = urlparse(host)
ftop... | 5,304,665 |
def get_static_mini_dataset() -> Dataset:
"""Return a collection of 10 documents and their target subjects of 4 different subjects.
Returns
-------
Dataset
the static dataset consisting of 10 documents and 4 subjects
"""
documents = [
Document(uri="uri://test_document1", title="... | 5,304,666 |
def popular_environment_shared(request, client_api):
"""
Method to return environment vip list by finality and client
Param: finality
Param: client
"""
lists = dict()
status_code = None
lists['environments'] = ''
try:
finality = get_param_in_request(request, 'finality')
... | 5,304,667 |
def save_name():
"""Change a users details, most importantly his name."""
user = request.json
store_user(user)
return "I'll try to remember your name, {}!".format(user.get("name")) | 5,304,668 |
def favicon():
"""Return favicon resource."""
return send_from_directory(
os.path.join(app.root_path, 'static'),
'icon.png',
mimetype = 'image/png') | 5,304,669 |
def test_queue_example():
"""Testing Queue Examples."""
print("Exercise 1.3.16 Date Queue: ")
print(read_dates())
print("\n") | 5,304,670 |
def add_l2_weight_decay(loss_fn: base.LossFn,
scale: Union[float, Callable[[hk.Params], hk.Params]],
predicate: Optional[PredicateFn] = None) -> base.LossFn:
"""Adds scale * l2 weight decay to an existing loss function."""
try: # Scale is numeric.
scale = jnp.sqr... | 5,304,671 |
def create_resnet101() -> tf.keras.Model:
"""Create ResNet101
"""
resnet_base = tf.keras.applications.ResNet101(
input_shape=(32,32,3),
weights='imagenet',
pooling='avg',
include_top=False)
# Downloading data from
# https://storage.googleapis.com/tensorflow/keras-app... | 5,304,672 |
def spatial_join_facilities(left,
right,
lid_property,
rid_property,
lsimilarity_properties,
rsimilarity_properties,
similarity_weights=None,
... | 5,304,673 |
def handle_description(update, context):
"""Добавление определенного кол-ва товара в корзину"""
query = update.callback_query
if '/back' == query.data:
return start(update, context)
purchase_id = str(query.data)
purchase_quantity = 1
chat_id = update.effective_message.chat_id
add... | 5,304,674 |
def dereference_json_pointer(root: n.SerializableType, ptr: str) -> Dict[str, Any]:
"""Given a dictionary or list, return the element referred to by the
given JSON pointer (RFC-6901)."""
cursor = root
components = ptr.lstrip("#").lstrip("/").split("/")
for component in components:
compone... | 5,304,675 |
def make_binary_EXEC(path):
"""Force the type of a binary to ET_EXEC (instead of for instance ET_DYN).
This is horrible."""
with open(path, 'rb') as f:
conts = f.read()
conts = conts[:0x10] + '\x02' + conts[0x11:] # e_type = ET_EXEC
with open(path, 'wb') as f:
f.write(conts) | 5,304,676 |
def port_exponential_moving_average(asset_indicator, close_arr, n):
"""Calculate the exponential weighted moving average for the given data.
:param close_arr: close price of the bar, expect series from cudf
:param n: time steps
:return: expoential weighted moving average in cu.Series
"""
EMA = ... | 5,304,677 |
def crop_to(arr: np.ndarray, target_shape: typing.Tuple[int]) -> np.ndarray:
"""
Center-crops an array to a desired shape. If the difference in shapes is not even the offset of the resulting array
will be rounded down, i.e. the removed area "in front" will be smaller than the area "behind" the crop.
Ar... | 5,304,678 |
def expand_related_tasks(tasks: Set[str],
expand_map: Mapping[str, Sequence[str]]) -> Set[str]:
"""The inverse of `collapse_related_tasks`.
Args:
tasks: a list of tasks to expand.
expand_map: map from a collapsed task name to a list of expanded task names.
Returns:
A list of... | 5,304,679 |
def antal_h_coefficient(index, game_matrix):
"""
Returns the H_index coefficient, according to Antal et al. (2009), as given by equation 2.
H_k = \frac{1}{n^2} \sum_{i=1}^{n} \sum_{j=1}^{n} (a_{kj}-a_{jj})
Parameters
----------
index: int
game_matrix: sympy.Matrix
Returns
------... | 5,304,680 |
def test_whitelist():
"""Test correct handling of whitelists for plotting."""
random_state = np.random.RandomState(2)
A2B = random_transform(random_state)
tm = TransformManager()
tm.add_transform("A", "B", A2B)
nodes = tm._whitelisted_nodes(None)
assert_equal({"A", "B"}, nodes)
nodes = ... | 5,304,681 |
def setup_logging(
logger_or_name=None,
logfile=None,
log_to_console=True,
level=logging.INFO
):
"""
Sets up a logger for logging
Args:
logger_or_name: Either a logging.Logger object or a string
used to reference the logger name. If None, root logger is assumed.
l... | 5,304,682 |
def run_evaluation(model_config,
dataset_configs,
make_outputs_fn):
"""Runs model evaluation loop over a set of datasets."""
is_metadataset = False
dataset_info = {name: eval_lib.dataset_with_custom_labels(
model_config, config) for name, config in dataset_configs.items... | 5,304,683 |
def getcertpubhash(certobj):
"""
Method 1: Hash from public key
:param certobj:
:return:
"""
if certobj:
pubkey = certobj.get_pubkey().as_der()
pubkeyhash = hashlib.sha256(pubkey).hexdigest()
return pubkeyhash
else:
return None | 5,304,684 |
def unique(items, key=lambda x: x):
"""
Iterate through unique items in an iterable.
Order is preserved.
"""
seen = set()
for item in items:
if item not in seen:
yield item
seen.add(item) | 5,304,685 |
def greedy_value_per_weight_unit(I: list, w: list, v: list, K: int) -> tuple:
"""
Solve knapsack problem with value per weight unit greedness.
Takes most beneficial first.
Parameters:
-----------
- I : items
- w : items' weights
- v : items' value
- K... | 5,304,686 |
def stop(ctx):
"""Stops the process.
Intended to be used for testing.
"""
raise SystemExit(1) | 5,304,687 |
def _wrap_output_like_matching_units(result, match):
"""Convert result to be like match with matching units for output wrapper."""
output_xarray = isinstance(match, xr.DataArray)
match_units = str(match.metpy.units if output_xarray else getattr(match, 'units', ''))
if isinstance(result, xr.DataArray):
... | 5,304,688 |
def get_mnest_results(root_name, parameters):
"""
Parameters
----------
root_name : str
The directory and base name of the MultiNest output.
parameters : list or array
A list of strings with the parameter names to be displayed.
There should be one name for each parameter in ... | 5,304,689 |
def _get_list_of_test_resources() -> List[Resource]:
"""The subset of all Resources that can be tested
Returns:
List[Resource] -- A list of TesTItems
"""
resources = [
resource
for resource in database.RESOURCES
if database.resources.APP_IN_GALLERY in resource.tags
]... | 5,304,690 |
def set_globals(options_file=None, args=None):
"""
Parses the options in the file specified in the command-line
if no options file is passed.
Args:
options_file (str): an optional file name of an options file
"""
def valid_date(s):
"""
Method to check if the string pass... | 5,304,691 |
def test_cache_expire_in_one_second(mock_time, cache, hub):
"""Test consecutive reads made one second apart ignore the cache."""
hub.read_holding_registers.return_value = [0]
current_time = 1615633800.799
mock_time.return_value = current_time
assert cache.read_holding_registers(50, 70, 1) == [0]
... | 5,304,692 |
def convert_units(
data: Union[tb.BeliefsSeries, pd.Series, List[Union[int, float]], int, float],
from_unit: str,
to_unit: str,
event_resolution: Optional[timedelta] = None,
capacity: Optional[str] = None,
) -> Union[pd.Series, List[Union[int, float]], int, float]:
"""Updates data values to refl... | 5,304,693 |
def add_delta_to_time(timestamp, delta):
"""Utility to add a datetime.timedelta object to a datetime.time one"""
return (
datetime.datetime.combine(datetime.date(2012, 1, 1), timestamp)
+ datetime.timedelta(seconds=delta)
).time() | 5,304,694 |
def raDecFromAltAz(alt, az, obs, includeRefraction=True):
"""
Convert altitude and azimuth to RA and Dec
@param [in] alt is the altitude in degrees. Can be a numpy array or a single value.
@param [in] az is the azimuth in degrees. Cant be a numpy array or a single value.
@param [in] obs is an O... | 5,304,695 |
def _is_convertible_to_tensor(value):
"""Returns true if `value` is convertible to a `Tensor`."""
if value is None:
return True
if isinstance(value,
(ops.Tensor, variables.Variable, np.ndarray, int, float, str)):
return True
elif isinstance(value, (sparse_tensor.SparseTensor,)):
retu... | 5,304,696 |
def add_ball(space, position):
"""Ajoute une balle dans l'espace à une position donnée"""
mass = 1
radius = 14
moment = pymunk.moment_for_circle(mass, 0, radius)
body = pymunk.Body(mass, moment)
body.position = position
shape = pymunk.Circle(body, radius)
space.add(body, shape)
retur... | 5,304,697 |
def add_to_cart_view(request, **kwargs):
"""Add a product to the cart"""
validator = ValidateCart(data=request.data)
validator.is_valid(raise_exception=True)
session_id, queryset = validator.save(request)
return simple_api_response(build_cart_response(queryset, session_id)) | 5,304,698 |
def _cx_to_dict(list_of_dicts: List[Dict], key_tag: str = "k", value_tag: str = "v") -> Dict:
"""Convert a CX list of dictionaries to a flat dictionary."""
return {d[key_tag]: d[value_tag] for d in list_of_dicts} | 5,304,699 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.