content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def _decode_and_center_crop(image_bytes, image_size):
"""Crops to center of image with padding then scales image_size."""
shape = tf.io.extract_jpeg_shape(image_bytes)
image_height = shape[0]
image_width = shape[1]
padded_center_crop_size = tf.cast(
((image_size / (image_size + CROP_PADDING)) *
tf.c... | e5bc7bf88912b4110d9de7fddcdfec6d1782fb40 | 3,604,500 |
from typing import List
def get_entity_attributes(entity: dict) -> List[str]:
"""Get a list with the attributes of the entity.
Args:
entity(:obj:`dict`): entity.
Returns:
list: containing the attributes.
"""
keys = entity.keys()
not_attributes = ["id", "type"]
attributes ... | a5482a679ff5060d2deb26d7af6f4dc7fe394bf5 | 3,604,501 |
from typing import Optional
def _shrink2(
xx: np.ndarray,
resampling: str = "nearest",
nodata: Optional[NodataType] = None,
axis: int = 0,
):
"""
:param xx: Image to shrink
:param resampling: Resampling strategy to use
:param nodata: nodata value for missing value fill
:param axis:... | 34e68be0fe63bf402acf78a696c5fec45f99185a | 3,604,502 |
import os
def check_path(path):
"""Prevent users from breaking out of the files/ directory."""
path = os.path.normpath(path)
comp = path.split(os.path.sep)
return (not os.path.isabs(path) and
not any(map(hidden, comp)) and
not '..' in comp) | ffad1b2f5baac5a1612384e5badad5cd1041f1e0 | 3,604,503 |
def fahrenheitToRankie(fahrenheit:float, ndigits = 2)->float:
"""
Convert a given value from Fahrenheit to Rankine and round it to 2 decimal places.
Wikipedia reference: https://en.wikipedia.org/wiki/Fahrenheit
Wikipedia reference: https://en.wikipedia.org/wiki/Rankine_scale
"""
return round(flo... | feea06edfbc800fbb4da6a3a128b2a89f07966ed | 3,604,504 |
from typing import Callable
def _call_method_from_namespace(obj: Callable, method_name: str, namespace: Namespace):
"""Call the method, retrieved from obj, with the correct arguments via
the namespace
Args:
obj: any kind of object
method_name: method to be called
namespace: an arg... | 1810e48919eea30a50bb7406123e1a90c6a51233 | 3,604,505 |
def period2omega(period):
"""
Convert Period (days) to Omega (OmegaSun)
"""
period = period << u.d
OmegaSun = u.def_unit(r'\Omega_\odot', 2.6*1e-6*u.Hz)
return ((2.*np.pi/(period.to(u.s))) << OmegaSun).value | f029a57f6d2cc554423baf3561bf554bbe7278ef | 3,604,506 |
def _build_notehead_stem_pairs(noteheads, stems, flags8=None, flags16=None):
"""
Combines list of noteheads and a list of stems into a list of
canvas items. Handles flipping when stem points down.
"""
items = []
for i, h in enumerate(noteheads):
if len(stems[i].inlinks) > 1:
... | b31f193f0c65a264054c291f85b8e67b145c6903 | 3,604,507 |
def connect(H, G, Gout=None, Hin=None):
"""
Connect outputs Gout of G to inputs Hin of H. The outputs and inputs of
the connected system are arranged as follows:
- remaining outputs of G get lower, the outputs of H the higher indices
- inputs of G get the lower, remaining inputs of H the hi... | c5a6bbf86ec9da5daf006a5e1dc3de1f8140e45f | 3,604,508 |
def get_summary_link(layout, reduced_chain_link_dict, name):
"""
<Purpose>
Merges the materials of the first step (as mentioned in the layout)
and the products of the last step and returns a new link.
This link reports the materials and products and summarizes the
overall software supply chain.
... | 2cc688bedd915cc60d20aae4c58addf392409dc4 | 3,604,509 |
import fsspec
from typing import Mapping
def get_prefix_time_mapping(
fs: fsspec.AbstractFileSystem, url: str
) -> Mapping[str, cftime.DatetimeJulian]:
"""Return a dictionary mapping restart file prefixes to times
Args:
fs: fsspec filesystem object
url: url to the run-directory
Return... | 1ceb0946d62f3967664fb72498e07b09df56ca79 | 3,604,510 |
import uuid
def generate_event_uuid():
""" Generate the identifier of the event (FaaS)
Returns:
str: the event identifier
"""
return str(uuid.uuid4()).replace('-', '') | e982f3699b9a0ee78676a74ed31095534a4ca24b | 3,604,511 |
import os
import csv
def update_archive_csv_by_df(archive_csv_filename, new_df):
"""Parameters:
archive_csv_filename: file name to open and add data to
new_df: dataframe to verify and add to existing file
Purpose:
To have clean, de-duplicated data store in this file
based on th... | 2b6453aefd8cc6bbc27d0b976117e1cfc32a1989 | 3,604,512 |
def X(qubit: QubitDesignator) -> Gate:
"""Produces the X ("NOT") gate::
X = [[0, 1],
[1, 0]]
This gate is a single qubit X-gate.
:param qubit: The qubit apply the gate to.
:returns: A Gate object.
"""
return Gate(name="X", params=[], qubits=[unpack_qubit(qubit)]) | 3765599becc4403971389539b920a17e1863885e | 3,604,513 |
def factorial(x):
"""Return the factorial of a given number."""
if x == 1:
return 1
else:
return factorial(x-1) * x | a1c3adacf122c1bec57bbbfd246f07bf627febcd | 3,604,514 |
def R313(a,b,c, degrees=False):
"""Returns a rotation matrix based on: Z(c)*X(b)*Z(a)"""
if degrees:
a *= deg2rad
b *= deg2rad
c *= deg2rad
s3 = np.sin(c); c3 = np.cos(c)
s2 = np.sin(b); c2 = np.cos(b)
s1 = np.sin(a); c1 = np.cos(a)
# return np.array(
# [
# ... | 9c8f1958c82c1bb02f75ce2647d47008deeb501f | 3,604,515 |
def roi_size(roi):
"""
returns number of cols and rows
"""
cols = roi[1][0] - roi[0][0] + 1
rows = roi[1][1] - roi[0][1] + 1
return cols, rows | caa9213399d9672aa9f23380c7f79db1b42cfa12 | 3,604,516 |
import re
def _remove_decorators(source_code: str, decorator_name: str = "to_document") -> str:
"""Function to remove all 'to_document' decorator
Parameters
----------
source_code : str
The source code
OPTIONAL[decorator_name] : str
The name of decorator to remove
Default: "to_document"
Returns
-----... | b8b59e18784a5d4c6c3fa0146c72fc68dd7b3343 | 3,604,517 |
def integration_checksums(
flight,
configuration,
sql = None,
engine = None,
df = None,
entity_set_names = None,
check_random_n_entity_sets = None
):
"""
For a given list of entity sets, checks the number of unique pk values in source data against those integrated
The list o... | 3541ac477de80f8c65224600a817436de847c198 | 3,604,518 |
import zlib
import pickle
import hashlib
def encode_data(data):
"""Turn `data` into a hash and an encoded string, suitable for use with `decode_data`."""
text = zlib.compress(pickle.dumps(data, 0)).encode('base64').replace('\n', '')
m = hashlib.md5(settings.SECRET_KEY + text).hexdigest()[:12]
return m... | 9a3b8abd04b9267b0d838ff50ba84142e7da6798 | 3,604,519 |
def _forecast_vars(steps, ma_coefs, sig_u):
"""_forecast_vars function used by VECMResults. Note that the definition
of the local variable covs is the same as in VARProcess and as such it
differs from the one in VARResults!
Parameters
----------
steps
ma_coefs
sig_u
Returns
---... | 14c838d5205fecbc4d23dcac2c9b4ab1e04e8a0e | 3,604,520 |
def jointImgTo3D(sample):
"""
Normalize sample to metric 3D
:param sample: joints in (x,y,z) with x,y in image coordinates and z in mm
:return: normalized joints in mm
"""
ret = np.zeros((3,), np.float32)
# convert to metric using f
ret[0] = (sample[0] - ux) * sample[2] / fx
ret[1] =... | ef91b87b9faf165e6d02811798034a495e8fe443 | 3,604,521 |
from pathlib import Path
def is_file_suffix(filename, suffixes, check_exist=True):
"""
is_file + check for suffix
:param filename: pathlike object
:param suffixes: tuple of possible suffixes
:param check_exist: whether to check the file's existence
:return: bool
"""
if check_exist and ... | e1e81eb0c39c991586097882c728535829acf415 | 3,604,522 |
from dask import array as da
from dask.base import tokenize
from typing import Any
from typing import Optional
from typing import Tuple
def to_rgba(
ds: Any,
bands: Optional[Tuple[str, str, str]] = None,
*,
vmin: Optional[float] = None,
vmax: Optional[float] = None,
) -> xr.DataArray:
"""
... | ebcc89505cff9b6778132c0b059e5258719397be | 3,604,523 |
def exu(x, weight, bias):
"""ExU hidden unit modification."""
return tf.exp(weight) * (x - bias) | 26fa33def7b4f78b1f141ebef85f47a242977b54 | 3,604,524 |
def cachefor(name):
"""Decorator to register a function as computing the cache for a set"""
def decorator(func):
assert name not in cachefuncs
cachefuncs[name] = func
return func
return decorator | de5a8419f3406069cdd0388d164e13b588f10f17 | 3,604,525 |
def room2blocks(data, label, num_point, block_size=1.0, stride=1.0,
random_sample=False, sample_num=None, sample_aug=1):
""" Prepare block training data.
Args:
data: N x 6 numpy array, 012 are XYZ in meters, 345 are RGB in [0,1]
assumes the data is shifted (min point is origi... | b22b2b153d70010d98e082a6f2cff668d0c547c3 | 3,604,526 |
def build_vector_batch(vectors, dtype):
"""
Return batch of vectors.
>>> from nutsml.datautil import shapestr
>>> vectors = [np.array([1,2,3]), np.array([2, 3, 4])]
>>> batch = build_vector_batch(vectors, 'uint8')
>>> shapestr(batch)
'2x3'
>>> batch
array([[1, 2, 3],
[2,... | 14f130cfce6eede3f2ffb0f76616c168f0af082a | 3,604,527 |
from typing import Callable
import tqdm
import time
def experiment(method: str, step_size: float, num_steps: int, num_samples: int, proposal: Callable, randomize_steps: bool) -> np.ndarray:
"""Experiment to examine the use of different integrators for sampling from the
Fitzhugh-Nagumo posterior distribution. ... | 8e5f39c8f4d5fb0e6a3a0823c32e95c8a482f304 | 3,604,528 |
import json
def read_users(db):
""" Return a dictionary of textids mapping to tuples
(User object, Cell values) """
user_filter = 'user.delete_time IS NULL AND user.id != 1'
db.execute('''SELECT
user.id,
user.email,
user.user_name,
user.display_name,
user.... | 627bdc577340791c489b840e889c01ed34c4ac60 | 3,604,529 |
from typing import List
import logging
import os
def get_jobs_for_url_or_path(path_or_url: str, settings: Settings) -> List[str]:
"""Returns a list of Game URLs for a given itch.io URL or file."""
path_or_url = path_or_url.strip()
if path_or_url.startswith("http://"):
logging.info("HTTP link prov... | f46f0c8ea8fc52a3fcb1cc4dfbd0d6e5250d68a2 | 3,604,530 |
import shutil
def cmd_exists(cmd):
"""Returns True if a binary exists on
the system path"""
return shutil.which(cmd) is not None | 0d43181532b9b71cb06b6a5d1f207bbb19899129 | 3,604,531 |
def read_viewpoint_quats(f):
"""Reads viewpoint qauternion from file
Args:
f (string): Path to the .mat file
Returns:
dict: A dictionary of viewpoint quaternions, indexed by the class id number.
"""
vp_data = loadmat(f)
vpq = vp_data['viewpoints']['quaternion'][0][0]
quat_di... | c9e8607f98ad36c3e5290b96f8a3bad6f774e6a3 | 3,604,532 |
import requests
def get_swapi_resource(url, params=None):
"""This function initiates an HTTP GET request to the SWAPI service in order to return a
representation of a resource. The function defines two parameters, the resource url (str) and
an optional params (dict) query string of key:value pairs may be ... | 3a5de57fc498da1e25de4f2b3e61cae8508ad7c7 | 3,604,533 |
def svm_accuracy_in_euc_space_params(X, labels, params, folds=3):
"""SVM classifier accuracy in an Euclidean Space.
Args:
X (np.ndarray): The data array.
labels (list, np.ndarray): The data labels.
params (dict): Dictionary of parameters and its values.
folds (int): Amount of fo... | f5ae96a642b3025168e8eaad7cb522a784d323f5 | 3,604,534 |
def get_user_categories(user: User):
"""
Retrieves a User's Categories.
:param user: A User
:return: A list of a User's Categories
"""
return Category.categories.filter(user_storage__id=user.id).order_by('name') | 253f53b3788133d49e80fe58ca725d5ab97c9249 | 3,604,535 |
def _normalize_results(inputs, outputs, results, return_rank1=False):
"""normalize_results() does standard return value handling for
a given set of ufunc actual parameters and results. Ufunc inputs
are assumed to be arrays or scalars, ufunc outputs can be arrays
or unspecified, and ufunc "preliminary r... | aa187e4e294afb847261e968e02910e9aa60a3f5 | 3,604,536 |
def assertify(text):
"""Wraps text in the (assert )."""
return '(assert ' + text + ')' | da7af0fe5d27759d8cef4589843796bee8e74383 | 3,604,537 |
def remove_nodata_records(df_records, nodata_value=-999):
"""
Read a numpy record array and remove nodata records.
Parameters
----------
df_records: pandas dataframe
A pandas dataframe type containing values extracted from env variables.
nodata_value : int, float, np.nan
A int, ... | 5523bad6bde93ef2b425110b37696d07e43ad6de | 3,604,538 |
def get_config(config_file_path):
"""
:param config_file_path:
:return:
"""
return parse_config_utils.Config(config_path=config_file_path) | 8f4f717c14d44de586dd567564e2379d8e10ffa7 | 3,604,539 |
def create_uniform_layer(
num_components, component_fn, combiner_fn, router_fn):
"""Creates a layer of components with the same architecture and router.
Args:
num_components: (int) number of components.
component_fn: function that creates a new component.
combiner_fn: function that creates a combin... | 780dbe32b404c7dd45192439a96b91a48bf67929 | 3,604,540 |
import time
def wait_for_services(cloud_name, host=None, service=None, admin_up_only=True, retries=18, timeout=10, **kwargs):
"""Ensure the service is up and running on specified host.
:param host: name of a host where service is running
:param admin_up_only: do not check status for admin disa... | 9f831e12f54522e328a5b184620380e356dd7558 | 3,604,541 |
import sys
def WaitFor(poller, operation_ref, message,
pre_start_sleep_ms=1000,
max_retrials=None,
max_wait_ms=1800000,
exponential_sleep_multiplier=1.4,
jitter_ms=1000,
wait_ceiling_ms=180000,
sleep_ms=2000):
"""Waits with retrues ... | 3c130f134f45d65e85436ce56aca920f4d4536f1 | 3,604,542 |
import PIL
def resize_image(img:PIL.Image, size:int)->PIL.Image:
""" resize PIL-image """
w, h = img.size
if w == size and h == size: return img
else: return img.resize((size, size), PIL.Image.BICUBIC) | d9548e12730b0972803ed7a0e485a65b1cc07db2 | 3,604,543 |
import os
def thermacc(year, Csp, nn=60, Kvar=2.45, Tunit='deg.C', path=None, tbl=True):
"""
Thermal-acclimation -- The acclimation of corals to their potentially
varying thermal environments. This function corrects for the effects of the
thermal boundary layer if enabled. Otherwise, the thermal-accli... | 058c3e66c9c754ac8e778596b5b311d6cedbf1d2 | 3,604,544 |
def find_resp_subject(subj, RESP):
"""Find if there is one matching subject in RESPECT database based on
the channel names"""
matching_subj = []
sessions = [x for x in subj.list_sessions() if x.name == 'IEMU']
for sess in sessions:
for chan in sess.list_channels():
matched = find... | 897d72c16d87a7b44c5a03673725de0a4c91ea57 | 3,604,545 |
from finitestate.common.aws.secrets import get_secret
from finitestate.common.db.get_pg_session import setup_session
import os
import urllib
def get_db_session(connect_timeout=5):
""" Returns a db_session for current status_tracker PostgreSQL database, default connection timeout 5 seconds """
REGION = os.env... | 875288543ec7f560c0713db4634eb58710e049b8 | 3,604,546 |
def mjed_from_tdb(tdb):
"""Modified Julian Ephemeris Date from TDB seconds."""
return tdb/86400. + MJED_OF_J2000 | 95c20b0838fd0e9a89f44581c215cc8cb0f6a89c | 3,604,547 |
def deseasonalize(ts):
""" removing monthly mean climatology """
dt_year = (ts.time[12]-ts.time[0]).values #
ts_ds = ts.copy()
yrly = ts.groupby_bins('time', np.arange(0,len(ts.time)+1,12)/12*dt_year, right=False).mean(dim='time').rename({'time_bins':'time'})
for j in range(12):
m = ts.isel... | b97ac236ebafb21544b9e5ff620af4403e38e1a2 | 3,604,548 |
def load_variable(checkpoint_dir, name):
"""See `tf.contrib.framework.load_variable`."""
return checkpoint_utils.load_variable(checkpoint_dir, name) | cf0ad703242287f85cd3399beb167bfc6dc4305f | 3,604,549 |
from typing import Optional
def parse_json_and_match_value(line: str, value: str) -> Optional[LogType]:
"""Parse a line as JSON log and check if it a valid log."""
log = parse_json(line)
if log:
key = "logbook_type"
if key not in log or log[key] != value:
log = None
return ... | 5468995f710aa5691a45a49fcfbd0c58db53df87 | 3,604,550 |
def get_images_from_multi_tiff(path, nb_img=False):
"""
Import .tif file from a given path and convert it to a 3d np.array where
the first dimension represent the image index.
Parameters
----------
path : str
.tif file path.
the tif file must carry only 2d arrays of the same dim... | d5b28dfbe1816098eb538d42c5847edc6f44c87a | 3,604,551 |
def test_print_validate_tuple():
"""
Feature: JIT Fallback
Description: Support print.
Expectation: No exception.
"""
@ms_function
def print_func():
x = Tensor(np.array([1, 2, 3, 4, 5]))
y = Tensor(np.array([1, 2, 3, 4, 5]))
tensor_sum = x + y
print("tensor_su... | f4100d80ff6526cd4848f47ba571ab103ff23410 | 3,604,552 |
def about_time(all_df):
"""
elapsed time
remaining time
Note: remaining time not collected anymore!
"""
# time_list = [all_df['elapsed'].iloc[-1], all_df['remaining_time'].iloc[-1]]
time_list = [all_df['elapsed'].iloc[-1], None]
if len(time_list) != 2:
print("***len(time_list): ... | 780a426c05ed8484796d718ca1aabaec1b648d03 | 3,604,553 |
def remove_repository(s3_client, bucket, prefix):
"""Remove a P2 repository from a prefix on an S3 bucket
:param s3_client Boto s3_client object to apply
:param bucket: Bucket to remove from
:param prefix: Prefix at which to remove the repository
:return: True if repository was removed, else False
... | d23a54195751a4ccfbe77a7fb099a8d4743bb83a | 3,604,554 |
import typing
def func_pq_annotate(*, p: "3" = "p", q="q") -> typing.Tuple:
"""func.
Parameters
----------
p, q: str, optional
Returns
-------
p, q: str
"""
return None, None, None, None, None, p, q, None | c65555a391e05248aecec5abcce6b6d0c60ef3ec | 3,604,555 |
def multi_row_selector(table, keyword, value_list,
row_selector=None, **kwargs):
"""Returns lists of indices into a table, one list per value of `keyword`
Parameters
----------
table : `~astropy.table.Table`
Usually a `ccdproc.ImageFileCollection.summary`, hence the use
... | d5de585afe3f97355dded18a59d3ec60576b55ee | 3,604,556 |
import requests
from bs4 import BeautifulSoup
def commitstrip_scraper():
"""
Filenames are in an javascript object on the mainpage.
"""
try:
except ModuleNotFoundError:
raise CartoonError("Packages for scraping not installed. Install requests and beautifulsoup4. "
... | 815d7684f9bec00a5d3bc376bc69f9eca3a38320 | 3,604,557 |
def invert_instruction(f, args):
"""
Transform a parsed instruction into its inverse
"""
if f in (swap_position, swap_char, move):
args.reverse()
elif f == rotate:
args[0] = -args[0]
elif f == rotate_position:
f = rotate_position_inverse
return f, args | 132ce0996daa26f0e69eccc1f86e1e3ac92ae800 | 3,604,558 |
import os
def get_file_name(file):
"""
Return a file name of path.
Keyword arguments:
file -- The string of file path
"""
return os.path.splitext(os.path.basename(file))[0] | 2590e6c90061ce37f8325776a038ce3770be1fe2 | 3,604,559 |
def new_fountain():
"""
Drinking from the fountain makes the player stronger.
"""
fountain = Composite()
set_dungeon_feature_components(fountain)
fountain.set_child(Description("Fountain",
("A Fountain full of clean water",
"... | 6640ce957517c425961581a22617a6f4b13ac505 | 3,604,560 |
def _chunk_outline(chunk: ChunkData) -> np.ndarray:
"""Return the line verts that outline this single chunk.
Parameters
----------
chunk : ChunkData
Create outline of this chunk.
Return
------
np.ndarray
The chunk verts for a line drawn with the 'segments' mode.
"""
... | fb8db1c4c1bb2cc95a9701e48733cb4b6c3abb2a | 3,604,561 |
def shuffle(batches):
"""Shuffle the data.
This method groups the batches together in pairs and within each pair shuffles
the data between the two members.
Args:
batches (List[Tuple[ObjectID, ObjectID]]): This is a list of tuples, where
each tuple consists of two object IDs. The first component is a... | 8180bf3f972f9206d7fa0b0e2deb1ffe175df98d | 3,604,562 |
import logging
def create_network(batch_size, update_freq):
"""Create a linear regression network for performing SVRG optimization.
:return: an instance of mx.io.NDArrayIter
:return: an instance of mx.mod.svrgmodule for performing SVRG optimization
"""
head = '%(asctime)-15s %(message)s'
loggi... | fb878f4f796a195b4e1c258f5742d034b7c272c2 | 3,604,563 |
def bubble_sort(items):
"""Sort given items by swapping adjacent items that are out of order, and
repeating until all items are in sorted order.
Running time: O(n**2) because it passes through n/2 (on average) elements
n-1 times, which simplifies to n elements n times, n**2
Memory usage: O(1), a... | 88748e0d552f0d08e228049f12268e34aed4907b | 3,604,564 |
import numbers
def is_special_slice(key) -> bool:
"""Does the key contain a list, ndarray, or logical ndarray?
"""
# Slices and int-like numbers are fine.
for elem in to_tuple(key):
if not (isinstance(elem, (numbers.Number, slice)) or np.isscalar(elem)):
return True
return Fal... | e7d5888002048472688f0f491b684d68fbd5014d | 3,604,565 |
def human_list(_list) -> str:
"""Convert a list of items into 'a, b or c'"""
last_item = _list.pop()
result = ", ".join(_list)
return "%s or %s" % (result, last_item) | 04ee703d1878ac7602ba33aaf1831ccc188ee9e2 | 3,604,566 |
import os
import sys
import traceback
import time
def run_rmsynth(data, polyOrd=3, phiMax_radm2=None, dPhi_radm2=None,
nSamples=10.0, weightType="variance", fitRMSF=False,
noStokesI=False, phiNoise_radm2=1e6, nBits=32, showPlots=False,
debug=False, verbose=False, log=pr... | 37b385ec4d354b742abea7023b5028135f7baab2 | 3,604,567 |
import base64
import io
def preprocess(data):
"""
This method decodes base64 encoded image, resizes it to 299 x 299 shape,
and turns it into tensor digestable by the model
"""
decoded_image = base64.b64decode(data);
image = Image.open(io.BytesIO(decoded_image));
resized_image = image.res... | ecfc2efa8f68a1263e94f7457e2ced9289b10774 | 3,604,568 |
import logging
def recluster(particles, Rjet,jetdef_tree):
"""Recluster the jet constituents"""
# Recluster the jet constituents and access the clustering history
#set up our jet definition and a jet selector
if jetdef_tree=='antikt':
tree_jet_def = fj.JetDefinition(fj.antikt_algorithm, Rjet)
... | 85196c3c477328570c06f61bfb8d7f8fc3b33efd | 3,604,569 |
def netcsf2sql(file_name: str, rootgrp: Dataset, xr_file, force_save_db):
"""_summary_
Args:
file_name (str): _description_
rootgrp (Dataset): _description_
Returns:
bool: _description_
"""
error = False
for name in settings.vars:
try:
tempc = rootgr... | 391a779526be9b70f9222aa1fb69bf4a40869032 | 3,604,570 |
def segment_mean(x, segment_ids):
"""
Computes the mean along segments of a tensor.
Parameters
----------
x : tensor
The tensor to segment_mean. Should have real numeric type.
segment_ids : tensor
A 1-D tensor whose size is equal to the size of data's first dimension. Values sho... | 232800aad718554162a48d4b5d418d5b4e18879a | 3,604,571 |
def compute_distances_squared(xi1, xi2):
"""
Return matrix of squared Euclidian distance between all pairs of points in d-dimensions.
Args:
xi1 (ndarray): Sample locations in d-dimensions, shape `(n1, d)`.
xi2 (ndarray): Sample locations in d-dimensions, shape `(n2, d)`.
Return:
out (ndarray): Shape `(n1... | 7177e0a08bf09257b1e8402040c8a8d7e6e2884e | 3,604,572 |
def is_unique_chars_v2(str):
"""
Let N be the string length
Dictionary construction: O(N); d[k] = v is O(1), done N times
Containment check: O(N)
=> O(N) time
=> O(N) space
"""
chars_map = defaultdict(int)
for char in str:
chars_map[char] += 1
return 2 not in chars_map.va... | 256bab14de37f9a1a86e6f2354085d4936382fff | 3,604,573 |
def get_session_detail_list_for_recover(session_list):
"""
根据集群名称列表,查询补全详细的信息("cluster_group", "cluster_label", "cluster_name", "version")
:param session_list: 集群名称列表
:return:
"""
session_detail_list = []
for cluster_name in session_list:
res = ResourceCenterHelper.get_cluster_info(
... | 5566892541d4214e7321aaaf120b9b5e5f810ec2 | 3,604,574 |
def mixup(
alpha,
beta,
sample_1,
label_1,
*,
sample_2=None,
label_2=None,
repeat=1,
shuffle=True
):
""" The interface of mixup functions.
"""
if sample_2 is None:
return _mixup_samples(
alpha, beta, sample_1, label_1, sample_1, label_1, repeat, shuffl... | 3a704fe0ca3bc054accafc5f544c9146bf9d2df4 | 3,604,575 |
def operate(id, event, qstate, qdata):
"""
Perform action on pending query. Accepts a new query, or work on pending
query.
You have to set qstate.ext_state on exit. The state informs unbound about
result and controls the following states.
Parameters:
id - module identifier (integer)
... | 368687808b53c92e6346af26ebbf457815676f87 | 3,604,576 |
def readOpenMMReporterFile(reporter_file):
"""
Creates a dictionary containing all the entries in the reported data reporter_file
Parameters
----------
reporter_file : str
Path to the reporter output file
"""
with open(reporter_file, 'r') as ef:
lines = ef.readlines()
... | 9f7d3c958ef82994764f276bdd854868099c7960 | 3,604,577 |
def run_parallel(workflow, n_threads):
"""Run a workflow in parallel threads.
:param workflow: Workflow or PromisedObject to evaluate.
:param n_threads: number of threads to use (in addition to the scheduler).
:returns: evaluated workflow.
"""
scheduler = Scheduler()
threaded_worker = Queue... | 0aa3674a3a964a130c21d64a08cd21592eda3492 | 3,604,578 |
def parse_chain(chain_desc):
"""Parse user input chain
assign id to each nf and group nf by location
assgin offloadability to each nf
"""
global nf_offlodability
nf_id = 0
cur_location = None
cur_group = None
nf_groups = {}
for nf in chain_desc:
# assign id first
... | 925463a29789ce2fee118ba4a90691604cc3223c | 3,604,579 |
def sobel_fg_alpha(idepth, beta=5.0):
"""Computes foreground alpha with sobel edges.
Alphas will be low when there are strong sobel edges.
Args:
idepth: [B, H, W, 1] inverse depth tensor.
beta: (float) Higher the beta, higher the sensitivity to the idepth edges.
Returns:
alpha: [B, H, W, 1] alpha... | 4eab004f66d301f778cf453b7d939dcd8c8aa3b1 | 3,604,580 |
def hat_3d(xi):
"""
Converts a 3D twist to its corresponding 4x4 matrix representation
Args:
xi - (6,) ndarray: the 3D twist
Returns:
xi_hat - (4,4) ndarray: the corresponding 4x4 matrix
"""
if not xi.shape == (6,):
raise TypeError('xi must be a 6-vector')
xi_hat =... | 932074306716e933cd557f57a6f9809c34332abb | 3,604,581 |
def colourise(value, colour, condition=None):
"""Colour a piece of text. If a condition callback is passed in, the text will only be
coloured if the condition is met.
"""
if condition is not None:
if not condition(value):
return str(value)
return f"{colour}{value}{Fore.RESET}" | e70af19a68a049ff4a4b680c1547417dc89ff4a2 | 3,604,582 |
def get_cohort_by_name(course_key, name):
"""
Return the CourseUserGroup object for the given cohort. Raises DoesNotExist
it isn't present.
"""
return CourseUserGroup.objects.get(
course_id=course_key,
group_type=CourseUserGroup.COHORT,
name=name
) | d29170ec078a58e56d77b2daee76c7be03a35bf5 | 3,604,583 |
from typing import List
from typing import Optional
from typing import Dict
def merge_records_gnss(
records_gnss_list: List[Optional[kapture.RecordsGnss]],
sensor_mappings: List[Dict[str, str]]) -> kapture.RecordsGnss:
"""
Merge several gnss records list into one list with new identifiers for ... | 1bc128662172691c44c48bec90a639f51900c496 | 3,604,584 |
import math
def attention(query, key, value, mask=None, dropout=None):
"""Compute 'Scaled Dot Product Attention.
Inputs:
- query: [batch_size, num_heads, num_objects, feat_dim]
- key: [batch_size, num_heads, num_objects, feat_dim]
- value: [batch_size, num_heads, num_objects, feat_dim]
- m... | 9718f8f75629cb46072df1f721e8ce32c561531e | 3,604,585 |
import logging
import subprocess
def start_process(args, input_string='', env=None, cwd=None, stdout=None,
stderr=None):
"""Starts a subprocess like subprocess.Popen, but is threadsafe.
The value of input_string is passed to stdin of the subprocess, which is then
closed.
Args:
args: A ... | c279860375a133786a4f27d57d48e2bde346bffd | 3,604,586 |
def make_random_walks(dataset, k, L):
"""Computes random walks."""
cfg = {
'walker-name': 'uniform',
'args': {'walk_length': L, 'num_walks': k}
}
graph = to_undirected(dataset['graph'])
walker = ng_walkers.make_walker(cfg)
rws = ng_rw_util.precompute_rws_par(
g=graph,
... | e7c3928c539beb298bec0f2eb67ab610935f0a17 | 3,604,587 |
import inspect
def full_class_name(cls):
"""Returns the full qualified name of given class."""
assert isinstance(cls, type)
return inspect.getmodule(cls).__name__ + '.' + cls.__name__ | 876ced2ab0aa95af6d1a71f37c7c70da5ac8d5bf | 3,604,588 |
def form_node_label_prediction_matrix(y_pred, y_test):
"""
Given the discriminator distances, this function forms the node-label prediction matrix.
It is assumed that the number of true labels is known.
Inputs: - y_pred: A NumPy array that contains the distance from the discriminator for each label f... | ccfe961dbc744dc85c5ea9e586e825383b1e48b4 | 3,604,589 |
from typing import List
def check_pool_exist(pool: str, region: str) -> bool:
""" Check that we have slaves in the provided pool and region
"""
system_paasta_config = load_system_paasta_config()
expected_slave_attributes = system_paasta_config.get_expected_slave_attributes()
if expected_slave_attr... | 1f159ada404dd67aa00a7dcf419571249c030036 | 3,604,590 |
from typing import Optional
def get_databases(opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetDatabasesResult:
"""
## Example Usage
```python
import pulumi
import pulumi_snowflake as snowflake
this = snowflake.get_databases()
```
"""
__args__ = dict()
if opts is N... | 0aef42b26a6b25d1b63edc1fab98613f3c3387e2 | 3,604,591 |
import os
def load_excel_centerline(basedirCenterline, vol, ptcode, ctcode, filename=None):
""" Load centerline data from excel
Centerline exported from Terarecon; X Y Z coordinates in colums
"""
if filename is None:
filename = '{}_{}_centerline.xlsx'.format(ptcode,ctcode)
excel_location =... | 59d01ad9c3756fb2ea44f8c61b4d93f25d843aa9 | 3,604,592 |
from typing import Callable
from typing import Optional
import pathlib
from typing import Sequence
import logging
import torch
import pprint
def maybe_launch(
main: Callable,
*,
exp_root: Optional[pathlib.Path],
overrides: Sequence[str],
cfg: pathlib.Path,
mode: util.ModeType,
adhoc: bool ... | e985a3088e63974fc0326b3def7a39f30aed45d0 | 3,604,593 |
from typing import Optional
def estimate_high_probability_upper_bound_bias(
reward: np.ndarray,
iw: np.ndarray,
iw_hat: np.ndarray,
q_hat: Optional[np.ndarray] = None,
delta: float = 0.05,
) -> float:
"""Helper to estimate a high probability upper bound of bias in OPE.
Parameters
----... | b5639db126029f0f24c641c39b443cd64e3aed99 | 3,604,594 |
def error_handler(error):
"""
Logs errors and renders specific, if available, or generic error page
"""
# For 4XX and 5XX level HTTP errors, save specific info
if isinstance(error, HTTPException):
code = error.code
description = error.get_description(request.environ)
name = ... | 16ba9672058555602e8b1eba4d5c08f31a704066 | 3,604,595 |
def compute_lr(
cv_in_2d_front: np.ndarray,
lr_2d_previous: np.ndarray,
disp: int,
p1_in_1d: np.ndarray,
p2_in_1d: np.ndarray,
current_segm_1d: np.ndarray,
previous_segm_1d: np.ndarray,
):
"""
Compute Lr of current plane, at a given disparity
:param cv_in_2d_front: cost volume
... | a78f5c14a8a77dead230aa7f75b53c4b06789e98 | 3,604,596 |
import typing
def ssub(s1: SliceRangeT, *rest: typing.Iterable[SliceRangeT]) -> SliceRangeSeqT:
"""Subtracts n >= 1 ranges"""
res = (s1,)
for i, el2 in enumerate(rest):
res1 = ()
for el1 in res:
res1 += ssub2(el1, el2)
res = res1
return res | eb1ea275e7cd58172ad3ee3a60605cda211e6d82 | 3,604,597 |
def logout(request, next_page=None,
template_name='myregistration/logged_out.html',
redirect_field_name=REDIRECT_FIELD_NAME,
current_app=None, extra_context=None):
"""
Logs out the user and displays 'You are logged out' message.
"""
auth_logout(request)
if next_page... | 4b2b4cf98a3c1fc8ccc658ea7ee33290622dc942 | 3,604,598 |
def make_response_409() -> jsonify(): # Conflict
"""This method is used to return request params related errors. Missing params or misspelling error handled"""
response_msg: dict = {
"Server Message": "The request could not be completed due to a conflict with the current state of the resource."
}
... | d548cccfb1aef3c0f4e1de45b98f05e7f8b4eb8c | 3,604,599 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.