content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def visualize_model(model, data, features, labels, error, score):
"""
模型可视化
"""
# 为在Matplotlib中显示中文,设置特殊字体
plt.rcParams['font.sans-serif'] = ['SimHei']
# 创建一个图形框
fig = plt.figure(figsize=(6, 6), dpi=80)
# 在图形框里只画一幅图
ax = fig.add_subplot(111)
# 在Matplotlib中显示中文,需要使用unicode
# 在... | 5,295,600 |
def neg(x: quat) -> quat:
"""
"""
... | 5,295,601 |
def labels_file_reader_factory(labels_file):
"""A factory for generating file readers that can read label files.
Args:
labels_file (str): the file with the labels of the regions
Returns:
LabelsFileReader: the reader for the given file
"""
extension = os.path.splitext(labels_file)[1... | 5,295,602 |
def main():
"""
Runs some search algorithms on some problems.
"""
run_tests_on_eight_puzzle() | 5,295,603 |
def weight_feature_selection(training_features, test_features, training_classes, test_classes, weights):
"""Performs SVM classifaction using best features."""
sorted_features = np.argsort(weights)[::-1]
# Perform features training based on these sorted indices
accuracies = features_training(
... | 5,295,604 |
def _IsNestedSet(field: descriptor.FieldDescriptor) -> bool:
"""If this is a nested field that translates to a set."""
return _IsNestedElement(field, Schema_pb2.ColumnInfo.TYPE_SET) | 5,295,605 |
def get_unit(coordinate):
"""
Get the `unit` identifier of **coordinate**, if **coordinate** has a valid
`unit` identifier appended, else returns `None`.
"""
if isinstance(coordinate, (int, float)):
return None
result = pattern.coordinate.match(coordinate)
if result:
return ... | 5,295,606 |
def GetVnodeLocksSummary(vnode):
""" Internal function to get summary of advisory locks for the given vnode
params: vnode - value representing the vnode object
return: str - formatted output information for the summary of advisory locks
"""
out_str = ''
if vnode:
lockf_list =... | 5,295,607 |
def run_oracle(query=None, execution=''):
""" Connect to the ORACLE database server """
conn = None
res = []
if query is None:
query = 'SELECT * FROM V$VERSION'
try:
# Le parametros de conexao
params = config(filename='apdex.ini', section='oracle')
dbName = params['... | 5,295,608 |
def pct_similarity(results, map_probes_to_genes_first=False, top=None):
""" Read each file in a list and return the percent overlap of their top genes.
See pct_similarity_matrix_raw for calculation details
:param results: a list of paths to tsv-formatted result files or a list of lists of probes for co... | 5,295,609 |
def check_lights_opposite(light_a, light_b):
""" Checks if the two given lights are opposite to each other or not. """
def get_forward_vector(light):
light_vector = light.get_transform().get_forward_vector()
return [light_vector.x, light_vector.y, light_vector.z]
light_a_vector = get_forwar... | 5,295,610 |
def _make_ls5_scene_datasets(geotiffs, tmpdir):
"""
Create directory structures like::
LS5_TM_NBAR_P54_GANBAR01-002_090_084_01
|---scene01
| |----- report.txt
| |----- LS5_TM_NBAR_P54_GANBAR01-002_090_084_01_B10.tif
| |----- LS5_TM_NBAR_P54_GANBAR01-002_090_... | 5,295,611 |
def construct_stimulus(
stim="dc",
duration=6000,
dt=0.1,
stim_amp=0.2,
stim_freq=1,
stim_bias=0,
n_periods=None,
nostim_before=0,
nostim_after=0,
):
"""Constructs a stimulus that can be applied to a model
:param stim: Stimulation type: 'ac':oscillatory stimulus, 'dc': stimp... | 5,295,612 |
def rsc_bounds(rsc_data):
"""Uses the x/y and step data from a .rsc file to generate LatLonBox for .kml"""
north, south, east, west = rsc_nsew(rsc_data)
return {"north": north, "south": south, "east": east, "west": west} | 5,295,613 |
def start_tornado_server(data_dir: pathlib.Path, workflows: Dict[str, workflow.CommonWorkflow]) -> None:
"""
Start Tornado server
:param data_dir: The directory to load interactions configuration from.
:param workflows: The workflows to be used to handle messages.
"""
interactions_config_file = ... | 5,295,614 |
def build_dir():
"""Test build dir for the sphinx compiled docs."""
return tempfile.mkdtemp() | 5,295,615 |
def check_index_bounds(index, size):
"""Validates whether index is an integer and in the list of size. Throws IndexError exception if not."""
if size == 0:
raise IndexError('Size of list is 0 so no indexing is valid')
if index >= 0:
if index >= size:
raise IndexError(
... | 5,295,616 |
async def join(ctx: lightbulb.Context) -> None:
"""Joins the voice channel you are in."""
channel_id = await _join(ctx)
if channel_id:
await ctx.respond(f"Joined <#{channel_id}>") | 5,295,617 |
def interp_ll(x, y, left=None, right=None):
"""Log-log interpolation of 1D data.
x and y are arrays of values. This function returns a function that can be
used to find interpolated or extrapolated values.
If out-of-bounds, left and right indicate the default behaviour. If they
are none, extrapolate; otherwise, ... | 5,295,618 |
def test_binance_query_balances_include_features(function_scope_binance):
"""Test that querying binance balances includes the futures wallet"""
binance = function_scope_binance
with patch.object(binance.session, 'get', side_effect=mock_binance_balance_response):
balances, msg = binance.query_balance... | 5,295,619 |
def tag_edit(tag_id):
"""Edit Tag"""
tag = Tag.get_item_by_id(tag_id)
if tag is None:
abort(404)
else:
if request.method == "POST":
tag.name = request.form["name"]
tag.slug = request.form["slug"]
db.session.add(tag)
db.session.commit()
... | 5,295,620 |
def _get_project_title():
"""Get project title"""
title = None
puts("")
while not title:
title = raw_input("What is the project's full title? (e.g. My awesome project) ")
return title | 5,295,621 |
def test_head_alone():
"""more than two items"""
arg = '"--head"'
out = getoutput(f"db-ls --head")
expected = """Loading the 'bluesky-tutorial-RSOXS' Catalog...\n Starting Time Scan ID UUID\n 2019-11-17 04:28:56 6959 777b44ae"""
assert out.strip() == expected | 5,295,622 |
def pred_hist(df_results_path=f'results/{name}_results.csv', bins=500, show_results=False):
"""
Plot the histogram of predicted values
:param df_results_path: dataframe of results, currently used path by default
:param bins: number of histogram bins, 500 by default
:param show_results: True if resul... | 5,295,623 |
def read_csv_file(file_name):
"""
Given a CSV file, read the data into a nested list
Input: String corresponding to comma-separated CSV file
Output: Nested list consisting of the fields in the CSV file
"""
with open(file_name, newline='') as csv_file: # don't need to explicitly cl... | 5,295,624 |
def asymptomatic_duration_00():
"""
Real Name: b'asymptomatic duration 00'
Original Eqn: b'5'
Units: b'Day'
Limits: (None, None)
Type: constant
b''
"""
return 5 | 5,295,625 |
def get_all_entries(df, pdbid, cdr):
"""
Get all entries of a given PDBID and CDR.
:param df: dataframe.DataFrame
:rtype: pandas.DataFrame
"""
return df[(df['input_tag'].str.contains(pdbid)) & (df['CDR'] == cdr)] | 5,295,626 |
def remove_categories(apps, schema_editor):
"""Remove the activities created by this data migration."""
ServiceCategory = apps.get_model("core", "ServiceCategory")
ServiceCategory.objects.filter(
slug__in=[
"basic-needs",
"health",
"shelter-centers",
"... | 5,295,627 |
def asynchronous(method):
"""Wrap request handler methods with this if they are asynchronous.
This decorator is for callback-style asynchronous methods; for
coroutines, use the ``@gen.coroutine`` decorator without
``@asynchronous``. (It is legal for legacy reasons to use the two
decorators together... | 5,295,628 |
def dynary(x, bases):
"""Represent the integer ``x`` with respect to the 'dynamical' ``bases``.
Gives a way to reliably enumerate and 'de-enumerate' the combination of
all different index values.
Examples
--------
>>> dynary(9, [2, 2, 2, 2]) # binary
[1, 0, 0, 1]
>>> dyna... | 5,295,629 |
def download_from_db() -> BytesIO:
"""
Возвращает байтовый буфер с таблицой бд
в формате xlsx
"""
wb = init_wb()
categories = get_categories_list()
for app in get_applications():
if app[1] in categories[:3]:
wb["1"].append(app)
elif app[1] in categories[3:6] + cat... | 5,295,630 |
def calculate_request_checksum(game, pid, sid):
"""Calculate checksum of payment details to pass to payment API"""
secret_key = get_payment_secret()
checksum_string = CHECKSUM_REQUEST_FORMAT.format(pid, sid, game.price, secret_key)
return calculate_checksum(checksum_string) | 5,295,631 |
def main(source_base, binary_base, num_threads=1):
"""Main entry point of the script."""
print 'Executing test for razers3'
print '==========================='
print
ph = app_tests.TestPathHelper(
source_base, binary_base,
'apps/razers3/tests') # tests dir
# =================... | 5,295,632 |
def encode(input, errors='strict'):
"""Encode unicode as USMARC
"""
if errors not in set(['strict', 'replace', 'ignore']):
raise ValueError("Invalid errors argument %s" % errors)
result = []
rappend = result.append
uget = unicodemap.get
for u in input:
s = uget(u)
if ... | 5,295,633 |
async def observe_is_in_air(pdrone: PDrone, running_tasks):
"""Monitors whether the drone is flying or not and
returns after landing"""
# taken from:
# https://github.com/mavlink/MAVSDK-Python/blob/main/examples/mission.py'
was_in_air = False
async for is_in_air in pdrone.drone.telemetry.in_air... | 5,295,634 |
def has_dask_arrays(dataset):
"""
check whether or not a dataset contains dask arrays
Parameters
----------
dataset : xarray.Dataset
Returns
-------
bool :
True if dask arrays are found
"""
has_dask = False
for varname, var in six.iteritems(dataset.variables):
... | 5,295,635 |
def Put(entities, **kwargs):
"""Store one or more entities in the datastore.
The entities may be new or previously existing. For new entities, Put() will
fill in the app id and key assigned by the datastore.
If the argument is a single Entity, a single Key will be returned. If the
argument is a list of Enti... | 5,295,636 |
def read_multivariate_dataset(root_dir, dataset_name, shot):
""" Read multivariate dataset
"""
X = np.load(os.path.join(root_dir, dataset_name+".npy"), allow_pickle=True)
y = np.loadtxt(os.path.join(root_dir, dataset_name+'_label.txt'))
y = y.astype(np.int64)
dim = X[0].shape[0]
max_length ... | 5,295,637 |
def epoch(session, snake, screen, learning_rate, gen, draw=False):
"""One epoch of snake crawling."""
# generate (by snake) sample points for training
sample_points, labels, which_nodes, dG0_dg, dG0_dT = snake.gen_samples(num_samples=MINI_BATCH_SIZE)
# clip sample points to prevent false data
sampl... | 5,295,638 |
def classify_image(interpreter, image, top_k=1):
"""Returns a sorted array of classification results."""
set_input_tensor(interpreter, image)
interpreter.invoke()
output_details = interpreter.get_output_details()[0]
output = np.squeeze(interpreter.get_tensor(output_details['index']))
# If the model is quan... | 5,295,639 |
def _get_scheme_map(input_encoding, output_encoding):
"""Provides a caching layer on top of `SchemeMap` objects to allow faster
access to scheme maps we've instantiated once.
:param input_encoding: Input encoding. Must be defined in `SCHEMES`.
:param output_encoding: Input encoding. Must be defined in ... | 5,295,640 |
def test_convert_2D(snapshots):
"""
Test that the preprocessing utility to convert to 2D works as expected
Args:
snapshots (np.array): snapshots data
"""
# Do the conversion to 2D and create numpy array
input_shape = (55, 42, 2)
snapshots = convert_2d(snapshots, input_shape, 200)
... | 5,295,641 |
def plot_hist(
targets,
expected_values,
y_pred_upper,
y_pred_lower,
analyzed_metrics=["mse"],
sample_frequency=1,
save_to_disc=False,
fig_title="Error Probability Distribution",
method="method",
bins=10,
):
"""
Create a matplotlib.... | 5,295,642 |
def test_fenced_code_blocks_extra_01a():
"""
Test case extra 01: start a "list block" within a fenced code block
"""
# Arrange
source_markdown = """```
- [foo]:
/url
```
"""
expected_tokens = [
"[fcode-block(1,1):`:3::::::]",
"[text(2,1):- [foo]:\n/url:]",
"[end-fcode-b... | 5,295,643 |
def collect_inst_model_pairs(start=None, stop=None, tinc=None, inst=None,
user=None, password=None, model_files=None,
model_load_rout=None, inst_lon_name=None,
mod_lon_name=None, inst_name=[], mod_name=[],
... | 5,295,644 |
def whl_install(path, dest, *args, pip=None, extra_install_args=None, install_dependencies=False, wait_func=None,
reset_modules=True, contained_modules=None, **kwargs):
"""Import whl or zip files and return the installed module.
Args:
dest (str): Destination path.
path (str): Pa... | 5,295,645 |
def move_folders(source, target):
""" Move all folders to "foldery" folder in new path. """
folders = operations.get_list_of_folders(source)
if folders:
if not os.path.isdir(os.path.join(target, "folders")):
os.mkdir(os.path.join(target, "folders"))
list_of_tuples = [(folder, "f... | 5,295,646 |
def cooling_resource_activator(mdot_kgpers, T_sup_K, T_re_K, limits, cooling_resource_potentials, T_ground_K, prices, lca,
master_to_slave_variables, config, Q_cooling_req, locator):
"""
:param DCN_cooling:
:param Qc_available_from_lake_W:
:type Qc_available_from_lake_W: ... | 5,295,647 |
def process_create_experiment_arguments():
"""
Processing command line arguments for 01_create_experiment script
"""
# defining command line arguments
parser = argparse.ArgumentParser()
# general arguments
parser.add_argument("-d", "--exp_directory", help="Directory where the experiment fo... | 5,295,648 |
def read_v70(fileglob):
"""Reads a location.pytxt sparse 70-vector that describes an extremum."""
files = glob.glob(fileglob)
if len(files) != 1:
raise ValueError('Got %d matches for glob %r: %r' % (
len(files), fileglob, files))
model = distillation.read_distillate_model(files[0])
return numpy.do... | 5,295,649 |
def merge_result(res):
"""
Merges all items in `res` into a list.
This command is used when sending a command to multiple nodes
and they result from each node should be merged into a single list.
"""
if not isinstance(res, dict):
raise ValueError("Value should be of dict type")
re... | 5,295,650 |
def break_strongly_connected(parent, broken_edges, scc):
"""
Breaks strongly connected components. Called recursively until all such
cycles are broken.
Args
----
parent : nx.DiGraph
Directed graph from which the SCCs are drawn.
broken_edges : list
List to which broken e... | 5,295,651 |
def release(version, force=False):
"""Perform a release. Example:
$ fab release:3.0.0
"""
if version.startswith("v"):
abort("Version should not start with 'v'")
version_str = "v%s" % version
clean()
puts(" * Tagging Version %s" % version_str)
force_option = 'f' if force else ... | 5,295,652 |
def verify_service_identity(cert_patterns, obligatory_ids, optional_ids):
"""
Verify whether *cert_patterns* are valid for *obligatory_ids* and
*optional_ids*.
*obligatory_ids* must be both present and match. *optional_ids* must match
if a pattern of the respective type is present.
"""
err... | 5,295,653 |
def cmd_line_renumber(): # pragma: no cover
"""command line interface to bdf_renumber"""
from docopt import docopt
import pyNastran
msg = (
"Usage:\n"
' bdf renumber IN_BDF_FILENAME OUT_BDF_FILENAME [--superelement] [--size SIZE]\n'
' bdf renumber IN_BDF_FILENAME ... | 5,295,654 |
def point_cloud_actor(xyz,
size=100,
color=(0,0,0),
opacity=1):
"""function to make a vtk.vtkActor from a set of xyz points that renders them as spheres
Parameters
----------
xyz : np.array
a Nx3 array of points
size: float o... | 5,295,655 |
def Growth_factor_Linder(omega_m, z, gamma=0.55):
"""
Computes the unnormalised growth factor at redshift z given the present day value of omega_m. Uses the approximation
from Linder2005 with fixed gamma
:param omega_m: the matter density at the present day
:param z: the redshift we want the matter... | 5,295,656 |
def test_parse_runs_piped_function():
"""Parser runs piped function."""
parser = sttp.Parser(template='m> {{ val = re("\\s*\\S+\\s*") | lstrip() }}\n')
assert parser.parse(' foo \n') == {'val': 'foo '} | 5,295,657 |
def get_redis_connection():
""" Get attribute to redis connecion object """
conn = getattr(g, "_redis_connection", None)
if conn is None:
url = current_app.config["REDIS_URL"]
conn = g._redis_connection = redis.from_url(url)
return conn | 5,295,658 |
def _get_block_ins(
instructions: t.Sequence[_Instruction],
co_consts: t.MutableSequence[t.Any],
origin: t.Sequence[int],
target: t.Sequence[int],
origin_i: int # for better error message
) -> t.Generator[_Instruction, None, None]:
"""calculate what instructions are needed to exit/enter a block... | 5,295,659 |
def process(j):
"""Process the json data j"""
if not j["data"]:
print("ERROR: No results found!")
return
with tempfile.NamedTemporaryFile(mode="w", delete=False) as tmpfd:
tmpfd.write(wrap(j["data"][0]["report"]))
for svs in j["data"][0]["svs"]:
tmpfd.write(wrap(... | 5,295,660 |
def _parse_oid_metric(metric):
# type: (OIDMetric) -> MetricParseResult
"""
Parse a fully resolved OID/name metric.
Example:
```
metrics:
- OID: 1.3.6.1.2.1.2.1
name: ifNumber
```
"""
name = metric['name']
oid = OID(metric['OID'])
parsed_symbol_metric = Parse... | 5,295,661 |
def create_progressbar(message, *args, **kwargs):
"""Create the correct progressbar based on availability of interactive shell."""
if 'CI' in os.environ and os.environ['CI']:
kwargs['poll_interval'] = 10
return progressbar.ProgressBar(*args, **kwargs)
# Removing for now to see if it is causing a... | 5,295,662 |
def _parse_additional_json(dir_name: Path) -> Dict[str, Any]:
"""Parse additional json files in the directory."""
additional_json = {}
for filename in dir_name.glob("*.json*"):
key = filename.name.split(".")[0]
if key not in ("custodian", "transformations"):
additional_json[key] ... | 5,295,663 |
def load_iharm(harm_dump_name, gcov, gcon, compute_b=True):
""" does what you expect """
hfp = h5py.File(harm_dump_name,"r")
N1 = hfp["header"]["n1"][()]
N2 = hfp["header"]["n2"][()]
N3 = hfp["header"]["n3"][()]
rho = hfp["prims"][:,:,:,0]
UU = hfp["prims"][:,:,:,1]
U = hfp["prims"][:,:,:,2:5]
... | 5,295,664 |
def check_id(ctx, ulid_id):
"""Verifies a ULID id is in a valid format"""
if ulid_id is None:
ctx.fail('Invalid ID. None is not a valid action ID.')
if len(ulid_id) != 26:
ctx.fail('Invalid ID. ID can only be 26 characters.')
if not ulid_id.isalnum():
ctx.fail('Invalid ID. ID can... | 5,295,665 |
def ensure_vacuum(structure, vacuum):
"""
Adds padding to a slab or 2D material until the desired amount
of vacuum is reached.
Args:
structure (Structure): Structure to add vacuum to
vacuum (float): Final desired vacuum thickness in Angstroms
Returns:
Structure object with v... | 5,295,666 |
def handle_input(sock):
""" Prompt user for message and send it to server """
print("Type messages, enter to send. 'q' to quit")
while True:
msg = input() # Blocks
if msg == 'q':
sock.shutdown(socket.SHUT_RDWR)
sock.close()
break
try:
chat.send_msg(sock, msg) # Blocks until sent
except (BrokenP... | 5,295,667 |
def generateDF(keys, periods=20, amplitudes=[1, 1.5], frequencies=[1/6, 1/2],
ground=0, sample_rate=1e-2):
"""
Генерирует таблицу со столбцами из синусоид с заданным количеством периодов,
случайно изменяющейся амплитудой и случайно изменяющейся частотой.
Параметры:
keys - список ... | 5,295,668 |
def get_file_section_name(section_key, section_label=None):
"""Build a section name as in the config file, given section key and label."""
return section_key + (" {0}".format(section_label) if section_label else "") | 5,295,669 |
def test_benchmark_blend_images_npy(benchmark: Callable[..., Any]) -> None:
"""Benchmark numpy implementation of alpha blending."""
def blend_images(img0: NDArrayByte, img1: NDArrayByte, alpha: float = 0.7) -> NDArrayByte:
"""Alpha-blend two images together using `numpy`.
Args:
img... | 5,295,670 |
def inf_get_cc_size_b(*args):
"""
inf_get_cc_size_b() -> uchar
"""
return _ida_ida.inf_get_cc_size_b(*args) | 5,295,671 |
def resnet18(pretrained=False, progress=True, **kwargs):
"""Constructs a ResNet-18 model.
Args:
pretrained (bool): If True, returns a model pre-trained on ImageNet
progress (bool): If True, displays a progress bar of the download to stderr
"""
return _resnet('resnet18', Distiller... | 5,295,672 |
def _get_test_stats_with_mi(feature_paths):
"""Get stats proto for MI test."""
result = statistics_pb2.DatasetFeatureStatistics()
for feature_path in feature_paths:
feature_proto = text_format.Parse(
"""
custom_stats {
name: "max_sklearn_adjusted_mutual_information"
... | 5,295,673 |
def chist(l):
"""Simple counting histogram. Takes a list of items
and returns a list of (count,object) tuples."""
counts = {}
for c in l:
counts[c] = counts.get(c,0)+1
hist = [(v,k) for k,v in counts.items()]
return sorted(hist,reverse=1) | 5,295,674 |
def FindSrcDirPath():
"""Returns the abs path to the src/ dir of the project."""
src_dir = os.path.dirname(os.path.abspath(__file__))
while os.path.basename(src_dir) != 'src':
src_dir = os.path.normpath(os.path.join(src_dir, os.pardir))
return src_dir | 5,295,675 |
def removeAllAltWCS(hdulist,extlist):
"""
Removes all alternate WCS solutions from the header
"""
original_logging_level = log.level
log.setLevel(logutil.logging.WARNING)
try:
hdr = hdulist[extlist[0]].header
wkeys = altwcs.wcskeys(hdr)
if ' ' in wkeys:
wkeys... | 5,295,676 |
def get_red(slider_value):
"""Turn current slider value for red into a hex value and update color.
The scale value is passed automatically when the scale is moved calling the get_red function."""
global red_value
#Turn the slider value into an int and hex value. Strip leading chars so only two rem... | 5,295,677 |
def select_exercise_and_start_time(bot):
"""
Selects an exercise and start time, and sleeps until the time
period has past.
"""
next_time_interval = select_next_time_interval(bot)
minute_interval = round(next_time_interval / 60, 0)
exercise = select_exercise(bot)
# Announcement String o... | 5,295,678 |
def make_random_constant(name=None, value=None, return_params=False):
"""Make a random Constant value."""
if name is None:
name = random_identifier()
if value is None:
const_type = random.choice([ParamType.FLOAT, ParamType.INT])
if const_type == ParamType.FLOAT:
value = r... | 5,295,679 |
def plot_response_alt(name, env, task, perf, during_training=False, failure=None, FDD=False, broken=False):
"""
plot the response for an altitude task
"""
subplot_indices = {0: [1, 2], 1: [1, 1], 3: [2, 2], 4: [2, 1], 5: [4, 2],
6: [3, 2], 7: [3, 1], 8: [7, 1], 9: [5, 1], 10: [7,... | 5,295,680 |
def recursive_search(path):
"""Perform recursive search for supported measurements"""
path = pathlib.Path(path).resolve()
path_in = []
# Get all candidates
cands1 = list(path.rglob("*")) + [path]
# Exclude all directories with the suffix _dm that contain drymass.cfg
cands2 = []
for c1 in... | 5,295,681 |
def rot_y2alpha(rot_y, x, FOCAL_LENGTH):
"""
Get alpha by rotation_y - theta + 180
rotation_y : Rotation ry around Y-axis in camera coordinates [-pi..pi]
x : Object center x to the camera center (x-W/2), in pixels
alpha : Observation angle of object, ranging [-pi..pi]
"""
alpha = rot_y - np.... | 5,295,682 |
def vis_detections_3DPlus(im, class_name, dets, im_ix, thresh=0.8):
"""Visual debugging of detections."""
import matplotlib.pyplot as plt
im = im[:, :, (2, 1, 0)]
for i in xrange(np.minimum(10, dets.shape[0])):
bbox = dets[i, :4]
score = dets[i, 4]
azimuth = dets[i, 5]
if... | 5,295,683 |
def psi2name(psi, scale=fine_scale):
"""Map single `psi` value to Wentworth bin name."""
for name, upper_psi in scale[:-1]:
if psi <= upper_psi:
return name
return scale[-1][0] | 5,295,684 |
def download_video_files(
video_metadata,
local_video_directory='./videos',
video_filename_extension='mp4',
download_workers=4,
):
"""
Downloads videos from S3 to local directory tree and returns metadata with
local path information added.
Videos are specified as a list of dictionaries,... | 5,295,685 |
def cloud_motion_fast(im1,im2,mask1=None, mask2=None,ratio=0.7, threads=1):
"""
Determine cloud motion
Input: Images and masks for two frames
Output: Cloud motion vector, and max correlation
"""
####use this routine if the inputs are raw images
ny,nx=im2.shape
# if im1.dtype == ... | 5,295,686 |
def get_demo_by_guid(guid):
"""
Retrieve a demo from the ERP system by guid.
:param guid: The demo's guid.
:return: An instance of the Demo.
"""
# Create and format request to ERP
url = '%s/api/v1/Demos/findByGuid/%s' % (get_service_url('lw-erp'), guid)
headers = {'cache-con... | 5,295,687 |
def preprocess_skeleton_frame(joint_collection, is_15_joint: bool, is_cad: bool = False,
to_edge: bool = True,
to_rotate: bool = False,
is_25_joint: bool = False) -> _np.ndarray:
"""Applies re-ordering, orientation standardzin... | 5,295,688 |
def test_wf_3(plugin_dask_opt):
""" testing None value for an input"""
wf = Workflow(name="wf_3", input_spec=["x", "y"])
wf.add(fun_addvar_none(name="addvar", a=wf.lzin.x, b=wf.lzin.y))
wf.add(add2(name="add2", x=wf.addvar.lzout.out))
wf.set_output([("out", wf.add2.lzout.out)])
wf.inputs.x = 2
... | 5,295,689 |
def apply_patch(doc, patch, in_place=False):
"""Apply list of patches to specified json document.
:param doc: Document object.
:type doc: dict
:param patch: JSON patch as list of dicts or raw JSON-encoded string.
:type patch: list or str
:param in_place: While :const:`True` patch will modify ... | 5,295,690 |
def _gt_mapping(D, W, Z):
"""Computes the mapping B(X) for a Guttman transform V X = B(X) Z."""
# Compute the Euclidean distances between all pairs of points
Dz = distance.cdist(Z, Z)
# Fill the diagonal of Dz, because *we don't want a division by zero*
np.fill_diagonal(Dz, 1e-5)
B = - W * D / ... | 5,295,691 |
def schema(_request):
"""API schema"""
return JSONResponse({
'/': 'api root'
}) | 5,295,692 |
def cvar_historic(r, level =5):
"""
Computes the Conditional VaR of series or Dataframe
"""
if isinstance(r, pd.Series):
is_beyond = r <= -var_historic(r, level = level)
return -r[is_beyond].mean()
elif isinstance(r, pd.DataFrame):
return r.aggregate(cvar_historic, le... | 5,295,693 |
def excepting(selector, handler_fn):
"""
Selector is not necessarily just an `Exception` subclass.
Potentially it can be an id for any purpose, not just exception handling.
It also can be an iterable of these things to register general
handlers.
"""
def decorator(task):
task_meta =... | 5,295,694 |
def test_temperature_offset_degc(value):
"""
Test if the TemperatureOffset() type works as expected for different values.
"""
result = Scd4xTemperatureOffsetDegC(value.get('degrees_celsius'))
assert type(result) is Scd4xTemperatureOffsetDegC
assert type(result.ticks) is int
assert result.tic... | 5,295,695 |
def load_data(name, path=None):
"""
Load data using either pickle or numpy's load function.
Parameters
----------
name: str
Name of file to load.
path: None, str or list(str), optional (default=None)
Absolute path or subfolder hierarchy where the file is located.
If None... | 5,295,696 |
def add_check_theta_generator(measure):
"""
This is a decorator to add a ValueError to a function if theta is not in the proper interval.
"""
include_0 = True
include_1 = True
measure = measure.upper()
# Should 0 be included
if measure in select_names(['PPV', 'FDR', 'MCC', 'MK', 'FM']):
... | 5,295,697 |
def get_function_id(functions_client: functions.FunctionsManagementClient,
app_id: str, function_name: str) -> str:
"""
Identifies function ID by its name
:param functions_client: OCI Functions client
:param app_id: OCI Functions app ID
:param function_name: OCI Functions functio... | 5,295,698 |
def init_graphic_environment(screen_width=background_width, screen_height=background_height):
"""
Initialize the graphic environment.
:param screen_width: width of the screen.
:param screen_height: height of the screen.
:return: the screen, the backgrounds and the font.
"""
pygame.ini... | 5,295,699 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.