content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def conv_block(
inp,
cweight,
bweight,
reuse,
scope,
use_stride=True,
activation=tf.nn.leaky_relu,
pn=False,
bn=False,
gn=False,
ln=False,
scale=None,
bias=None,
class_bias=None,
use_bias=False,
... | 71,300 |
def qa_statistics(raster, mask, blocks, confidence=None) -> Tuple[float, float]:
"""Retrieve raster statistics efficacy and not clear ratio, based in Fmask values.
Notes:
Values 0 and 1 are considered `clear data`.
Values 2 and 4 are considered as `not clear data`
The values for snow `3... | 71,301 |
def user_activation(email_to_file=None, rank_required=ADMIN_LEVEL):
"""Activate a user's account"""
from varappx.main.view_tools import authenticate as auth
# logger.info("Activate/deactivate user")
if auto_process_OPTIONS(request):
return auto_process_OPTIONS(request)
username = request.for... | 71,302 |
def queue_push():
"""Queue push""" | 71,303 |
def remove_emoji_and_non_alphanumeric(word_list):
"""
Remove both emojis and non-alphanumeric tokens in the given word list
parameters
-----------
:param word_list: list of str
:return: list of str
"""
filtered_list = [word for word in word_list if word not in emoji.UNICODE_EMOJI and no... | 71,304 |
def _GetJsonFileCreator(name, json_object):
"""Creates a creator function for an extended source context file.
Args:
name: (String) The name of the file to generate.
json_object: Any object compatible with json.dump.
Returns:
(callable()) A creator function that will create the file and return a
... | 71,305 |
def run_experiment(nbits) -> None:
"""Run full experiment for a given number of bits."""
c = make_c(nbits-1)
u = make_u(nbits, c)
psi = state.zeros(nbits-1) * state.ones(1)
psi = ops.Hadamard(nbits)(psi)
psi = u(psi)
psi = ops.Hadamard(nbits)(psi)
check_result(nbits, c, psi) | 71,306 |
def active_matrix_from_extrinsic_euler_zyx(e):
"""Compute active rotation matrix from extrinsic zyx Cardan angles.
Parameters
----------
e : array-like, shape (3,)
Angles for rotation around z-, y-, and x-axes (extrinsic rotations)
Returns
-------
R : array-like, shape (3, 3)
... | 71,307 |
def test_FUNC_country_iso_3_WITH_null_string_EXPECT_exception_not_raised() -> None:
"""
Check whether the validation succeeded.
:return: No return.
"""
FieldValidator.country_iso_3(None) | 71,308 |
def get_index_of_feature(feature_list, item):
"""
Gets the index of the feature in the provided feature list
:rtype : int
:param feature_list: List of features to search from
:param item: The feature to search
:return: The index where the feature was founded, -1 otherwise
"""
# getting... | 71,309 |
def test_tetra_concordance(
paths_concordance_fna, path_concordance_jspecies, tolerance_tetra, tmp_path
):
"""Check TETRA results are concordant with JSpecies."""
# Perform TETRA analysis
zscores = dict()
for filename in paths_concordance_fna:
zscores[filename.stem] = tetra.calculate_tetra_z... | 71,310 |
def get_timezone(WindowsZoneName=True):
"""
Get the TimeZone Name
if WindowsZoneName is True, then it returns the name used by the Microsoft Windows Platform
otherwise it returns the Olsen name (used by all other platforms)
Note: this needs to get tested on Windows
"""
log = logging.getLog... | 71,311 |
def test_jvm_g1_slow_death_oom():
"""
Executes a program which over time does way more GC than actual execution
In this case -XX:GCTimeLimit and -XX:GCHeapFreeLimit do squat for G1GC
"""
g1_slow_death = java_cmd[
'-Xmx100m',
'-XX:+UseG1GC',
'-XX:GCTimeLimit=20',
'-XX... | 71,312 |
def train(args):
"""High-level method for training a model"""
# load data
x_train, y_train, n_sam = util.load_data(args, type='train', num_files=args.num_files, full_data=True)
x_val, y_val = util.load_data(args, type='val', num_files=int(np.floor(args.num_files*0.3)))
# callbacks
checkpointer ... | 71,313 |
def ncrp(outdir, **graph_config):
"""Writes out a nested Chinese restaurant process graph"""
write_graph(outdir, type="nested_chinese_restaurant_process", **graph_config) | 71,314 |
def fix_ghdx_birth_weights(df):
"""Ensure the child birth weight is in grams and is a legal value.
The original survey allowed answers to weights to be coded in grams or
kilograms. The GHDx data has recoded the values into grams. However, a
few cases are clearly still coded in kilograms. The survey als... | 71,315 |
def __virtual__():
"""
Only load if boto is available.
"""
if "boto3_elasticache.cache_cluster_exists" in __salt__:
return "boto3_elasticache"
return (False, "boto3_elasticcache module could not be loaded") | 71,316 |
def parse_adjlist(lines, comments='#', delimiter=None,
create_using=None, nodetype=None):
"""Parse lines of a graph adjacency list representation.
Parameters
----------
lines : list or iterator of strings
Input data in adjlist format
create_using: NetworkX graph container... | 71,317 |
def get_slovakia():
"""
gets all the data for Slovakia
:return: object
"""
slovakia = Country('Slovak Republic')
slovakia.get_gdp('https://www.quandl.com/api/v3/datasets/WWDI/SVK_'
'NY_GDP_PCAP_CD.json?api_key=2jhCWecEKmuxzVY9ifwp')
slovakia.get_investment_inflow... | 71,318 |
def cluster_acc(y_true, y_pred):
"""
Calculate clustering accuracy. Require scikit-learn installed
# Arguments
y: true labels, numpy.array with shape `(n_samples,)`
y_pred: predicted labels, numpy.array with shape `(n_samples,)`
# Return
accuracy, in [0,1]
"""
y_true = y_... | 71,319 |
def calc_rms_df(df, measured_tox_col, modeled_tox_col):
"""
Calculate the root mean square deviation for two columns of a DataFrame
returns √[ ∑(x-y)² / n ]
"""
df_rms = df[[measured_tox_col, modeled_tox_col]].dropna()
toxobs = df_rms[measured_tox_col].tolist()
toxmod = df_rms[modeled_tox_co... | 71,320 |
def dist(p1, p2):
"""
Distance between two points represented by arrays.
"""
return distance(p1[0], p1[1], p2[0], p2[1]) | 71,321 |
def restart_service(service_name):
"""
Message SM to restart a service
"""
sm_api_msg = ("%s,%s,%i,%s,%s,%s"
% (SM_API_MSG_VERSION, SM_API_MSG_REVISION, 1,
SM_API_MSG_TYPE_RESTART_SERVICE, "sm-action",
service_name))
_send_msg_to_sm(sm_api... | 71,322 |
def trim_motif(pfm, motif, min_ic=0.2, pad=0):
"""
Given the PFM and motif (both L x 4 arrays) (the motif could be the
PFM itself), trims `motif` by cutting off flanks of low information
content in `pfm`. `min_ic` is the minimum required information
content. If specified this trimmed motif will be e... | 71,323 |
def org_search():
"""
Organisation REST controller
- limited to just search.json for use in Autocompletes
- allows differential access permissions
"""
s3.prep = lambda r: r.representation == "json" and \
r.method == "search"
return s3_rest_controller(modu... | 71,324 |
def in_quiet_hours() -> bool:
"""Check whether the current time is within quiet hours.
Returns:
bool: True if within quiet hours
Raises:
AttributeError: if quiet hours weren't defined in config
"""
now = pendulum.now()
hour = now.hour
if config.QUIET_START > config.QUIET_E... | 71,325 |
def save(path, args, model, optimizer):
"""Saving model"""
fluid.save_dygraph(model.state_dict(), path)
fluid.save_dygraph(optimizer.state_dict(), path)
with open(path + ".args", "wb") as f:
pickle.dump(args.namespace, f, protocol=2) | 71,326 |
def show_view_wireframe() -> None:
"""
""" | 71,327 |
def int_to_smile(list_of_int):
"""
Convert the list of int to list of token according to the vocabulary
:param list_of_int: list of int representing the SMILES
:type list_of_int: list of int
:return: list of token
"""
return [p.tokens[s] for s in list_of_int] | 71,328 |
def searchLibary(keyword):
"""
Keyword based search for books, case insensitive in author and title
Args:
keyword (string): Keyword to search for
Return:
List of search results
"""
results = []
lk = keyword.lower()
for bookid, book in library.LIBRARY.items():
... | 71,329 |
def emprestarLivro(livro):
""" Emprestimo do livro
"""
return biblioteca_temp.emprestarLivro(livro) | 71,330 |
def _heapify(items: list[Any], d: int, comp=lt) -> list[Any]:
"""Создать на месте кучу из списка за время O(log(len(items))).
:param items: список элементов
:param d: коэффициент ветвления (максимальное число потомков у одного элемента)
:param comp: функция сравнения двух элементов, определяющая будет ... | 71,331 |
def build_generator_growth_layer_block(conv_layers, params, block_idx):
"""Builds generator growth block internals through call.
Args:
conv_layers: list, the current growth block's conv layers.
params: dict, user passed parameters.
block_idx: int, the current growth block's index.
... | 71,332 |
def isfloat(s):
"""**Returns**: True if s is the string representation of a number
:param s: the candidate string to test
**Precondition**: s is a string
"""
try:
x = float(s)
return True
except:
return False | 71,333 |
def alto_illustrations(xml, xmlns):
""" Extract bounding boxes of illustration from ALTO xml file """
# Find all <Illustration> elements
for illustration in xml.iterfind('.//{%s}Illustration' % xmlns):
# Get @ID of <Illustration> element
illustration_id = illustration.attrib.get('ID')
... | 71,334 |
def generate_password(length=10):
"""Generate rnadom password of the given length.
"""
import random
import string
return ''.join(
random.SystemRandom().choice(
string.ascii_lowercase + string.ascii_uppercase + string.digits
)
for _ in range(length)
) | 71,335 |
def add_optional_gps_tags(exif_gps: {str: any},
speed: float,
altitude: float,
compass: float) -> {str: any}:
"""This method will append optional tags to exif_gps tags dictionary"""
if speed:
exif_gps[piexif.GPSIFD.GPSSpeed] =... | 71,336 |
def generate_TISARADC(laygen, objectname_pfix, sar_libname, rdac_libname, space_1x_libname,
sar_name, rdac_name, space_1x_name, placement_grid,
routing_grid_m3m4, routing_grid_m4m5, routing_grid_m4m5_basic_thick, routing_grid_m5m6, routing_grid_m5m6_thick,
... | 71,337 |
def reference_transit(samples, per, rp, a, inc, ecc, w, u, limb_dark):
"""Returns an Earth-like transit of width 1 and depth 1"""
f = numpy.ones(tls_constants.SUPERSAMPLE_SIZE)
duration = 1 # transit duration in days. Increase for exotic cases
t = numpy.linspace(-duration * 0.5, duration * 0.5, tls_co... | 71,338 |
def sol_rad_from_t(et_radiation, cs_radiation, temperature_min, temperature_max, coastal):
"""
Estimate incoming solar (or shortwave) radiation, *Rs*, (radiation hitting
a horizontal plane after scattering by the atmosphere) from min and max
temperature together with an empirical adjustment coefficient ... | 71,339 |
def moving_avg(v, N):
"""
simple moving average.
Parameters
----------
v : list
data ta to average
N : integer
number of samples per average.
Returns
-------
m_avg : list
averaged data.
"""
s, m_avg = [0], []
for i, x in enumerat... | 71,340 |
def solve():
"""This method will compute and return the solution if it exists, as a list of (row, column) tuples, zero-based.
Else, an exception will be raised stating a loop was detected and that no solution exists."""
robot = Robot(number_of_rows, number_of_columns, ball_location, goal_location, block... | 71,341 |
def test_gather_object_artifacts_uselist_no_backref():
"""
GIVEN specification with uselist but not backref and schemas
WHEN gather_object_artifacts is called with the specification and schemas
THEN MalformedRelationshipError is raised.
"""
spec = {"$ref": "#/components/schemas/RefSchema"}
s... | 71,342 |
def hashed_password(username: str, password: str) -> str:
"""
ハッシュ化したパスワードを返す。
"""
tmp = adcconfig.SALT + username + password
return sha256(tmp.encode('utf-8')).hexdigest() | 71,343 |
def load_check_test_cvs():
"""
This fixture ensures that the required test controlled vocab repository
has been cloned to the cache directory within the home directory.
"""
branch = "master"
target = os.path.join(COMP_CHECK_CV_REPO_DIR, branch)
if not os.path.isdir(COMP_CHECK_CV_REPO_DIR):
... | 71,344 |
def linierRegression(features, weights):
"""
Performs simple linier regression
"""
return np.dot(features, weights) | 71,345 |
def plot_model_predictions(df, baseline, file_name, txt_cord_y = 0.51, y_label= "Precision-Recall AUC %", title_label="Precision-Recall AUC score for all models",
path = model_preds_figures):
"""Plot model predictions for all profiling assays"""
if not os.path.exists(path):
os.mk... | 71,346 |
def get_students(tas: List[str], gr:str)->List[str]:
""" From the list of all TAs, find TAs matching the constraint string
For example, gr could be "cs17|es18" this represents all the students
whole roll numbers start from cs17 or es18
This function returns the list of TAs from tas which match gr
... | 71,347 |
def calculate_prototypes_from_labels(embedding,
labels,
max_label=None):
"""Calculates prototypes from labels.
This function calculates prototypes (mean direction) from embedding features
for each label. This function is also used as the m... | 71,348 |
def save_obj(obj: Any, path: PathLike):
"""
Dump the model to the specified path.
Parameters
----------
obj: Estimator
The model to be saved
path: PathLike
The path where to save the model
"""
with open(path, "wb") as f_w:
pickle.dump(obj, f_w) | 71,349 |
def get_mask(pos, shape, radius, include_edge=True, return_masks=False):
""" Create a binary mask that masks pixels farther than radius to all
given feature positions.
Optionally returns the masks that recover the individual feature pixels from
a masked image, as follows: ``image[mask][masks_single[i]]... | 71,350 |
def Volume(v,u,w):
"""Calculate volume of solid created by three vectors.
Returns int
Attributes
----------
v: Vector
First Vector
u: Vector
Second Vector
w: Vector
Third Vector
"""
return abs(DotProduct(CrossProduct(v,u), w)) | 71,351 |
def is_admin(user_id):
"""
Retrieves a user's admin status from the permissions directory.
"""
perms = get_current_permissions()
return user_id in perms["admins"] | 71,352 |
def test_set_project_to_available_valid_transition(module_client, test_project):
"""Set status to Available for test project"""
new_status = {"new_status": "Available", "deadline": 10}
project_id = test_project
project = project_row(project_id=project_id)
time.sleep(1)
response = module_clien... | 71,353 |
def _get_commits(output):
"""Returns the commits message in the output. All commits must have
been made by `Alice Author` or `PY C` to be found.
"""
commits = []
save = False
cnt = 0
for row in output.split("\n"):
if row.strip() in ["Alice Author", "Alice Äuthòr", "PY C"]:
... | 71,354 |
def main():
"""
A basic commandline wrapper for our training and plotting functions.
"""
parser = argparse.ArgumentParser(
description="Train a switching optimizer and plot output"
)
parser.add_argument("--config", type=str, help="the path to the configuration file")
parser.add_argu... | 71,355 |
def scan():
"""scan for available ports. return a list of names"""
system_name = platform.system()
if system_name == 'Windows':
available = []
for i in range(200):
try:
s = serial.Serial(i)
available.append(s.portstr)
s.close() # explicit clo... | 71,356 |
def valid_value(value, quote=default_cookie_quote, unquote=default_unquote):
"""Validate a cookie value string.
This is generic across quote/unquote functions because it directly verifies
the encoding round-trip using the specified quote/unquote functions.
So if you use different quote/unquote function... | 71,357 |
def cmdLists(cmd):
"""
creates docker or singularity command(s) from either a
single command or a list of commands.
"""
if os.environ.get('CAT_BINARY_MODE') == 'docker':
if isinstance(cmd[0],list):
docList = []
for e in cmd:
docList.append(getDockerCom... | 71,358 |
def steg(in_path, out_path=None, data=None):
"""
The steg function (use the LSB of the color table entries to hide the data)
"""
# Must encode the length of the data so we know how much to read when extracting
if data is not None:
data_array = bytearray(data)
data_array.insert(0, le... | 71,359 |
def _make_specific_identifier(param_name, identifier):
# type: (str, str) -> str
"""
Only adds an underscore between the parameters.
"""
return "{}_{}".format(param_name, identifier) | 71,360 |
def resnet50(pretrained=False, pretrained_model_path=None, num_classes=None, expose_stages=None, dilations=None, stride_in_1x1=False):
"""Constructs a ResNet-50 model
Args:
pretrained (bool): if True, load pretrained model. Default: False
pretrained_model_path (str, optional): only effective whe... | 71,361 |
def ReadTag(buffer, pos):
"""Read a tag from the buffer, and return a (tag_bytes, new_pos) tuple.
We return the raw bytes of the tag rather than decoding them. The raw
bytes can then be used to look up the proper decoder. This effectively allows
us to trade some work that would be done in pure-python (decodi... | 71,362 |
def emptyStack():
""" Empties the stack while collecting each element as it is removed.
Returns the collected elements. """
elements = ""
while not stack.isEmpty():
if isOperator(stack.peek()):
elements += stack.pop()
elif stack.peek() == '(':
raise ParensMism... | 71,363 |
def test_weighted_median():
"""
Tests for the weighted median function.
"""
# w = np.ones((50, 50))
# u = np.zeros(w.shape)
# u[10:20, 40:45] = 1
# output = weighted_median(w, u)
pass | 71,364 |
def normalize_args_for_analyze(args, from_build_command):
""" Normalize parsed arguments for analyze-build and scan-build.
:param args: Parsed argument object. (Will be mutated.)
:param from_build_command: Boolean value tells is the command suppose
to run the analyzer against a build command or a compi... | 71,365 |
def main(connection, info, args, world) :
"""Starts the loop for checking feeds"""
feedurl = args[-2]
onoff = args[-1]
title = " ".join(args[1:-2])
if onoff == "on" :
feeds = shelve.open("feeds-%s.db" % (connection.networkname), writeback=True)
feeds[feedurl] = {}
fee... | 71,366 |
def get_brackets(title: str) -> Union[str, None]:
"""
Return the substring of the first instance of bracketed text.
"""
regex_brackets = re.search(r"\[(.*?)\]", title)
if regex_brackets is None:
return None
else:
return regex_brackets.group() | 71,367 |
def stack_3rd_dimension_along_axis(u_jkir, axis):
"""
Take the 3D input matrix, slice it along the 3rd axis and stack the resulting 2D matrices
along the selected matrix while maintaining the correct order.
:param u_jkir: 3D array of the shape [JK, I, R]
:param axis: 0 or 1
:... | 71,368 |
def test_jan1():
"""Test that a DSM for the previous year works properly."""
text = """
794
CDUS27 KZME 010616
KHKS DS 31/12 661152/ 470316// 66/ 46//0021509/45/00/00/00/00/00/05/
02/06/T/T/12/00/03/17/T/T/T/00/00/00/00/T/00/00/78/17171245/16231238/
13/NN/N/N/NN/ET EP EW=
"""
prod = parser(text, utcnow=utc(... | 71,369 |
def autoload_resource(session: CloudShellAPISession, test_helpers: TestHelpers, server: str) -> ResourceInfo:
""" Yields CPE resource for shell autoload testing. """
resource = test_helpers.create_autoload_resource(BYTEBLOWER_CHASSIS_MODEL, 'test-byteblower', server)
yield resource
session.DeleteResourc... | 71,370 |
def _op_nodes(
graph: Union[tf.Graph, testutils.GraphDef]) -> List[testutils.NodeDef]:
"""Return arithmetic/nn operation nodes from a graph"""
graph_def = graph.as_graph_def() if isinstance(graph, tf.Graph) else graph
def _op(node): return node.op not in ('Const', 'Identity', 'Placeholder')
... | 71,371 |
def output_file(save_format, pcap_packets, exclude_empty, anonymize_names):
"""Save the specified file with the specified format."""
pcap_filenames = list(pcap_packets)
if save_format == 'txt':
output_text = make_text_not_war(pcap_packets)
print(output_text)
with open('pcap_graph.txt... | 71,372 |
def _compositeImageToVideoSegment(compositeImage):
"""
:param compositeImage:
:return:
@type compositeImage: CompositeImage
"""
if compositeImage is None or compositeImage.videomasks is None:
return []
return [segmentToVideoSegment(item) for item in compositeImage.videomasks] | 71,373 |
def collect_sessions(bids_dir, session=None, strict=False, bids_validate=True):
"""
List the sessions under the BIDS root and checks that sessions
designated with the participant_label argument exist in that folder.
Returns the list of sessions to be finally processed.
Requesting all sessions in a B... | 71,374 |
def _dof(mean_tau, sd_tau2):
"""
Returns the degrees of freedom for the chi-2 distribution from the mean and
variance of the uncertainty model, as reported in equation 5.5 of Al Atik
(2015)
"""
return (2.0 * mean_tau ** 4.) / (sd_tau2 ** 2.) | 71,375 |
def stations():
"""Return a list of stations."""
print("Received Station API Request.")
# Query the station list
station_data = session.query(Station).all()
# Create a list of dictionaries
station_list = []
for station in station_data:
station_dict = {}
station... | 71,376 |
def yaml_load(string):
"""Parse multiple strings as yaml data. Multiple dictionaries are combined togather."""
if isinstance(string, str):
return ordered_load(string)
if not isinstance(string, Iterable):
raise TypeError('Invalid yaml_load argument type')
ret = dict()
for s in strin... | 71,377 |
def get_checklist(identifier):
"""
Get the data for a checklist from its eBird web page.
Args:
identifier (str): the unique identifier for the checklist, e.g. S62633426
Returns:
(dict): all the fields extracted from the web page.
ToDo:
* scrape entry comments.
* sc... | 71,378 |
def main(args):
"""Do it all."""
if not os.path.isdir(args.logs):
raise Fail("Logs location '%s' is not a directory." % args.logs)
builds = gather_builds(args)
if args.verbose:
print("Lined up %d builds." % len(builds))
# The "configure" step is single-threaded. We can run many at... | 71,379 |
def check_tensors_dtype_same(data_dtype, value_dtype, op_name):
"""Check tensors data type same."""
if data_dtype in value_dtype:
return True
raise TypeError(f"For '{op_name}', the value data type '{value_dtype}' "
f"is not consistent with assigned tensor data type {data_dtype}."... | 71,380 |
def generate_data(data_dirs, save_dir):
"""
Routine for generating train data in tfrecords
Args:
data_dirs: where simulation data is.
save_dir: where tfrecords will go.
Returns: list of tfrecords.
"""
def data_generator():
def _get_data(dir):
"""
... | 71,381 |
def to_categories(df, cat_map):
""" Convert a dataframe to use categories, based on the category map created by table_category_map.
:param df: CHIS Dataframe to convert, loaded from Metatab
:param cat_map: category map, from table_category_map
:return:
"""
df = df.copy()
for col in df.c... | 71,382 |
def hastty():
""" Whether (it looks like) a tty is available.
"""
try:
return sys.stdin and sys.stdin.isatty()
except Exception: # pragma: no cover
return False | 71,383 |
def change(duty):
"""
改变led的亮度
duty: 百分比 x 1,000,000
"""
pi.hardware_PWM(PWM_LED_PIN,PWM_FREQ,duty) | 71,384 |
def xgcd(vals):
"""Calculate extended greatest commond divisor."""
_xgcd = Xgcd(vals)
return _xgcd.run() | 71,385 |
def _get_i18n_locale(locale_name, react=False):
"""Retrieve a locale in a Jed-compatible format."""
# Ensure we have a valid locale. en_GB is our source locale and thus always considered
# valid, even if it doesn't exist (dev setup where the user did not compile any locales)
# since otherwise we'd have... | 71,386 |
def find_bad_frames(ds, reindex=True):
"""
Find the frames that have fewer cells than the previous frame.
Parameters
----------
ds : (S, T, ..., Y, X) DataSet
reindex : bool, default: True
Whether to reindex each frame as well.
Returns
-------
bad : list
With entrie... | 71,387 |
def test_shell_cmd_inputs_template_4():
"""additional inputs with output_file_template and an additional
read-only fields that combine two outputs together in the command line
one output_file_template can't be resolved - no inpB is provided
"""
my_input_spec = SpecInfo(
name="Input",
... | 71,388 |
async def get_steam_game_search(keyword: str) -> list:
"""
Return search result
Args:
keyword: Keyword to search(game name)
Examples:
get_steam_game_search("Monster Hunter")
Return:
[
str,
MessageChain
]
"""
url = "https://steamstats... | 71,389 |
def get_most_energetic_neutrino(particles):
"""Get most energetic neutrino.
Parameters
----------
particles : ndarray of dtype I3PARTICLE_T
Returns
-------
most_energetic_neutrino : shape () ndarray of dtype I3PARTICLE_T
"""
return get_best_filter(
particles=particles, fil... | 71,390 |
def test_apply_device_failed_duplicate_apply(admin_token, empty_device_apply_record):
"""
申请设备失败,重复申请
:param admin_token:
:param empty_device_apply_record:
:return:
"""
empty_device_apply_record(1)
data = {
"start_time": "2019-10-15 09:28:55", "end_time": "2019-10-30 00:55:55", "... | 71,391 |
def cria_coordenada(linha,coluna):
"""int x int -> tuple
Esta funcao recebe duas coordenadas do tipo inteiro, a primeira correspondente a linha e a segunda a coluna e devolve um elemento do tipo coordenada, ou seja, o tuplo (linha,coluna)"""
if 1<=linha<=4 and 1<=coluna<=4 and isinstance(linha,int) and i... | 71,392 |
def test_force(tissue_object):
"""Testing the force calcultion function"""
# TODO: Might need to half or double since calculation is per post.
systolic_force = calculations.force(1000, 3, 3, 2.8, 3, 2.8, tissue_object.peaks[1])
diastolic_force = calculations.force(
1000, 3, 3, 2.8, 3, 2.8, tissu... | 71,393 |
def identify_groups(ref_labels, pred_labels, return_overlaps=False):
"""Which predicted label explains which reference label?
A predicted label explains the reference label which maximizes the minimum
of ``relative_overlaps_pred`` and ``relative_overlaps_ref``.
Compare this with ``compute_association_... | 71,394 |
def spring(*args, **kwargs):
"""
The spring command can do any of the following: * create a new spring object (shape plus transform).
Returns: `string` Command result
"""
pass | 71,395 |
def commit_config(node, raid_controller, reboot=False, realtime=False):
"""Apply all pending changes on a RAID controller.
:param node: an ironic node object.
:param raid_controller: id of the RAID controller.
:param reboot: indicates whether a reboot job should be automatically
crea... | 71,396 |
def link(g: Graph, subject: Node, predicate: URIRef) -> Tuple[Optional[URIRef], Optional[URIRef]]:
"""
Return the link URI and link type for subject and predicate
:param g: graph context
:param subject: subject of linke
:param predicate: link predicate
:return: URI and optional type URI. URI is... | 71,397 |
def radar_info(data: np.ndarray, metadata: dict):
"""Display metadata from radar request."""
log.info("Data shape: %s", data.shape)
log.info("Metadata")
for key, value in metadata.items():
print(f"- {key}: {value}") | 71,398 |
def list_pages(page_obj: Page) -> Page:
"""
Gets a paginator page item and returns it with a list of pages to display like:
[1, 2, "…", 17, 18, 19, "…" 41, 42]
Currently not in use, simpler pages lists are implemented.
"""
last_page_number = page_obj.paginator.num_pages
pages_list = [1, 2]
... | 71,399 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.