content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def get_step_name(monitoring_info_proto):
"""Returns a step name for the given monitoring info or None if step name
cannot be specified."""
# Right now only metrics that have a PTRANSFORM are taken into account
return monitoring_info_proto.labels.get(PTRANSFORM_LABEL) | e211465455d2f173ba00b17bd8603d6de7468679 | 42,100 |
def field_isomorphism(a, b, *, fast=True):
"""Construct an isomorphism between two number fields. """
a, b = sympify(a), sympify(b)
if not a.is_AlgebraicNumber:
a = AlgebraicNumber(a)
if not b.is_AlgebraicNumber:
b = AlgebraicNumber(b)
if a == b:
return a.coeffs()
n =... | 2c5cd6b635883caa9d344542e03c139da8ae4685 | 42,101 |
def first_dup(s):
"""
Find the first character that repeats
in a String and return that character.
:param s:
:return:
"""
for char in s:
if s.count(char) > 1:
return char
return None | 300d9c60123bbceff8efde84be43c26f527f2fc0 | 42,102 |
def SegRename(ea, name):
"""
Change name of the segment
@param ea: any address in the segment
@param name: new name of the segment
@return: success (boolean)
"""
seg = idaapi.getseg(ea)
if not seg:
return False
return idaapi.set_segm_name(seg, name) | 95d2ed2d15b5329be881e4bcec2afff80af4bf06 | 42,103 |
def clean_df(df):
"""what it does: cleans the consolidated dataframe
arguments: takes a dataframe as argument
returns: the cleaned dataframe"""
df['published_date'] = pd.to_datetime(df['published_date'], errors='coerce')
# Convert list of authors to one single str of authors
authors... | f34362353cbb817ee605f9dd3c0796ddf2920ef4 | 42,104 |
def type_check(tags):
"""Perform a type check on a list of tags"""
if type(tags) in (list, tuple):
single = False
elif tags == None:
tags = []
single = False
else:
tags = [tags]
single = True
if len([t for t in tags if type(t) not in (str,bytes)]) == 0:
valid = Tr... | 519fb2bcf0b8c8792465cc2e057e3dea8f611841 | 42,105 |
from typing import Union
def open_pdf(file_name: str,
parent: QWidget) -> (Union[Doc, None], bool):
"""
open pdf file and return a fitz object if applied
:param file_name: pdf file name
:param parent: parent
:return (doc, bool)
"""
try:
doc = Doc(file_name)
except... | c28f8bc29f5986fe90010cd252ca8505eecd40a6 | 42,106 |
async def upload_complete(
request: Request,
uuid: str,
user: domain.User = Depends(dep.get_current_user),
config: Config = Depends(dep.config),
response_class=HTMLResponse,
):
"""Page that advises user to wait after upload."""
details = infra.parse.details_from_params(
... | 08a6decbf0175cd06e279a3ed2b3234c49e8c3f4 | 42,107 |
def load_Ttree(tree):
"""load TTree as dict"""
ret = {}
for i in tree.keys():
arr = tree.get(i).array()
if isinstance(arr, np.ndarray):
ret[i.decode()] = arr
return ret | d14a6446d6d469f33036b08c80d794427ff37855 | 42,108 |
def traducir_resultados(i: dict) -> None:
"""
Traducir resultados // Translate results
#### Parametros:
* @param i: Diccionario con el resultado // Dictionary with the results
#### Returns:
* return _bTranslated: True: si fue traducido, False: si no // True: if it was translated, False: if not
"""
_bTransl... | 5d26235978fd19002ee6b9f20925cc47ae103584 | 42,109 |
def get_type_for_model(model):
"""
Return type name for a given model class.
"""
opts = model._meta.concrete_model._meta
return camelcase_to_underscore(opts.object_name) | bc16a5fe4e4b8b285814017f00b9d3e016740a97 | 42,110 |
def trace_plot_all_clusters(processed_neurons, clus_df, time_arr, label_col, ix_col, color_palette = None,
max_ix= None, clus_num_list = None, **kwargs):
"""
Wrapper function to make a list of bokeh figures containing the distribution of traces
for visualization of clustering results.
Params
-------
proce... | f04adb46e482ae334bd54c3f66bc21338bede416 | 42,111 |
import subprocess
def run_subprocess(command, return_code=False, verbose=None, *args, **kwargs):
"""Run command using subprocess.Popen.
Run command and wait for command to complete. If the return code was zero
then return, otherwise raise CalledProcessError.
By default, this will also add stdout= and... | 4ebe634bc3da5470180618433872a71a0b4e25f2 | 42,112 |
def get_OUT_port(port: str) -> int:
""" Get number of OUT port, or None if 'port' is not a valid value. """
return get_port_nr(port, "OUT") | 2c657143b6384341314e25d94fa3189814dd5e68 | 42,113 |
def input_position():
"""
input the position option for pasted QR code
"""
option = input('Please select the position (1:left-top, 2:right-top, 3:left-bottom, 4:right-bottom, 5:left-middle, 6:right-middle) for QR code: ')
if option == '':
pos = 1
print(' Use the default position, ... | 80e2b69d04991781515790c4fd0fbb6719d3e6d4 | 42,114 |
from datetime import datetime
def tow_to_datetime(tow, week):
"""
Convert a GPS Week and Time Of Week to Python datetime object.
Does *not* convert from GPST to UTC.
Fractional seconds are supported.
Parameters
----------
tow : time of week in seconds
weeks : gps week
Returns
... | e22a3d90184edc7ded540de89a12ffe262fa3080 | 42,115 |
import argparse
def parse_args():
"""
Parse input arguments
"""
parser = argparse.ArgumentParser(description='Train a Fast R-CNN network')
parser.add_argument('--dataset', dest='dataset',
help='training dataset',
default='hico_full', type=str)
parser.add_argumen... | 40bb22612bf5627f7dc0f663fa03e1ba26c7e359 | 42,116 |
import random
def load_batch(batchsize, mode, gt_type):
"""
This function loads a batch for mlnet training.
:param batchsize: batchsize.
:param mode: choose among [`train`, `val`, `test`].
:param gt_type: choose among [`sal`, `fix`].
:return: X and Y as ndarray having shape (b, c, h, w).
... | 3af708c683ea63933b485c45ed1a5bcd7dc198f5 | 42,117 |
def Helheim_map(service='ESRI_Imagery_World_2D', epsg=3413, xpixels=2000):
"""Function using Basemap to plot map for only Helheim Glacier
"""
m = Basemap(projection='npstere', boundinglat=70, lon_0=315, epsg=epsg, llcrnrlon=320.3, llcrnrlat=66.1, urcrnrlon=322.4, urcrnrlat=67.6, resolution='h')
plt... | 07e0291e158e7e8acbd2f43f0bbb91d65f26f3a8 | 42,118 |
def return_countries():
"""
Get the countries available
:return: country JSON
"""
with open("country.json", "r") as country:
return country.read() | b927b6b4b6797a76fd047ed88c2809b66df206b9 | 42,119 |
def outer_product(a: Vector, b: Vector) -> Matrix2d:
"""
Given vectors a = (a1, a2, ..., an),
b = (b1, b2, ..., bm)
Returns a matrix of shape NxM
A = [ a1b1, a1b2, ..., a1bm,
.
.
.
anb1,... | 386c48e59967651b03ae10f706c37382adba14b5 | 42,120 |
def epsilon_greedy_policy(Qs, nA, i_episode, epsilon=None):
"""epsilon greedy policy
env: Gym environment
s: state
i_episode: index of current episode -> epsilon should reduce when i increase
eps: customized epsilon
"""
epsilon = 1 / i_episode if epsilon is None else epsilon
... | 22ff8762da5df54ac2ebd60e471abfa7397b8af0 | 42,121 |
from datetime import datetime
def BJtime(mergeTime):
"""
utc时间转换北京时间
"""
mergeTime = mergeTime.replace('T', ' ').replace('Z', '')
mergeTime = datetime.datetime.strptime(mergeTime, '%Y-%m-%d %H:%M:%S')
mergeTime = mergeTime + datetime.timedelta(hours=8)
mergeTime = datetime.datetime.strftim... | d0929ec8988a41148b2e5bdc63c13ad6f6434a64 | 42,122 |
def make_simple_templating_function(template):
"""Factory for making a templating function that applies the context object to the given template to create a
string.
Arguments:
template -- Templated string, whose values will be filled at run-time from the passed context.
For example, the... | e562c9d217ca892467b60c30f4806987eeffa4d4 | 42,123 |
def flatten_to_single_ndarray(input_):
"""Returns a single np.ndarray given a list/tuple of np.ndarrays.
Args:
input_ (Union[List[np.ndarray],np.ndarray]): The list of ndarrays or
a single ndarray.
Returns:
np.ndarray: The result after concatenating all single arrays in input_.... | 37f0aa6272b421481bef044f87a8bfe2ab1bb134 | 42,124 |
def get_pbs_node_requirements(sys_settings,node_count):
"""Get the cpu and memory requirements for a given number of nodes
Args:
sys_settings (dict): System settings dict, as supplied from config_manager
node_count (int): Number of whole nodes on target system
Returns:
dict... | f4fd12dee6608a87e6c8b0f2f56e245e6be7c0fc | 42,125 |
from unittest.mock import Mock
def api_fixture():
"""Define a fixture for simplisafe-python API object."""
api = Mock()
api.refresh_token = "token123"
api.user_id = "12345"
return api | 2270391b02dd02de71a312ed6d6edd780c5bdff2 | 42,126 |
def checkArray(comment,check,expected,tol=1e-7):
"""
This method is aimed to compare two arrays of floats given a certain tolerance
@ In, comment, string, a comment printed out if it fails
@ In, check, list, the value to compare
@ In, expected, list, the expected value
@ In, tol, float, optional, ... | 99b79234df19d3fb69a245f6e52e7d24967e599f | 42,127 |
import subprocess
def task_interactive():
"""Run the Docker container in interactive mode"""
def run():
cmd = [
'docker',
'run',
'-it',
'--rm',
'-w',
'/app',
'--volume',
'%s/:/app' % CONFIG['volume_path'],
... | bc2f342f6dc86e26fb2c5555fd0ebfbdb150ec20 | 42,128 |
import numpy
def classificationModel(model,dataFrame,predictors,outcome,nFolds:int):
"""
Method for computing accuray and cross-validation based upon given model
"""
if dataFrame is None:
return None
model.fit(dataFrame[predictors],dataFrame[outcome])
predictions=model.predict(dataFram... | 30c3bdeef0c499d535313917938eeefc9297a6f9 | 42,129 |
def simu_abstract_div_stutter(ts):
"""Compute the coarsest divergent stutter bisimulation abstraction for a Finite Transition System.
@param ts: input finite transition system, the one you want to get
its abstraction.
@type ts: L{FTS}
@return: the abstraction, and the corresponding... | 03e38bcebc3058fd794cd84563947803431e683b | 42,130 |
def runtime_error(exception):
"""Handle a runtime error, e.g., an unresponsive server.
:param exception: Exception caught.
:return: constants.EXIT_CODE_ERR
"""
parser.print_error(msg=exception)
return constants.EXIT_CODE_ERR | 96abf6998e2619356410ec32d4d24b3a523c6471 | 42,131 |
def donchian(candles: np.ndarray, period=20, sequential=False) -> DonchianChannel:
"""
Donchian Channels
:param candles: np.ndarray
:param period: int - default: 20
:param sequential: bool - default=False
:return: float | np.ndarray
"""
if not sequential and len(candles) > 240:
... | dc2d345e93fa892d0b963ef907811f6c309d8b47 | 42,132 |
def genball(npt, ndim, rstate=None):
""" Simulate points in ndim ball """
# use Barthe2005
x = rstate.standard_normal(size=(npt, ndim))
y = rstate.exponential(0.5, size=npt)
x1 = x / np.sqrt((y + (x**2).sum(axis=1)))[:, None]
return x1 | c73fba269e7c7a06af0a6ed9555166cfaf5cd17b | 42,133 |
def autoenc_quantize(x, nbits, nmaps, do_training, layers=1):
"""Autoencoder into nbits vectors of bits, using noise and sigmoids."""
enc_x = tf.reshape(x, [-1, nmaps])
for i in xrange(layers - 1):
enc_x = tf.layers.dense(enc_x, nmaps, name="autoenc_%d" % i)
enc_x = tf.layers.dense(enc_x, nbits,... | eab1e7df449246c22577ab72bab3696a1e6c0d49 | 42,134 |
def grab_liberty_siam_dataset(pairs=250000):
"""
References:
http://www.cs.ubc.ca/~mbrown/patchdata/patchdata.html
https://github.com/osdf/datasets/blob/master/patchdata/dataset.py
Notes:
"info.txt" contains the match information Each row of info.txt
corresponds corresponds ... | b3293f63d1bbcf830388507446f73b185fbc0ea5 | 42,135 |
def ndcg_at_k(
rating_true,
rating_pred,
col_user=DEFAULT_USER_COL,
col_item=DEFAULT_ITEM_COL,
col_rating=DEFAULT_RATING_COL,
col_prediction=PREDICTION_COL,
relevancy_method="top_k",
k=DEFAULT_K,
threshold=DEFAULT_THRESHOLD,
):
"""Normalized Discounted Cumulative Gain (nDCG).
... | b4529260aa2be6619735497daaca5a733ea09e20 | 42,136 |
def select_table_value_from_page(**params):
"""从画面上选择出一个列表的数据"""
return """\
with open('../script_lib/parse_table_value.js', encoding='utf-8') as file:
script = file.read()
header = driver.execute_script(script, '{header_selector}')[0]
result = driver.execute_script(script, '{data_selector}')
... | d9e5087b50188b6c4e4125bfa396ae2e9b02a6db | 42,137 |
def create_canvas(height, width):
"""Creates blank canvas given height and width. Returns Canvas object."""
new_canvas = Canvas(height, width)
return new_canvas | 759d9194d1391e8852729593f4a8dcbad3ee390f | 42,138 |
def families_lens():
"""."""
return ['Lens', 'LensRev'] | dd1c39ca606f100fc3efbf22be2a402507d262de | 42,139 |
async def jobs_list(
db=Depends(get_db),
):
"""
Get all jobs
"""
try:
return get_jobs(db)
except Exception as e:
return JSONResponse(status_code=status.HTTP_400_BAD_REQUEST, content=f'{str(e)}') | 0ace5eed845161f43da78c54986934d094a148c3 | 42,140 |
def load_training_data(direc: str = 'data/training/training_articles.csv', size: int = 50):
"""
opens text file with sample articles to train and tokenizes
"""
with open(direc) as f:
return [prepare_text_for_lda(line) for line in f] | 33fb765dc6aa1a022b2faba236c891c53139c50c | 42,141 |
def reduce2scalar_seasonal_zonal( mv, seasons=seasonsyr, region=None, latmin=None, latmax=None, vid=None, gw=None ):
"""returns the mean of the variable over the supplied latitude range (in degrees).
The computed quantity is a scalar but is returned as a cdms2 variable, i.e. a MV.
The input mv is a cdms2 va... | 5716c69733062ba39a5083a10edb202b638bec51 | 42,142 |
def upsert_org(datadict, ckanapi, debug=False):
"""Create or update organisations through a ckanapi as per given datadict.
Arguments:
datadict A dict with information on organizations, such as:
{
'logo_url': 'http://www.dfes.wa.gov.au/_layouts/images/FESA.Mobile/dfes_print.png',
... | d990925265be60f081f4beb450d38adfc4cf03b6 | 42,143 |
def parallel(iterable, count, callable, *a, **kw):
"""
Concurrently fire C{callable} for each element in C{iterable}.
Any additional arguments or keyword-arguments are passed to C{callable}.
@type iterable: C{iterable}
@param iterable: Values to pass to C{callable}.
@type count: C{int}
... | 0f7d277d0c8719a4e1e00a9e4a4f988a7778ddb4 | 42,144 |
def create_user_object(uname, psswd,sub_u):
"""Return a User object with given information."""
return User(
username=uname,
password=pwd_context.hash(psswd),
sub_user=sub_u
) | aa8f6bf5197798fc98a1ea9dd977dcbe3982fe93 | 42,145 |
def myreplace(old, new, s):
"""Replace all occurrences of old with new in s."""
result = " ".join(s.split()) # firsly remove any multiple spaces " ".
return new.join(result.split(old)) | 4355251d3c52424041ce86b2449843c565beb301 | 42,146 |
import re
def need_analyzer(args):
""" Check the intent of the build command.
When static analyzer run against project configure step, it should be
silent and no need to run the analyzer or generate report.
To run `scan-build` against the configure step might be neccessary,
when compiler wrapper... | 8dc2f6cb3071cf3d8190261c4136670b2dec5b5a | 42,147 |
import torch
def angular_terms(Rca: float, ShfZ: Tensor, EtaA: Tensor, Zeta: Tensor,
ShfA: Tensor, vectors12: Tensor) -> Tensor:
"""Compute the angular subAEV terms of the center atom given neighbor pairs.
This correspond to equation (4) in the `ANI paper`_. This function just
compute t... | 56b8cb281bd862eab6a8e39a8e4947a46b495e7d | 42,148 |
def cookie_session_name() -> str:
"""
Retorna o nome do cookie para a sessão.
"""
return "ticket_session" | eaa4517b0635ea8e57d07a46d90c6bcdc3d044e8 | 42,149 |
def query():
"""Display search requests and pagination via GET"""
if not request.args.get("search"):
return redirect(url_for("index"))
if request.args.get("start") is None or int(request.args.get("start")) < 0:
start = 0
else:
start = int(request.args.get("start"))
query = ... | 82f6f2db5dede75f7e6df31f8681b298986a75ac | 42,150 |
import random
def select_a_genome():
"""
This function randomly selects a genetic operation from following options to produce a genome:
1. Crossover two randomly selected genomes
2. Random selection from available genomes
3. Latest genome
4. Best fitness ever
5. Mutate genome with highest ... | 9db4e137cab04209817198c8c7da13886b7b2650 | 42,151 |
from re import X
from re import I
def prep_qubits(qubits: list, n: int):
"""
Generate a quil program which prepares given qubits in a state representing number n.
:param n: the number to write
:param qubits: qubit indexes to write the number n
:return: circuit to write number n on given qubits.
... | 5ad6fe7ab67e7f6ac8d57d9f3d209d9bf4e7bf32 | 42,152 |
def plot_seq_label(ax, X, Fs=1, color_label=[], direction='horizontal',
fontsize=10, time_axis=False, print_labels=True):
"""Plot label sequence in the style of annotations
Notebook: C4/C4S5_Evaluation.ipynb
Args:
ax: Axis used for plotting
X: Label sequence
Fs: ... | 02d798b855f056a5118125f2609fb2d44eea6789 | 42,153 |
def _sqrt_symbolic_denest(a, b, r):
"""Given an expression, sqrt(a + b*sqrt(b)), return the denested
expression or None.
Algorithm:
If r = ra + rb*sqrt(rr), try replacing sqrt(rr) in ``a`` with
(y**2 - ra)/rb, and if the result is a quadratic, ca*y**2 + cb*y + cc, and
(cb + b)**2 - 4*ca*cc is 0... | bea440797224e546f0aac8c93590020041047f86 | 42,154 |
def blackNormalizeImage(a):
"""
Normalizes numarray to fit into an image format
that is values between 0 and 255.
"""
#Minimum image value, i.e. how black the image can get
minlevel = 0.0
#Maximum image value, i.e. how white the image can get
maxlevel = 200.0
#Maximum standard deviations to include, i.e. pixe... | ac3cd6d8ea34982756ad806dc0e365b10c788604 | 42,155 |
def create_mfcc(path, sr=None, offset=0, duration=None):
"""Create an mfcc from the passed path"""
wave = AudioSegment.from_wav(path)
mono = wave.channels != 1
if duration:
y, sr = librosa.load(path, sr=sr, mono=mono, offset=offset, res_type='kaiser_fast')
else:
y, sr = librosa.load(... | 442736b0a031c2fb7ce2ab95c13c5ecbd114d472 | 42,156 |
def maybe_pad(draw, regex, strategy, left_pad_strategy, right_pad_strategy):
"""Attempt to insert padding around the result of a regex draw while
preserving the match."""
result = draw(strategy)
left_pad = draw(left_pad_strategy)
if left_pad and regex.search(left_pad + result):
result = left... | 6e3a6f1481e9d432b63cc237e68f89035aa56588 | 42,157 |
import re
def parseSections (fd):
"""
Quick&Dirty parsing for GNU ld’s linker map output, needs LANG=C, because
some messages are localized.
"""
sections = []
# skip until memory map is found
found = False
while True:
l = fd.readline()
if not l:
break
... | f33c430e4f76f6913fd63fa5bea9b48111a87451 | 42,158 |
def from_year_fraction(date: float):
"""
this function takes a date in float as input and return datetime as output
Parameter:
--------
date: float such as 2000.02
Return:
--------
the corresponding datetime object
"""
if type(date).__name__ != 'float':
raise Ty... | d7d8c2412ff5dcb4ad10d508170c76964768b431 | 42,159 |
def even(value):
"""Simple validator defined for test purpose"""
return not (int(value) % 2) | 1774e55ef53799ff16f232c3ca51c322cadf1d54 | 42,160 |
import sys
def diff(a, b, sline=0):
"""
Return a list of deletions and insertions that will turn 'a' into 'b'. This
is done by traversing an implicit edit graph and searching for the shortest
route. The basic idea is as follows:
- Matching a character is free as long as there was no
... | 2503da131c6173d3f5013dfed578de0fa62139de | 42,161 |
def new_webui_log_file():
"""Create new logging files for web ui."""
ui_stdout_file, ui_stderr_file = new_log_files(
"webui", redirect_output=True)
return ui_stdout_file, ui_stderr_file | beef8637b9e14b20ab714dae42d7d9698a87eec0 | 42,162 |
from typing import Optional
def get_quarter_start(x: Optional[Date] = None) -> Date:
"""
Returns the quarter start as of the given date.
>>> get_quarter_start(Date(2017, 1, 1))
datetime.date(2017, 1, 1)
>>> get_quarter_start(Date(2017, 5, 31))
datetime.date(2017, 4, 1)
>>> get_quarter_sta... | 7a79dc9e01413dd6a802e30a89d5a52fd6dae71a | 42,163 |
def _compute_J(x, window_starts, L):
"""Compute the cost, which is proportional to the
difference between pairs of windows"""
# Get all windows and zscore them
N_windows = len(window_starts)
windows = np.zeros((N_windows, L))
for w in range(N_windows):
temp = x[window_starts[w]:window_s... | 0d035607d416d3e0cd23b0858ae869e04f1c5df5 | 42,164 |
def getAppLink(dic):
"""Returns the Link for Chapter Application Form.
dic -- Dictionary from the JSON with all values.
"""
return str(dic["content"]["$t"]).split(',')[3].split(' ')[2].strip() | 4525a9aa11a293666f14b22507ee1d8e67607cdd | 42,165 |
import os
def create_single_env(env_name, seed, dmlab_homepath, use_monitor,
split='train', vizdoom_maze=False, action_set='',
respawn=True, fixed_maze=False, maze_size=None,
room_count=None, episode_length_seconds=None,
min_goal_... | b06d5bf280f3d556dbb9d9f15a7117f5832bab99 | 42,166 |
def test_parameter_3():
"""
Feature: Check the names of parameters.
Description: Check the name of parameter in init.
Expectation: No exception.
"""
class ParamNet(Cell):
def __init__(self):
super(ParamNet, self).__init__()
self.param_a = Parameter(Tensor([1], ms.... | 4f40fe29fa404a6a7d0231d97698cf1bfb22911b | 42,167 |
def veh_search_for_immediate_request(sim_time, prq, fleetctrl, list_excluded_vids=[]):
"""This function can be used to find pooling vehicles for an immediate service of a request.
:param sim_time: current simulation time
:param prq: PlanRequest to be considered
:param fleetctrl: FleeControl instance
... | 975200901be03626025f5483771cf30e82dab5b7 | 42,168 |
def rebase(df_: pd.DataFrame, base_year: int) -> pd.Series:
"""Rebase values to a given base year"""
base_values = (
df_.loc[df_.year.dt.year == base_year].set_index("iso_code")["value"].to_dict()
)
return round(100 * df_.value / df_.iso_code.map(base_values), 3) | 6483225b6f29b82f7c17db36d4d1aaad832abc59 | 42,169 |
def big_sliding_window(raster):
"""Creates 3D array organizing local neighbors at every index
Returns a raster of shape (L,W,9) which organizes (along the third
dimension) all of the neighbors in the original raster at a given
index, in the order [NW, N, NE, W, 0, E, SW, S, SE]. Outputs are
ordered... | 1d4592dbcd31bade5dde774f5814b6739229c323 | 42,170 |
import os
import shutil
def module_hrun(name, base_url, module, receiver):
"""
异步运行模块
:param env_name: str: 环境地址
:param project: str:项目所属模块
:param module: str:模块名称
:return:
"""
logger.setup_logger('INFO')
kwargs = {
"failfast": False,
}
runner = HttpRunner(**kwargs)... | e3ae32f801999e18800b7555428e2c9b06281319 | 42,171 |
def met_gfssdJ1_3sopt_tr50(P, Q, data_source, n, r, J=1, tr_proportion=0.5):
"""
FSSD-based model comparison test
* Use J=1 test location by default (in the set V=W).
* 3sopt = optimize the test locations by maximizing the 3-model test's
power criterion. There is only one set of test lo... | f41da6da3b64a9f926335381d84d3294ccbc6808 | 42,172 |
def find_permutation(s, pattern):
"""Find presence of any permutation of pattern in the text as a substring.
>>> find_permutation("oidbcaf", "abc")
True
>>> find_permutation("odicf", "dc")
False
>>> find_permutation("bcdxabcdy", "bcdxabcdy")
True
>>> find_permutation("aaacb", "abc")... | ba823208ed92fc3da9725081f3dfca87c5a47875 | 42,173 |
from typing import Callable
def crownibp_bound_propagation(
function: Callable[..., Nest[Tensor]],
*bounds: Nest[GraphInput]) -> Nest[LayerInput]:
"""Performs Crown-IBP as described in https://arxiv.org/abs/1906.06316.
We first perform IBP to obtain intermediate bounds and then propagate linear
bounds ... | ba6b572491cd8b807b75cb7fbeae85fd73787b81 | 42,174 |
def radioButtons(
widget,
master,
value,
btnLabels=(),
tooltips=None,
box=None,
label=None,
orientation=Qt.Vertical,
callback=None,
**misc
):
"""
Construct a button group and add radio buttons, if they are given.
The value with which the buttons synchronize is the ind... | 21aff75e25caf0d64c00b93b41018edb3fa2a3d3 | 42,175 |
def remove_plane(z, x, y):
"""Remove linear plane from z values. All need to have same shape!
Parameters
----------
z : [type]
[description]
x : [type]
[description]
y : [type]
[description]
"""
X_reg = np.vstack([x.flatten(), y.flatten(), x.flatten()*y.flatten()... | aa006f90158807caabef52cbe6884ed86fb3f4ae | 42,176 |
def preprocess_df(df: pd.DataFrame, userdict: str = None, jumanpp: bool = False) -> pd.DataFrame:
"""Perform preprocessing for given dataframe,
including, binarizing p/n labels to 1/0, normalization (JP), adding column of tokenized sentence.
"""
df = _binarize_pn(df)
if _check_lang(df) == 'ja':
... | f226ca7cdc87cbb394152989e837855b28928539 | 42,177 |
import os
def local_help_filename(pkg_info, help_file):
"""
Determine what the full file name of a help file from a given package would
be if it was stored locally
"""
return os.path.join(sublime.packages_path(), pkg_info.doc_root, help_file) | 7961dcc9aa235251437c0c3cb2e2c4a33e67d7db | 42,178 |
import torch
def get_model_predictions(data, model):
"""
Function to get prediction for a data point (datapoint being a tokenized text segment)
Input: data to predict, model to predict with
Output: prediction for input data
"""
output = model(torch.tensor([data['input_ids']]), attention_... | 06be220420a5bd556d9263ee05d56ddabc3f952f | 42,179 |
def p2p_gnuetella08():
"""
Returns the graph from: https://snap.stanford.edu/data/p2p-Gnutella08.html,
where we preprocess it to only keep the largest connected component
:return: undirected NetworkX graph
"""
graph = nx.read_edgelist(graph_dir + "p2p-Gnutella08.txt")
return graph.subgraph... | 0762b3ea1dcb19666c4c776d4fbfb1587254725c | 42,180 |
def object_lookup_command():
""" Sample query: querystring = {'filter':'subnet','count':'50','exact_subnet':'1.1.1.1'} """
querystring = {
'filter': 'subnet',
'count': '50',
'exact_subnet': demisto.args()['ip']
}
if not valid_ip(querystring['exact_subnet']):
return_error(... | facb66a246ad59eafb91510f4bcbdc33d0fb35ea | 42,181 |
def isObsMosaic(data, indx, mtype=MOSAIC_TYPES):
"""
Returns True or False if an observation is a mosaic of a
type listed in MOSAIC_TYPES.
data : Contains data from readObservations() in the DATA key
indx : Row number within data
mtype : A list of mosaic types
The typ... | abb6f92316ec00aae8c916ff486086d42c224110 | 42,182 |
import re
def most_probable_alleles(allele_list):
"""
Identify the most probable haplotype in a list
:param list allele_list: List of tuples of (allele, p_value)
:return: List of 2 most probable alleles in the group
:rtype: list[str]
"""
all_alleles = defaultdict()
# First collect all... | 6efd5a5063e5ee5541f05f8bb2036f3282cc16eb | 42,183 |
def bootstrap_freq_sweep_ci(df, quantity, replicate_identifier,
n_bootstrap, ci, estimator=np.mean):
""" Gets bootstrap confidence interval for an estimator of
frequency sweep (or time sweep) data. Boot strap can be either a
percentile bootstrap of an estimator of a studentized bootstra... | 1aa3db386dd3d437fd2ea7815d88840cb3d2912b | 42,184 |
def atcab_sha_hmac(data, data_size, key_slot, digest, target):
"""
Use the SHA command to compute an HMAC/SHA-256 operation.
Args:
data Message data to be hashed. (bytearray or bytes)
data_size Size of data in bytes. (int)
key_slot Slot key id to ... | 12abcb1c7eb42c8db22289885fa3aba4f6377105 | 42,185 |
import json
def get_embedded_json(port, flag):
""" Reads out uart from port and looks for the flag. The flag is valid json
with the values wanted by the programmer.
"""
with Serial(port, 115200, timeout=1) as ser:
wd_parse_retries = 0
while wd_parse_retries < 7:
# 1. Use ... | 992f94fea23e61583fc6439bb14dd750a453e40b | 42,186 |
def ra_parser(lines):
"""return a list from RA lines.
The RA (Reference Author) lines list the authors of the paper (or other
work) cited. RA might be missing in references that cite a reference group
(see RG line). At least one RG or RA line is mandatory per reference block.
All of the authors ar... | d34eefdeb1b33628ad9525160cb93bc9c0e1943e | 42,187 |
def load_markercolors():
"""
Returns a dictionary mapping sources of the E. coli data with standard colors
and glyphs. This ensures constant marking of data across plots.
"""
colors, _ = get_colors()
mapper = {
'Bremer & Dennis, 2008': {'m':'X', 'm_bokeh':'circle_dot'},
'Brunsch... | 5711f7b32b1dcb7b88681fdd437957482406d2af | 42,188 |
import requests
def get_Dna_Token(dnac):
"""
Intent-based Authentication API call
The token obtained using this API is required to be set as value to the X-Auth-Token HTTP Header
for all API calls to Cisco DNA Center.
:param: dnac
:return: Token STRING
"""
url = 'https://{}/dna/system/... | ab55d6969e9d5521aea108e499061a2670a331cb | 42,189 |
def un_map_pack_response_edition_modifier(response_modifier):
"""
Returns an un-map-packer to the given response modifier for message edition endpoints.
Parameters
----------
response_modifier : `None`, ``ResponseModifier``
The response modifier to un-map-pack if any.
Returns
... | 277ab1ec6d9c6ed3283bcdbde0842276c1940efb | 42,190 |
def _extract_non_mrjob_tags(cluster):
"""get tags from a cluster as a dict, excluding tags starting with
``__mrjob_``"""
return {k: v for k, v in _extract_tags(cluster).items()
if not k.startswith('__mrjob_')} | d0ef1066cd4f6b340d915a15ea9790dbca9ec74b | 42,191 |
def calc(diff, pool, torment=5, charmed=1):
"""
api call to get the probabilities of a dice pool.
"""
root = wodDice.PoolCalc(pool, diff, torment, charmed)
s = root.summary()
result = {
'pool': pool,
'diff': diff,
'torment': torment,
'charmed': charmed,
'F... | 432e3013ac452ae596f0269a769059c19fd8a4b1 | 42,192 |
def update_xml_for_new_img(current_ome_xml_str, new_xyzct, bf_dtype, is_rgb, pixel_physical_size_xyu=None, channel_names=None, perceputally_uniform_channel_colors=False):
"""Update dimensions ome-xml metadata
Used to create a new ome-xml that reflects changes in an image, such as its shape
If `current_ome... | 629c0d545560bce60e4666e90414bb0dc8e6961e | 42,193 |
from .. import url_name as _url_name
def url_name(context):
""" Returns URL name of the current request.
Example::
{% url_name as current_url_name %}
{% if current_url_name != 'auth_login' %}
<li>
<a href="{% url 'auth_login_next' request.get_full_path|urlencode %}">
... | f8d159f715e1054fa543f0d2ba1c795c5ea7f995 | 42,194 |
def lowest_common_ancestor(G, node1, node2, default=None):
"""Compute the lowest common ancestor of the given pair of nodes.
Parameters
----------
G : NetworkX directed graph
node1, node2 : nodes in the graph.
default : object
Returned if no common ancestor between `node1` and `node2`... | 39c0e53b823f9303cb11485bf0932ddfb5c33c2b | 42,195 |
def cross_entropy(prediction, target):
"""
prediction should be probabilities [N × C], target should be label index (0 ~ C-1)
:param prediction: size: [N, C]
:param target: size: [N]
:return:
"""
return F.cross_entropy(prediction, target) | b0afc3165d3dc3f36ab9ff712e8dcfb65ad683de | 42,196 |
import six
def resolve_class(classref):
"""Attempt to return a Python class for the input class reference.
If `classref` is a class or None, return it. If `classref` is a
python classpath (e.g., "foo.bar.MyClass") import the class and return
it.
Args:
classref: A fully-qualified Python p... | 5d6cea47b178bc217ff0ed9c8eb128641ce7dc25 | 42,197 |
def nms(bboxes, score_threshold, iou_threshold, sigma=0.3):
"""
:param bboxes:
假设有N个bbox的score大于score_threshold,那么bboxes的shape为(N, 6),存储格式为(xmin, ymin, xmax, ymax, score, class)
其中(xmin, ymin, xmax, ymax)的大小都是相对于输入原图的,score = conf * prob,class是bbox所属类别的索引号
:return: best_bboxes
假设NMS后剩下N个bbox,那么b... | 1a95bd0e3304dd7bff1953c061f5b1b18fc80c63 | 42,198 |
def QCLog_Meta():
"""QCLog_Meta() -> MetaObject"""
return _DataModel.QCLog_Meta() | 4d209a16efe053ca59eb0d23a50e4e521bc45fc0 | 42,199 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.