content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def render():
"""Test rendering pipeline for development."""
import app
test_dir = '_build'
cache_dir = os.path.join(test_dir, '_cache')
product_data = app.dashboard.loaders.load_dataset_with_caching(
cache_dir, 'sqr-013', 'product')
edition_data = app.dashboard.loaders.load_dataset_wi... | 5,288,400 |
def average_trip_length_with_protion_of_trips_longer_than_30_min(filename):
"""
This function reads in a file with trip data and reports the number of
trips made by subscribers, customers, and total overall.
"""
with open(filename, 'r') as f_in:
# set up csv reader object
reader = cs... | 5,288,401 |
def gradient_check_n(parameters, gradients, X, Y, epsilon=1e-7, print_msg=False):
"""
Checks if backward_propagation_n computes correctly the gradient of the cost output by forward_propagation_n
Arguments:
parameters -- python dictionary containing your parameters "W1", "b1", "W2", "b2", "W3", "b3"... | 5,288,402 |
def is_short_flag_reason(flag: str) -> Optional[str]:
"""
Checks if the given string is a valid short flag.
:param flag: The string to check.
:return: None if it is a valid short flag,
or the reason if not.
"""
# Short flags must start with '-'
if not flag.star... | 5,288,403 |
def text_from_doc_list(doc_list):
"""
extract a text from list of html elements.
"""
return [doc.text for doc in doc_list] | 5,288,404 |
def renderHTML(maxrows,sortby,search,descend):
"""generate HTML table with sorted filtered results"""
data_sorted = sorted(indexnotebooks(), key=lambda item: item[sortby])
if len(search)>0:
data_sorted = list(filter(lambda x:x['path'].lower().find(search.lower())>-1,data_sorted))
nitems = len(da... | 5,288,405 |
def supports_librabbitmq() -> bool | None:
"""Return true if :pypi:`librabbitmq` can be used."""
if _detect_environment() == 'default':
try:
import librabbitmq # noqa
except ImportError: # pragma: no cover
pass
else: # pragma: no cover
... | 5,288,406 |
def _create_enums(properties):
"""Returns a list of Enums to be generated"""
enums = {}
for property_ in properties:
# Only generate enums for keyword properties that do not require includes.
if property_['field_template'] in ('keyword', 'multi_keyword') and len(property_['include_paths']) =... | 5,288,407 |
def get_config_file(config=None):
"""
This method parses properties and returns the value of CONFIG_FILE.
If undefined, VACCA_CONFIG is returned as fallback.
"""
global VACCA_CONFIG,VACCA_DIR
print('-')*80
if not config:
VACCA_CONFIG = get_env_variable('VACCA_CONFIG',DB_HOST)
... | 5,288,408 |
def adder():
"""Adds all the numbers the user gives until "done" is typed."""
print("Type a number or 'done' when finished")
result = 0
while True:
try:
val = input("Please give input: ")
if val == "done":
break
else:
result += ... | 5,288,409 |
def test_normalized_wup_verbs(id1, id2, upper, similarity):
"""Tests whether the normalized wup score for verbs is correct."""
synset1 = germanet_data.get_synset_by_id(id1)
synset2 = germanet_data.get_synset_by_id(id2)
sim = relatedness_verbs.wu_and_palmer(synset1=synset1, synset2=synset2, normalize=Tru... | 5,288,410 |
def fixed_start_fourier_df(pd_index, freq, k, name="ffcomp"):
"""
Generates fourier features, with a fixed starting point
"""
assert isinstance(
pd_index, pd.Index
), "Provide pd.Index subclass as the first argument"
assert pd_index.freq, "freq for input index is not defined"
assert ... | 5,288,411 |
def mask_accessions(subset, taxids):
"""
filter lines from idmap that are not in set of masked taxids,
return list of accessions
"""
accessions = []
mapfile = "%s/%s.taxid_map.gz" % (INDIR, subset)
if os.path.isfile(mapfile):
with Popen(['pigz', '-dc', mapfile], stdout=PIPE, encoding... | 5,288,412 |
def vocal():
"""Transcribe vocal notes in the audio.""" | 5,288,413 |
def load_obj(filename):
"""
load from a Wavefront obj file
"""
vertices_pool = []
uvs_pool = []
normals_pool = []
indices = []
vertices = []
normals = []
uvs = []
vertices_map = {}
for line in open(filename, 'r'):
line = line.strip()
splitted = re.sp... | 5,288,414 |
def prepare_dataset():
"""
Download out.csv, cast the right datatypes and convert date
:return: Dataframe - columns = ['timestamp', 'article_id', 'click', 'date']
"""
df = pd.read_csv('./data/R6A/out.csv', usecols=['timestamp', 'article_id', 'click'], sep=' ')
df = df.astype({'timestamp': int, ... | 5,288,415 |
def mse(x, y, axis=None):
"""Mean squared error"""
if np.isclose(x.size, 0.0) and np.isclose(y.size, 0.0):
return 0.0
elif np.isclose(x.size, 0.0):
return np.mean(np.absolute(y))
elif np.isclose(y.size, 0.0):
return np.mean(np.absolute(x))
min_l = min(len(x), len(y))
x... | 5,288,416 |
def telemetry(fn):
"""
Decorator for CLI and other functions that need special Sentry client handling.
This function is only required for functions that may exit *before* we set up
the ._raven_client object on the Api instance *or* that specifically catch and re-raise
exceptions or call sys.exit dir... | 5,288,417 |
def detect(sess, net, im_file, mode='normal', cls='person', cls_ind=1):
"""Detect all objects of a single class in an image using pre-computed object proposals."""
im = cv2.imread(im_file)
if mode == 'fast':
scores, boxes = im_detect_fast(sess, net, im)
else:
scores, boxes = im_dete... | 5,288,418 |
def is_write(node):
"""Try to find write primitives.
Looking for things like::
*(_DWORD *)(something) = v38
arr[i] = v21
TODO: Rather rough, it is a first version...
:param node: a :class:`controlFlowinator` node
:type node: :class:`cinsn_t` or :class:`cexpr_t`
:return: True ... | 5,288,419 |
def decode(
data: _ByteString,
errors: _Str = 'strict'
) -> Tuple[str, int]:
"""Convert a bytes type of escaped utf8 hexadecimal to a string.
Args:
data (bytes or bytearray or memoryview): The escaped utf8
hexadecimal bytes.
errors (str or :obj:`~UserString`): The er... | 5,288,420 |
def reset_console_line(out=sys.stdout, length=PROGRESS_BAR_WIDTH):
"""Returns cursor to first column.
"""
out.write("\b" * (length + 1))
out.flush() | 5,288,421 |
def sort_chans(chans):
"""
A utility function to sort channel codes into Z, N, E or Z, 1, 2
order.
"""
sorted_chans = []
for chan in chans:
if chan[2] == "Z":
sorted_chans += [chan]
for chan in chans:
if chan[2] == "N" or chan[2] == "1":
sorted_chans +... | 5,288,422 |
def encoding_space_to_vexvalid(space):
"""Input string, output number"""
return _space_id[space] | 5,288,423 |
async def async_setup_entry(
hass: core.HomeAssistant, entry: config_entries.ConfigEntry
) -> bool:
"""Set up platforms from a ConfigEntry."""
url = entry.data["url"]
hass.data[DOMAIN][entry.entry_id] = SensorManager(hass, url)
if not entry.unique_id:
hass.config_entries.async_update_entry(... | 5,288,424 |
def normalize(df_origin):
"""Fill missing values, drop unneeded columns and convert columns to appropriate dtypes"""
df = df_origin.copy()
drop_columns = ["name", "owner", "repository"]
for c in drop_columns:
if c in df.columns:
df.drop(c, axis=1, inplace=True)
for c in df.column... | 5,288,425 |
def check_file_isvid(filename):
"""
checks if a file has a video extension, accepted files are: '.mp4', '.mpg', '.avi'
:param filename: (str) name of the file
:return: (bool)
"""
list_extensions = ['.mpg', '.MPG', '.mp4', '.MP4', '.AVI', '.avi']
if filename[-4:] in list_extensions:
r... | 5,288,426 |
def open(filename, mode="r"):
"""
Open a file for CSV mode in a Python 2 and 3 compatible way.
mode must be one of "r" for reading or "w" for writing.
"""
if sys.version_info[0] < 3:
return io.open(filename, mode + "b")
return io.open(filename, mode, encoding="utf-8", newline="") | 5,288,427 |
def test_ok(
api_client: TestClient,
token_service: TokenService,
) -> None:
"""Test a successful request."""
token_service.get_user_id.return_value = 1
token = "token"
password = "password"
response = api_client.post(
f"{URL}?token={token}",
data={"password": password},
... | 5,288,428 |
def is_setext_underline(line: str) -> bool:
"""Evaluates whether a line could be the underlining for a setext heading
Examples:
```
---
==
```
Args:
line: The line to evaluate
Returns:
True if the line is could underline an setext heading. False other... | 5,288,429 |
def test_calculate_modifier():
"""Test that modifier is calculated properly."""
tackle = BaseMove(**MOVE_DATA["tackle"])
exploud = Pokemon(name="exploud", moves=["return"])
floatzel = Pokemon(name="floatzel", moves=["shadowball"])
gengar = Pokemon(name="gengar", moves=["tackle"])
regirock = Poke... | 5,288,430 |
def build_directories(root_dir):
"""Constructs the subdirectories output, stderr, stdout, and jobs in the
passed root directory. These subdirectories have the following roles:
jobs Stores the scripts for each job
stderr Stores the stderr output from SGE
stdout ... | 5,288,431 |
def get_disparity_map(imageL: np.ndarray, imageR: np.ndarray,
disparity_matcher: cv.StereoMatcher = None,
disparity_filter: cv.ximgproc_DisparityFilter = None):
"""
Returns the disparity map based on image 1 and image 2.
example:
disparity = get_disparity_map... | 5,288,432 |
def batcher(iterable: Iterable[T], batch_size: int) -> Iterator[List[T]]:
"""Groups elements from `iterable` into batches of size `batch_size`.
>>> list(batcher("ABCDEFG", 3))
[['A', 'B', 'C'], ['D', 'E', 'F'], ['G']]
Unlike the grouper proposed in the documentation of itertools, `batcher`
doesn't... | 5,288,433 |
def fmul_ru(x, y):
"""
See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_fmul_ru.html
:param x: Argument.
:type x: float32
:param y: Argument.
:type y: float32
:rtype: float32
""" | 5,288,434 |
def clean_exit(exitcode, logfile, dry=False):
"""Close the logfile and exit with the given exit code
"""
if not dry and logfile is not None:
logfile.close()
sys.exit(exitcode) | 5,288,435 |
def get_qp_init_attr(cq, attr):
"""
Creates a QPInitAttr object with a QP type of the provided <qpts> array and
other random values.
:param cq: CQ to be used as send and receive CQ
:param attr: Device attributes for capability checks
:return: An initialized QPInitAttr object
"""
qp_cap =... | 5,288,436 |
def g():
"""Returns the graph traversal source. It takes care of closing the gremlin
connection after finishing the test. All vertices are deleted on both
the setup and teardown stage of this fixture."""
conn = gremlin.get_connection(get_gremlin_endpoint(), get_auth_mode())
g = traversal().withRemot... | 5,288,437 |
def dir_tree_run(action, base_dir):
"""
Apply funcition "action" to the individual files from tree directory
"""
_temp_f_name = ""
for f_name in os.listdir(base_dir):
_temp_f_name = os.path.join(base_dir,f_name)
if os.path.isdir(_temp_f_name):
dir_tree_run(action,_temp_f_... | 5,288,438 |
def TransWaleContGraph(Matrix, salve = 1, name = "Transformada Wavelet.png"):
"""Gera um gráfico em Matplotlib de linha feito para demonstração grafica da transformada de Wavelet
Argumentos:
Matrix: Uma Numpy Matrix da Transformada de Wavelet
Salve: 1 para gravar em PNG, 0 para exibir em Pop Up... | 5,288,439 |
def _extract_filename(upload_filename):
"""
Extract filename from fully qualified path to use if no filename provided
"""
import os.path
return os.path.basename(upload_filename) | 5,288,440 |
def update_observation(request):
"""
Update observation in config advisor.
Parameters
----------
request : a dict
Returns
-------
a readable information string in HttpResponse form
"""
if request.method == 'POST':
if request.POST:
task_id = request.POST.get(... | 5,288,441 |
def logger_setup():
"""
Creates a logger object and returns it
"""
logging.basicConfig(level=logging.DEBUG)
return logging.getLogger(__name__) | 5,288,442 |
def closed_isosigs(snappy_manifold, tries = 20, max_tets = 50):
"""
Generate a slew of 1-vertex triangulations of a closed manifold
using SnapPy.
>>> M = snappy.Manifold('m004(1,2)')
>>> len(closed_isosigs(M, tries=5)) > 0
True
"""
M = snappy.Manifold(snappy_manifold)
assert set... | 5,288,443 |
def test_create_project_date_created_overridden(client, boto3_session):
"""Create project with own date_created, should be overridden."""
proj_data_date_created_own = proj_data.copy()
proj_data_date_created_own["date_created"] = "test"
response = client.post(
tests.DDSEndpoint.PROJECT_CREATE,
... | 5,288,444 |
def valLoss(model, timeStep, csystem):
"""
The validation loss is the MSE between predicted and correct solution.
The loss is calculated seperatly for real and imaginary part
"""
x, y, t = SchrodingerEquationDataset.getInput(timeStep,csystem)
x = torch.Tensor(x).float().cuda()
y = torch.Ten... | 5,288,445 |
def get_attr_lookup(lines, attr_name):
"""
:arg lines: a list of :class:`TextLine` instances
:arg attr_name: A string, e.g. ``"y0"``, an attribute
of :class:`TextLine`
:returns: A dictionary of strings mapping values of
the given attribute to lists of :class:`TextLine`
sharing th... | 5,288,446 |
def test_concreteness():
"""A concrete sub-class of TextProvider can be instantiated."""
mock_arg = 'a'
concrete_prov = MockProvider(mock_arg) | 5,288,447 |
def encode_function_data(initializer=None, *args):
"""Encodes the function call so we can work with an initializer.
Args:
initializer ([brownie.network.contract.ContractTx], optional):
The initializer function we want to call.
args (Any, optional):
The arguments to pass to the i... | 5,288,448 |
def parse(renpy_nodes, renpy_ast, config):
"""
Parse all node to a useable format. The node Label named 'start' will be the
node with id '0'.
:param renpy_nodes: all nodes from renpy game (renpy.game.script.namemap)
:param renpy_ast: the renpy ast module (renpy.ast)
:returns: a dict... | 5,288,449 |
def repeat_img_per_cap(imgsfeats, imgsfc7, ncap_per_img):
"""Repeat image features ncap_per_img times"""
batchsize, featdim, feat_h, feat_w = imgsfeats.size()
batchsize_cap = batchsize*ncap_per_img
imgsfeats = imgsfeats.unsqueeze(1).expand(\
batchsize, ncap_per_img, featdim, feat_h, feat_w)
imgsfeats = i... | 5,288,450 |
def test_odd_qubits():
"""Tests the AlternatingAnsatz circuit is correct for an
odd number of qubits.
"""
a = AlternatingAnsatz(3)
print(a) | 5,288,451 |
def conv_layer(num_conv, output_size, nodes, children, feature_size):
"""Creates a convolution layer with num_conv convolutions merged together at
the output. Final output will be a tensor with shape
[batch_size, num_nodes, output_size * num_conv]"""
with tf.name_scope('conv_layer'):
nodes = [
... | 5,288,452 |
def send_message(request):
"""发送消息,AJAX POST 请求"""
sender = request.user
recipient_user_name = request.POST['to']
recipient = get_user_model().objects.get(username=recipient_user_name)
message = request.POST['message']
if len(message.strip()) != 0 and sender != recipient:
msg = Message.o... | 5,288,453 |
def half_preserve_energy_index(xfft, energy_rate=None, index_back=None):
"""
The same as the function preserve_energy_index but we discard half of the input signal since it is Hermitian
symmetric.
"""
initial_length = len(xfft)
half_fftsize = initial_length // 2 # the signal in frequency domain... | 5,288,454 |
def test_schedule_error_duplicate_task(publish_agent, cancel_schedules):
"""
Test error response for schedule request through pubsub. Test Agent=''.
This test case should be removed
once agent id are generated by the volttron platform
:param publish_agent: fixture invoked to setup all agents necess... | 5,288,455 |
def local_action_factory(action_classes, action_names, utter_templates):
# type: (List[Text], List[Text], List[Text]) -> List[Action]
"""Converts the names of actions into class instances."""
def _action_class(action_name):
# type: (Text) -> Action
"""Tries to create an instance by importin... | 5,288,456 |
def listPalettes(show=True, getdescriptions=True):
"""
Function listPalettes
Gets the list of available palette names
Arguments
show: If set (default) prints the list of palettes to the terminal as well
as returning it
getdescriptions: If set (default) returns and if required prints the
... | 5,288,457 |
def subtract(x, y):
"""
Subtracts two number
:param x: minuend
:param y: subtrahend
:return: difference between two numbers
"""
return x - y | 5,288,458 |
def file_name_convention() -> Dict:
"""
This function returns the file name taxonomy which is used by ImageAutoOutput and Dataset class
"""
file_name_convention = {"CT": "image",
"MR": "image",
"RTDOSE_CT": "dose",
"RTS... | 5,288,459 |
def detokenize(tokens):
"""
Detokenizing a text undoes the tokenizing operation, restores
punctuation and spaces to the places that people expect them to be.
Ideally, `detokenize(tokenize(text))` should be identical to `text`,
except for line breaks.
"""
text = ' '.join(tokens)
step0 = t... | 5,288,460 |
def read_file(path):
"""
lit le conllu et donne en sortie une liste d'objets Sent
chaque objet Sent a : .id, .text, .tree
les éléments de l'arbre d'un Sent sont des Word
un Word : .nid, .form, .lemma, .upos, .xpos, .feats, .head, .deprel, .deps, .misc
si le résultat est stocké dans une variable corpus on aura :
... | 5,288,461 |
def prepare_data_task1c(input_dir: str, output_dir: str, correction_file: str) -> None:
"""
Prepare task1c documents (decompress, rename, correct and sort).
The function creates two subdirectories within output_dir:
* decompressed: zip files are decompressed into this directory
* gold-standard-sorte... | 5,288,462 |
def from_dateutil_rrule(rrule):
"""
Convert a `dateutil.rrule.rrule` instance to a `Rule` instance.
:Returns:
A `Rrule` instance.
"""
kwargs = {}
kwargs['freq'] = rrule._freq
kwargs['interval'] = rrule._interval
if rrule._wkst != 0:
kwargs['wkst'] = rrule._wkst
kwarg... | 5,288,463 |
def test_extract_geometry():
""" purpose of the test is to test that geometry can be pulled from xlsx (modern) excel versions--comparing returned values to a locked spreadsheet"""
pt0x, pt0z, pt0y, pt1x, pt1z, pt1y, pt2x, pt2z, pt2y, pt3x, pt3z, pt3y, pt4x, pt4z, pt4y, pt5x, pt5z, pt5y, pt6x, pt6z, pt6y, pt... | 5,288,464 |
def vpncredential_create(request, **kwargs):
"""Create VPNCredential
:param request: request context
:param admin_state_up: admin state (default on)
:param name: name for VPN Credential
:param description: description for VPN Credential
"""
body = {'vpn_credential':
{'name':... | 5,288,465 |
def pkg_config_command(prefix, args):
""" Pkg config """
prefix.cmd.pkg_config(args) | 5,288,466 |
def find_similar():
"""
Finds relevant articles based on provided keywords and parameters
args:
List[String] keywords: list of keywords to search
Int recency: max age (in days) of returned articles, 0 for any time
List[String] blacklist: list of top level domains blocked by user
... | 5,288,467 |
def ensure_dir(directory):
"""Make sure the directory exists. If not, create it."""
if not os.path.exists(directory):
os.makedirs(directory)
return directory | 5,288,468 |
def classify(feature_matrix, theta, theta_0):
"""
A classification function that uses theta and theta_0 to classify a set of
data points.
Args:
feature_matrix - A numpy matrix describing the given data. Each row
represents a single data point.
theta - A numpy array d... | 5,288,469 |
def rebuild(request):
"""Rebuild ``XPI`` file. It can be provided as POST['location']
:returns: (JSON) contains one field - hashtag it is later used to download
the xpi using :meth:`xpi.views.check_download` and
:meth:`xpi.views.get_download`
"""
# log whole request without ... | 5,288,470 |
def write_xyz_file(mol, file_name, smiles):
"""
Embeds a mol object to get 3D coordinates which are written to an .xyz file
"""
n_atoms = mol.GetNumAtoms()
charge = Chem.GetFormalCharge(mol)
symbols = [a.GetSymbol() for a in mol.GetAtoms()]
Chem.SanitizeMol(mol)
rdmolops.AssignStereoc... | 5,288,471 |
def abspath(*args):
"""convert relative paths to absolute paths relative to PROJECT_ROOT"""
return os.path.join(PROJECT_ROOT, *args) | 5,288,472 |
def handle_unfollow(event):
# INSERT DATA TO DATABASE
""" config """
db = Database(Config)
""" query """
db.run_query(Delete.userleave(user_id), user_name, user_id)
""" log """
app.logger.info("Got Unfollow event:" + event.source.user_id) | 5,288,473 |
def create_sum_squares():
"""Returns a code dag for sum of squares."""
num_squares = Variable('N', var_type="int")
sum_var = Variable('sum_var', var_type="int")
sum_squares = FunctionNode('sum_squares', ret_type="int", inputs=[num_squares], output=sum_var)
sum_squares.add_object(sum_var)
sum_sq... | 5,288,474 |
def get_ps_url(ra, dec, size=240, output_size=None, filters="grizy", format="fits", color=False):
""" Get URL for images in the table
Parameters
----------
ra, dec: [floats]
position in degrees
size: [float]
image size in pixels (0.25 arcsec/pixel)
filters: [strings... | 5,288,475 |
def mcb(l, bit, mlb, tiebreaker = "1"):
"""
l = list of bits, e.g. ["00100", "11110", "10110"]
bit = index of the bit to consider, integer
mlb = most ("1") or least ("0") bit
tiebreaker = if there's an even split, default to this value.
returns the most common occurrencs, subjec... | 5,288,476 |
def weight_variable(stddev):
"""Weight variable."""
return TruncatedNormal(stddev) | 5,288,477 |
def convert_dict(txtfile):
""" convert this to dictonary, where key = CISC and val = ADIE"""
with open(txtfile) as f:
rename = {}
for line in f:
(key, val) = line.split()
# Remove any non-digit i.e. 'CISC'
rename[str(re.sub("[^0-9]", "", key))] = str(val)
... | 5,288,478 |
def get_query_for_oracle_load_full(table_name, columns, owner):
"""
JDBC query for full ingestion of one table
"""
logging.info(f"BUILDING FULL QUERY for {table_name}")
select_cols = ",".join(str(x) for x in columns)
return f"select {select_cols} from {owner}.{table_name}" | 5,288,479 |
def get_container_ipv_from_arguments(arguments):
"""
Determine the container IP version from the arguments.
:param arguments: Docopt processed arguments.
:return: The IP version. 4, 6 or None.
"""
version = None
if arguments.get("--ipv4"):
version = 4
elif arguments.get("--ipv6... | 5,288,480 |
def gradient_method(obj_function,
start_point,
init_step_size,
shrink_factor,
grad_function=approx_gradient,
step_function=descent_step,
max_iterations=float("inf"),
stop_norm=1e-8... | 5,288,481 |
def dump_candidates(cands, Y_prob, outfile):
"""Output the ce_v_max candidates and their probabilities for later analysis."""
dirname = os.path.dirname(__file__)
with open(os.path.join(dirname, outfile), "w") as csvfile:
writer = csv.writer(csvfile)
for i, c in enumerate(cands):
... | 5,288,482 |
def main():
"""Console script for pact_testgen."""
parser = argparse.ArgumentParser()
parser.add_argument("pact_file", help="Path to a Pact file.")
parser.add_argument(
"output_dir", help="Output for generated Python files.", type=directory
)
parser.add_argument(
"--base-class",
... | 5,288,483 |
def add_vacation_food_request(request, student):
"""
This function is to record vacation food requests
:param request:
start_date: Starting date of food request
end_date: Last date of food request
purpose: purpose for vacation food
:param student: Student ... | 5,288,484 |
def info() -> flask.Response:
"""API endpoint to retrive information about the current status.
Return a description of the current status, e.g in which state the crawler
is, which config is used, etc.
Returns:
flask.Response: REST response
"""
global TW_STATE
response = TW_STATE.i... | 5,288,485 |
def bandwidth_usage(context, instance_ref, audit_start,
ignore_missing_network_data=True):
"""Get bandwidth usage information for the instance for the
specified audit period.
"""
admin_context = context.elevated(read_deleted='yes')
def _get_nwinfo_old_skool():
"""Support for getting... | 5,288,486 |
def test_isclose() -> None:
"""Test :meth:`AssertionManager.isclose`."""
cls = type(assertion)
assertion.is_(cls.isclose, cls.allclose) | 5,288,487 |
def refine_result(authors_duplicates_dict, name_instance_dict, id_name_dict, name_statistics, similarity_dict, metapaths, remove_flag):
"""Filter out obvious conflict names."""
for author_id in authors_duplicates_dict.iterkeys():
if author_id in authors_duplicates_dict[author_id]:
authors_du... | 5,288,488 |
def updateEventRange(event_range_id, eventRangeList, jobId, pandaProxySecretKey, status='finished', os_bucket_id=-1, errorCode=None):
""" Update an list of event ranges on the Event Server """
# parameter eventRangeList is not used
try:
tolog("Updating an event range..")
if pandaProxySecre... | 5,288,489 |
def __voxel_normal_distribution(pointcloud, voxel_hashes, is_sorted: bool = False):
"""
Computes the normal distribution of points in each voxel
Args:
pointcloud (np.ndarray): The input pointcloud `(n, 3)` [np.float32]
voxel_hashes (np.ndarray): The voxel hashes `(n,)` [np.int64]
... | 5,288,490 |
def log_dict(writer, intro, data):
"""
Log structured data, e.g. JSON responses or a Python ``list``.
.. note::
For logging unstructured "blobs" of text, use :py:func:`gluetool.log.log_blob`. It does not
attempt to format the output, and wraps it by header and footer to mark its boundaries.
... | 5,288,491 |
def test_load_config_from_dotenv_non_empty_file_some_keys_accepted(tmp_path):
"""Load configuration from `.env`-file but accept some keys"""
env_file = tmp_path / ".env"
env_file.write_text('VALID = true\nNOT_ACCEPTED = true')
config = ConfigLoader.load_config_from_dotenv(str(env_file), accepted_keys=[... | 5,288,492 |
def plot_event_label(axis, starttime, endtime, **options):
"""
Plot event label on current axis.
Provide required ``eventtype`` field in the options to specify which event
to plot.
Plot style can be updated by providing keyword ``style`` in the extensions
plot entry.
Default style: ::
... | 5,288,493 |
def generate_submission_file(weight_path, model_name, target_size, test_path, use_folds):
"""
Generates rle encoded submission files of model - model_name
use_folds - if True - a weighted average prediction of folds is used from weight files in folder - 'weights/model_name'
- if False - a sing... | 5,288,494 |
def webhosting():
"""Manage and configure your WebHosting products.""" | 5,288,495 |
def balance(text, bal=0):
"""
Checks whether the parens in the text are balanced:
- zero: balanced
- negative: too many right parens
- positive: too many left parens
"""
if text == '':
return bal
elif text[0] == '(' and bal >= 0:
return balance(text[1:], bal +... | 5,288,496 |
def test_qrs_detection():
"""Main function - print quick test example
"""
try:
print("Example MIT-BIT Quick Test")
# Quick test
# load ECG data from ludb database into pandas dataframes
ecg, rpeaks = read_mit_bit_files()
print(ecg)
# load raw ECG sign... | 5,288,497 |
def test_multiple_hex_multiple_subvoxel_uniform():
"""This test tests that particle are sampled uniformly from a uniform source
defined on eight mesh volume elements in two energy groups.
"""
seed(1953)
m = Mesh(
structured=True,
structured_coords=[[0, 0.5, 1], [0, 0.5, 1], [0, 0.5, ... | 5,288,498 |
def _inches_to_meters(length):
"""Convert length from inches to meters"""
return length * 2.54 / 100.0 | 5,288,499 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.