content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def get_segment_library_list(instrument, detector, filt,
library_path, pupil='CLEAR'):
"""Given an instrument and filter name along with the path of
the PSF library, find the appropriate 18 segment PSF library files.
Parameters
-----------
instrument : str
Name ... | 73,500 |
def test_validate_passcode_fail():
"""Assert that passcode can be validate."""
pass_code: str = '111111111'
hashed_pass_code: str = passcode.passcode_hash(pass_code)
checked_pass_code: str = '222222222'
validated: bool = passcode.validate_passcode(checked_pass_code, hashed_pass_code)
assert not ... | 73,501 |
def resize(mat, width, height):
"""
Resize the input image to width x height
:param mat: input image
:param width: new width
:param height: new height
:return: resized image
"""
return cv2.resize(mat, (width, height)) | 73,502 |
def read_write_star(file, mics_to_remove, line_range, star_column_num, output_fname) :
""" Open a .star file and read it line-by-line. Evaluate each line with conditional functions.
============================================
PARAMETERS:
============================================
... | 73,503 |
def stockout_box_pack_api(order_id):
"""
包裹信息, 有明细行
post req:
{
lines: [
{sku, qty_pack}
]
}
"""
box = None
if request.method == 'POST':
order = Stockout.query.t_query.filter_by(id=order_id).with_for_update().first()
lines ... | 73,504 |
def create_model(google_colab, n_features):
"""Creates Keras model"""
LSTM_ = CuDNNLSTM if google_colab else LSTM
inputs = Input(shape=(None, n_features))
x = Conv1D(
filters=32,
kernel_size=16,
padding="same",
kernel_initializer="he_uniform",
)(inputs)
x = Batc... | 73,505 |
def get_hash_command(client: Client, args: dict) -> CommandResults:
"""
Get hash reputation.
Removed hash classification since SentinelOne has deprecated it - Breaking BC.
"""
hash_ = args.get('hash')
type_ = get_hash_type(hash_)
if type_ == 'Unknown':
raise DemistoException('Enter a... | 73,506 |
def map_color(color: Optional[str]) -> Color:
"""Maps color onto Nozbe color"""
colors = list(list(Color.allowed_values.values())[0].values())
colors.remove("null")
return Color(color if color in colors else random.choice(colors)) | 73,507 |
def transform_labels_into_names(labels, entity_idx_to_name):
"""
Trasform a list of number labels to the related names of characters
:param labels:
:param entity_idx_to_name:
:return: list of names labels
"""
names_labels = []
for label in labels:
if label < len(entity_idx_to_nam... | 73,508 |
def validate_alert_report_type_arguments(args: Dict[str, Any], params: Dict[str, Any]) -> Dict[str, Any]:
"""
Validates the arguments required for alert details report type from input arguments of reports command.
Will raise ValueError if inappropriate input given.
:param args: Input arguments
:par... | 73,509 |
def laplacian(csgraph, normed=False, return_diag=False, use_out_degree=False,
*, copy=True):
"""
Return the Laplacian matrix of a directed graph.
Parameters
----------
csgraph : array_like or sparse matrix, 2 dimensions
compressed-sparse graph, with shape (N, N).
normed : ... | 73,510 |
def individual_amalgamate(subitem, past_subitem, create_subitem, ys1):
""" amalgamate the individual items. Recurse when needed. """
try:
if subitem['name'] != past_subitem['name']:
pass
else:
create_subitem['children'].append(subitem['children'][0])
past_subi... | 73,511 |
def interpolated_acf(times, fluxes, cadences=None):
"""
Calculate the autocorrelation function after interpolating over
missing times and fluxes.
Parameters
----------
times : numpy.ndarray
Incomplete but otherwise uniformly sampled times
fluxes : numpy.ndarray
Flux for each... | 73,512 |
def _transformer(
emb_dim=512,
num_heads=8,
num_layers=6,
qkv_dim=512,
mlp_dim=2048,
dropout_rate=None,
attention_dropout_rate=None,
nonlinearity='gelu',
):
"""Transformer config."""
configs = {
'models.build_transformer_config.emb_dim': emb_dim,
'models.build_transformer... | 73,513 |
def run():
"""Requirements for Task 1F"""
#Build list of all stations
stations_list = build_station_list()
#find stations with inconsistent data
stations = inconsistent_typical_range_stations(stations_list)
#keep the names of the stations and delete all other information
stations = [statio... | 73,514 |
def get_vpc_list():
"""获取所有的vpc信息"""
s = get_aws_session(**settings.get("aws_key"))
clients = s.client("ec2")
resp_dict = clients.describe_vpcs()
vpc_list = resp_dict.get("Vpcs")
return vpc_list | 73,515 |
def get_package_path(repodir, packagename):
""" Return the path to an individual package file. """
return os.path.join(repodir, PACKAGESDIR, packagename) | 73,516 |
def cd(new_dir: str) -> Generator:
"""Context manager allowing an operation to be performed inside given directory.
Args:
new_dir: the directory to move into
"""
prev_dir = os.getcwd()
os.chdir(os.path.expanduser(new_dir))
try:
yield
finally:
os.chdir(prev_dir) | 73,517 |
def make_bank_act_tp_data(ctif_tp):
"""
生成银行账号种类
:param ctif_tp: 主体类型
:return: 账号类型
"""
if ctif_tp == "1":
act_tp = random.choice(["02", "03"])
elif ctif_tp == "2":
act_tp = random.choice(["01", "03"])
else:
raise TypeError("ctif_tp={}类型错误!".format(ctif_tp))
... | 73,518 |
def v70_from_params_asdict(v70_from_params):
"""Converts a sparse `v70_from_params` array to a dict."""
dict_v70_from_params = {}
for i in range(v70_from_params.shape[0]):
for j in range(v70_from_params.shape[1]):
v = v70_from_params[i, j]
if v:
dict_v70_from_params[(i, j)] = str(v)
retu... | 73,519 |
def _validate_arguments(parser, args):
"""Validate command line arguments.
Arguments:
parser -- argument parser (type: argparse.ArgumentParser)
args -- arguments (type: argparse.Namespace)
Raise:
ValueError -- If the times in args.data, args.summary or args.graph
are not in ... | 73,520 |
def open_r(filename):
"""Open a file for reading with encoding utf-8 in text mode."""
return open(filename, 'r', encoding='utf-8') | 73,521 |
def get_current_kernel_release():
"""
Get the release of the current kernel as a string.
"""
return api.current_actor().configuration.kernel.split('-')[1] | 73,522 |
def genetic_algorithm_optimizer(starting_path, cost_func, new_path_func, pop_size, generations):
"""Selects best path from set of coordinates by randomly joining two sets of coordinates
Arguments:
starting_path -- List of coordinates, e.g. [(0,0), (1,1)]
cost_func -- Optimization metric calculator,... | 73,523 |
def solve(service_name, api_key):
""" Get and solve CAPTCHA """
# init captcha solver
solver = CaptchaSolver(service_name, api_key)
# make a session, update headers and proxies
session = requests.Session()
session.headers.update({
'User-Agent': USER_AGENT,
})
session.proxies.up... | 73,524 |
def test_blob_value():
"""
Test BLOB values.
"""
lib.backup_and_restore(
lambda context: put_values(lib.SET, "key", BLOB_VALUES),
None,
lambda context: check_values(lib.SET, "key", BLOB_VALUES)
) | 73,525 |
async def test_flow_entry_config_entry_already_exists():
"""Test that create data from user input and config_entry already exists.
Test when the form should show when user puts existing name
in the config gui. Then the form should show with error
"""
hass = Mock()
flow = config_flow.IpmaFlowHan... | 73,526 |
def setup_platform(hass, config, add_devices, discovery_info=None):
"""Set up DLNA DMR platform."""
if discovery_info and \
'upnp_device_type' in discovery_info and \
discovery_info['upnp_device_type'] != UPNP_DEVICE_MEDIA_RENDERER:
_LOGGER.debug('Device is not a MediaRenderer: %s',
... | 73,527 |
def _check_empty(key, value, empty):
"""
if empty is False and value does not exist assert error
if empty is True and value exists assert error
"""
if not empty and not value:
raise Exception("{} is empty, expecting a value".format(key))
elif empty and value:
raise Exception(
... | 73,528 |
def get_a_mock_request_packet_and_raw():
"""Returns a tuple of mock (IncomingPacket, REQID, RegisterResponse message)"""
reqid = REQID.generate()
message = mock_protobuf.get_mock_register_response()
pkt = convert_to_incoming_packet(reqid, message)
return pkt, reqid, message | 73,529 |
def _settingFileList():
"""
Get list of setting files from settings folder.
"""
ret = []
files = [f for f in os.listdir(os.path.dirname(__file__))
if os.path.isfile(os.path.join(os.path.dirname(__file__), f))]
for f in files:
if f.endswith(Global.settingFileExtention):
... | 73,530 |
def test_atomic_duration_max_exclusive_3_nistxml_sv_iv_atomic_duration_max_exclusive_4_4(mode, save_output, output_format):
"""
Type atomic/duration is restricted by facet maxExclusive with value
P1983Y12M12DT16H37M58S.
"""
assert_bindings(
schema="nistData/atomic/duration/Schema+Instance/NI... | 73,531 |
def all_gather(data):
"""
Run all_gather on arbitrary picklable data (not necessarily tensors).
Args:
data: any picklable object
group: a torch process group. By default, will use a group which
contains all ranks on gloo backend.
Returns:
list[data]: list of data gath... | 73,532 |
def random_transform(random_state=np.random.RandomState(0)):
"""Generate random transform.
Each component of the translation will be sampled from
:math:`\mathcal{N}(\mu=0, \sigma=1)`.
Parameters
----------
random_state : np.random.RandomState, optional (default: random seed 0)
Random n... | 73,533 |
def normalize_frequency_locations(samples, Kmax=None):
"""
This function normalize the samples locations between [-0.5; 0.5[ for
the non-cartesian case
Parameters:
-----------
samples: np.ndarray
Unnormalized samples
Kmax: float
Maximum Frequency of the samples locations is ... | 73,534 |
def max_value(uncert_val):
"""Maximum confidence interval for a ufloat quantity."""
return uncert_val.nominal_value + uncert_val.std_dev | 73,535 |
def get_shear_meas_config():
"""get config info for shear measurement"""
# simulation and measurement config stuff
try:
from config import SWAP12
except ImportError:
SWAP12 = False
try:
from config import CUT_INTERP
except ImportError:
CUT_INTERP = False
# s... | 73,536 |
def load_labels_schema():
"""Loads the label json schema file
:return: json schema
"""
json_schema = {}
with open(label_schema_json, "r") as schema_file:
json_schema = json.load(schema_file)
return json_schema | 73,537 |
def run(argv=None):
"""The main function which creates the pipeline and runs it."""
parser = argparse.ArgumentParser()
# Here we add some specific command line arguments we expect. Specifically
# we have the input file to load and the output table to write to.
parser.add_argument(
'--input... | 73,538 |
def _parabolic_interpolation(y_frames):
"""Piecewise parabolic interpolation for yin and pyin.
Parameters
----------
y_frames : np.ndarray [shape=(frame_length, n_frames)]
framed audio time series.
Returns
-------
parabolic_shifts : np.ndarray [shape=(frame_length, n_frames)]
... | 73,539 |
def create_api():
"""
Create API with auth info provided in keys.txt
Return and log relevant errors.
"""
auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)
auth.set_access_token(ACCESS_KEY, ACCESS_SECRET)
api = tweepy.API(
auth, wait_on_rate_limit=True, wait_on_rate_limit_noti... | 73,540 |
def exp(h, Omega):
"""
:param h: steglengde
:param Omega: matrise med vinkelhastigheter
:return: exp(h*Omega) etter definisjonen i likning (21) i oppgaven
"""
I = np.identity(3, dtype=np.double)
omega = np.sqrt(Omega[2, 1] ** 2 + Omega[0, 2] ** 2 + Omega[1, 0] ** 1)
return (
I
... | 73,541 |
def compute_mae(vec1, vec2):
"""
vec1, vec2 is torch.Tensor
"""
vec1 = vec1.reshape(-1, vec1.shape[-1])
vec2 = vec2.reshape(-1, vec2.shape[-1])
if vec2.shape[-1] == 2 and vec1.shape[-1] == 3:
vec1 = vec1[..., :2] / torch.norm(vec1[..., :2], dim=-1, keepdim=True)
if vec2.shape[-1] =... | 73,542 |
def get_refresh_view():
""" Returns a Token Refresh CBV without a circular import """
from rest_framework_simplejwt.settings import api_settings as jwt_settings
from rest_framework_simplejwt.views import TokenRefreshView
class RefreshViewWithCookieSupport(TokenRefreshView):
serializer_cla... | 73,543 |
def prepend_protocol(url: str) -> str:
"""Prefix a URL with a protocol schema if not present
Args:
url (str)
Returns:
str
"""
if '://' not in url:
url = 'https://' + url
return url | 73,544 |
def mechFileRestore():
"""Use this function to restore the original mechanism files supplied."""
#get directory path of package
print("\nRestoring original mechanism files...\n")
direc = os.path.dirname(os.path.abspath(__file__))
opath = os.path.join(direc,"originals")
npath = os.path.join(direc... | 73,545 |
def jackknife_errors(data_input, weights_input, bins, num_sub_samps):
"""Returns the jackknife resampling errors for the estimation of histogram
bar height, for the provided weighted data and bin edges.
Parameters
----------
data : numpy.ndarray
Input first-passage time data.
weights: n... | 73,546 |
def test_nov0512_as_planned():
"""NOV0512 the way it really is. This is how old loads with no characteristics will
process when run through the checker."""
ok, lines, sc = run_nov0512(with_characteristics=False)
# hopper.pcad now uses the default ODB_SI_ALIGN if not supplied,
# so we get this warni... | 73,547 |
def NL3P_sinc(A, to, BW, E1, k2, cDiss, nu, R, dt, startprint, simultime, fo1, k_m1, zb, printstep = 1, Q1=156.7, Q2=300, Q3=450):
"""This function performs sinc excitation simulation of the cantilever at the tip"""
"""This is designed for the NL3P model described in: “Theory of single-impact atomic force spect... | 73,548 |
def get_dataset(dataset_id, client_email, private_key_path):
"""Shortcut method to establish a connection to a particular dataset in the Cloud Datastore.
You'll generally use this as the first call to working with the API:
>>> from gcloud import datastore
>>> dataset = datastore.get_dataset('dataset-id', emai... | 73,549 |
def authenticate(inner_function):
""":param inner_function: any python function that accepts a user object
Wrap any python function and check the current session to see if
the user has logged in. If login, it will call the inner_function
with the logged in user object.
To wrap a function, we can p... | 73,550 |
def provider_get(args):
"""Get a provider info."""
providers = ProvidersManager().providers
if args.provider_name in providers:
provider_version = providers[args.provider_name][0]
provider_info = providers[args.provider_name][1]
if args.full:
provider_info["description"] ... | 73,551 |
def Ptoa(P, m1, m2): # input not in SI
"""
Calculates orbital radius from period
:param P: period [yr]
:param m1: mass of primary [Msol]
:param m2: mass of secondary [Mjup]
:return: semi-major axis [AU]
"""
# a^3/P^2 = (G / 4 pi pi) (m1 + m2)
c = G / (4. * np.pi * np.pi)
mu = (m... | 73,552 |
def plot_func(
x,
y,
title,
x_label,
y_label,
color='green',
legend=[],
multi=False):
"""
Plot function.
:param x: x-axis data
:type x: list or numpy array
:param y: y-axis data
:type y: list or numpy array
:param title: plot t... | 73,553 |
def issn_sync_records():
"""parse SourceRawData and sync to SourceRecords """
IssnHarvesterManager.sync_records() | 73,554 |
def buildinfo(lenv, build_type):
"""
Generate a buildinfo object
"""
build_date = time.strftime ("%Y-%m-%d")
build_time = time.strftime ("%H:%M:%S")
build_rev = os.popen('svnversion').read()[:-1] # remove \n
if build_rev == '':
build_rev = '-UNKNOWN-'
if lenv['BF_DEBUG']:
... | 73,555 |
def nlopt_bobyqa(
criterion_and_derivative,
x,
lower_bounds,
upper_bounds,
*,
convergence_relative_params_tolerance=CONVERGENCE_RELATIVE_PARAMS_TOLERANCE,
convergence_absolute_params_tolerance=CONVERGENCE_ABSOLUTE_PARAMS_TOLERANCE,
convergence_relative_criterion_tolerance=CONVERGENCE_REL... | 73,556 |
def templated_name_logger(template):
"""Returns a classmethod that calculates logger names by first applying the class name to `template`.
For instance:
class Foo(core.Configuration):
NAME = 'foo'
get_logger_name = helpers.templated_name_logger('my.%s')
class Bar(Foo):... | 73,557 |
def test_file_in_handler_with_vfs():
"""vfs file path is expanded"""
uri = 'zip://tests/data/files.zip!/RGB.byte.tif'
ctx = MockContext()
retval = file_in_handler(ctx, 'INPUT', uri)
assert retval.startswith('zip:///')
assert 'tests/data/files.zip!/RGB.byte.tif' in retval | 73,558 |
def search_vehicle(alarm_day_count, plate_num):
"""
获取需要报警的车辆信息
:parameter: alarm_day_count 提前报警天数
:parameter: plate_num 车牌号
:return: List[
(客户名称,客户性别,身份证号,电话,
车牌号,车辆型号,车辆登记日期,公里数,过户次数
贷款产品,贷款期次,贷款年限,贷款金额,贷款提报日期,贷款通过日期,放款日期,
承保公司,险种,保险生效日期,保险到期日期,
备注,修改人,修改时间... | 73,559 |
def plot_losses(train_losses=None, test_losses=None, accuracies=None,
plot_title='Train/Dev Loss', figsize=(7, 4), legend_loc='best',
legend_labels=['train', 'dev', '1 - acc'], save_name=None):
"""Plots train and dev losses obtained during training.
The plot image is saved to dis... | 73,560 |
def readBinaryWatch(self, num): # ! 44ms,进行双重循环,并统计1的数量,没什么太多的技巧性
"""
:type num: int
:rtype: List[str]
"""
return ['%d:%02d' % (h, m)
for h in range(12) for m in range(60)
if (bin(h) + bin(m)).count('1') == num] | 73,561 |
def tdb_minus_tt(jd_tdb, fraction_tdb=0.0):
"""Computes how far TDB is in advance of TT, given TDB.
Given that the two time scales never diverge by more than 2ms, TT
can also be given as the argument to perform the conversion in the
other direction.
"""
t = (jd_tdb - T0 + fraction_tdb) / 36525... | 73,562 |
def login_not_required(f):
""" Decorate routes to not require login. """
@wraps(f)
def decorated_function(*args, **kwargs):
if session.get("user_id"):
return redirect("/home")
return f(*args, **kwargs)
return decorated_function | 73,563 |
def build_function(type_, params, variable):
"""
Create object function matching type and parameters given.
Parameters
----------
type_ : str
'name' attribute of one of the classes of this module.
params : dict
Dict mapping parameter names with their values.
variable : str
... | 73,564 |
def test_empty_block():
"""Test an empty program
"""
@mb.program(input_specs=[mb.TensorSpec(shape=(2, 4))])
def prog(x0):
return x0
block = prog.functions["main"]
if len(block.operations) != 0:
raise AssertionError
if len(block.inputs) != 1:
raise AssertionError
... | 73,565 |
def download_blow(load=True): # pragma: no cover
"""Download blow dataset.
Parameters
----------
load : bool, optional
Load the dataset after downloading it when ``True``. Set this
to ``False`` and only the filename will be returned.
Returns
-------
pyvista.UnstructuredGr... | 73,566 |
def set(x, y):
"""Set console width and height."""
os.system("mode con: cols=" + str(x) + "lines=" + str(y)) | 73,567 |
def batch_retrieve_for_processing(ftp_as_object):
""" Used for mapping an s3_retrieve function. """
# Convert the ftp object to a dict so we can use __getattr__
ftp = ftp_as_object.as_dict()
data_type = file_path_to_data_type(ftp['s3_file_path'])
# Create a dictionary to populate an... | 73,568 |
def register_map(**kwargs):
"""Register an ObjectMapper to use for a Container class type
If mapper_cls is not specified, returns a decorator for registering an ObjectMapper class
as the mapper for container_cls. If mapper_cls specified, register the class as the mapper for container_cls
"""
contain... | 73,569 |
def main(args: argparse.Namespace):
"""Run the program according to arguments provided
Args:
args: A Namespace object of arguments to provide
"""
if args.install_scripts or args.list:
if args.install_scripts:
if not copy_scripts(dest=args.scripts_dir, quiet=args.quiet):
... | 73,570 |
def textilize(s):
"""Remove markup from html"""
s = s.replace("<p>", " ").replace(" ", " ")
return _re_html.sub("", s) | 73,571 |
def synchronise(sync_all=False, skip_video_fetch=False, skip_channel_fetch=False):
"""
Synchronise the list of Cached JWP resources in the database with the actual list of resources
using the JWP management API.
For JWP videos which come from the SMS, media items are automatically created as videos ape... | 73,572 |
def safe_join(base, *paths):
"""
A version of django.utils._os.safe_join for S3 paths.
Joins one or more path components to the base path component
intelligently. Returns a normalized version of the final path.
The final path must be located inside of the base path component
(otherwise a Value... | 73,573 |
def miniterm(owf_instance=None, *args):
"""
Run a serial console session (using miniterm from serial package).
:param args: Varargs command options.
:param owf_instance: Octowire framework instance (self).
:return: Nothing.
"""
if len(args) < 1:
config = None
else:
config... | 73,574 |
def inorder(node: Node, nodes: List[Node]) -> None:
"""Inorder traversal.
1. Traverse left
2. Visit root
3. Traverse right
In a BST, gives nodes in ascending order.
5
/ \
3 8
/ \ / \
1 4 7 10
1, 3, 4, 5, 7, 8, 10
"""
if not node:
... | 73,575 |
def create_dataset(data_dir,
train_mode=True,
epochs=1,
batch_size=4096,
is_tf_dataset=True,
line_per_sample=4096,
rank_size=None,
rank_id=None):
"""
create_dataset
"""
if... | 73,576 |
def drawSlice(col):
"""
Draws a slice of the specified color.
Parameters:
col (String): An RGB string in the format '#RRGGBB'
"""
turtle.color(col)
turtle.forward(100) | 73,577 |
def _request_user_ids():
"""Get dataframe of user emails, gids, names."""
params = {
'workspace': WORKSPACE_ID,
'opt_fields': 'email,name'
}
endpoint = 'teams/{}/users/'.format(TEAM_ID)
url = 'https://app.asana.com/api/1.0/{}'.format(endpoint)
r = requests.get(url, params=par... | 73,578 |
def driver(request_id):
"""Initialize the output row count entry."""
output_table = boto3.resource(
"dynamodb", region_name="us-east-1").Table(ZARR_ENV_VARS["zarr_output_table"])
output_table.put_item(
Item={"RequestId": request_id,
"RowCount": 0}
) | 73,579 |
def test_api_project_get_exception(app):
"""Test api GET /api/project endpoint exception"""
with app.test_client() as client:
res = client.get("/api/project")
json_data = res.get_json()
assert json_data["success"] is False
assert json_data["error"] == 500
assert "The server encountered ... | 73,580 |
def _squash_context(*args):
"""
Unwraps ``RequiresContext`` values, merges them into tuple, and wraps back.
.. code:: python
>>> from returns.context import RequiresContext
>>> from returns.converters import squash_context
>>> assert squash_context(
... RequiresContext.... | 73,581 |
def decode_message(buf, message_type=None, config=None):
"""Decode a message to a Python dictionary.
Returns tuple of (values, types)
"""
if config is None:
config = blackboxprotobuf.lib.config.default
if isinstance(buf, bytearray):
buf = bytes(buf)
buf = six.ensure_binary(buf)... | 73,582 |
def ca_all(request):
"""Lists all files readable by the current user"""
method = request.method
if method == 'POST':
keys = ['c', 'st', 'l', 'o', 'ou', 'cn', 'email']
values = {}
for key in keys:
if request.data.get(key):
values[key] = request.data.get(ke... | 73,583 |
def supervised_disagreement(labels, logits_1, logits_2):
""" Supervised disagreement """
labels = tf.cast(labels, tf.int32)
preds_1 = tf.argmax(logits_1, axis=-1, output_type=tf.int32)
preds_2 = tf.argmax(logits_2, axis=-1, output_type=tf.int32)
par1 = tf.reduce_mean(tf.cast(tf.math.logical_and(preds_1 == lab... | 73,584 |
def sort_tests(tests) -> unittest.TestSuite:
"""Sort supplied test suites such that MemoryTestCases are at the end.
`lsst.utils.tests.MemoryTestCase` tests should always run after any other
tests in the module.
Parameters
----------
tests : sequence
Sequence of test suites.
Return... | 73,585 |
def set_dtype(dtype):
"""Set the dtype to use during estimation.
Parameters
----------
dtype : object
numpy dtype
"""
global _DTYPE
_DTYPE = dtype | 73,586 |
def chunk_by_image(boxes):
"""
turn a flat list of boxes into a hierarchy of:
image
category
[boxes]
:param boxes: list of box detections
:return: dictionary of boxes chunked by image/category
"""
chunks = {}
for b in boxes:
if b['image_id'] not in chunks:
... | 73,587 |
def get_all_secret_registry_events(
chain: BlockChainService,
secret_registry_address: Address,
events: List[str] = ALL_EVENTS,
from_block: BlockSpecification = 0,
to_block: BlockSpecification = 'latest',
) -> List[Dict]:
""" Helper to get all events of a SecretRegistry. """
... | 73,588 |
def test_label_fiber_array_align_ports():
"""Test that adds the correct label for measurements."""
c = pp.c.waveguide()
assert len(c.labels) == 0
c = pp.routing.add_fiber_single(c, with_align_ports=True)
pp.show(c)
print(len(c.labels))
assert len(c.labels) == 4
l0 = c.labels[0].text
... | 73,589 |
def run_simulation(simulation, n_steps, run_ideal=False, simdir="r"):
"""
Run a neural network model simulation computing occupancy histograms
:param simulation: The simulation to run
:param n_steps: The number of steps to simulation
:param run_ideal: If True, instead of using neural network movemen... | 73,590 |
def _RunLengthDecode(count_value_pairs):
"""Iterator to expand a run length encoded sequence.
The test results dashboard compresses some long lists using "run length
encoding", for example:
['F', 'F', 'F', 'P', 'P', 'P', 'P', 'F', 'F']
becomes:
[[3, 'F'], [4, 'P'], [2, 'F']]
This function takes t... | 73,591 |
def find_duplicate_uuids(images):
"""
Create error records for UUID duplicates.
There is no real way to figure out which is the correct image to keep, so
we keep the first one and mark all of the others as an error. We also
remove the images with duplicate UUIDs from the image dataframe.
"""
... | 73,592 |
def copy_static(root_directory, dist_directory, sdk_directory, development):
"""
Copy all static files from source to target.
"""
for static in configuration.STATICS:
context = {
"development": development,
"dist": dist_directory,
"root": root_directory,
... | 73,593 |
def accounts_root():
"""
---
get:
summary: Get all accounts this user has access to
tags:
- Accounts
description:
Returns the list of accounts that this user (person or bot) has permission to access. The list is returned in a single array (no pag... | 73,594 |
async def arrival(request: Request): # data { name, phone, remark }
""" D -> H 到达现场并开始处理 """
_oid = get_maintenance_id(request)
data = await request.json()
_time_str = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
try:
_edit = data['name']
_phone = data['phone']
_content = "... | 73,595 |
def test_resolve_bundle_type(config):
"""The config indicates the project is a bundle."""
config.set(type="bundle")
cmd = PackCommand("group", config)
with patch.object(cmd, "_pack_bundle") as mock:
cmd.run(noargs)
mock.assert_called_with() | 73,596 |
def to_graph(inp: Union[Graph, str], fmt: Optional[str] = "turtle") -> Graph:
"""
Convert inp into a graph
:param inp: Graph, file name, url or text
:param fmt: expected format of inp
:return: Graph representing inp
"""
if isinstance(inp, Graph):
return inp
g = Graph()
if not... | 73,597 |
def file_exists(session, ds_browser, ds_path, file_name):
"""Check if the file exists on the datastore."""
client_factory = session._get_vim().client.factory
search_spec = search_datastore_spec(client_factory, file_name)
search_task = session._call_method(session._get_vim(),
... | 73,598 |
def main():
"""Script function to run tests on a cross section file"""
from argparse import ArgumentParser, ArgumentDefaultsHelpFormatter
set_verbosity(3)
parser = ArgumentParser(description='Test genie xsec service',
formatter_class=ArgumentDefaultsHelpFormatter)
parser... | 73,599 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.