content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def test_load(cursor, run):
"""verify simple load by key"""
_ = run(MyTable.load, cursor, 123)
assert cursor.query_after == (
"SELECT 'my_table'.'id' AS 0_id, 'my_table'.'name' AS 0_name,"
" 'my_table'.'email' AS 0_email FROM 'my_table' AS 'my_table'"
" WHERE 'id'=123 LIMIT 1"
) | 30,400 |
def my_join(x):
"""
:param x: -> the list desired to join
:return:
"""
return ''.join(x) | 30,401 |
def config_parse_args(configfile=None):
""" Command line arguments and configuration file setting """
parser = argparse.ArgumentParser(
description='nanoping log importer to InfluxDB')
parser.add_argument('--config', type=str, required=True,
help='configuration file')
par... | 30,402 |
def run_example(FLAGS):
"""
Run parallel Sherpa optimization over a set of discrete hp combinations.
"""
# Iterate algorithm accepts dictionary containing lists of possible values.
hp_space = {'act': ['tanh', 'relu'],
'lrinit': [0.1, 0.01],
'momentum': [0.0],
... | 30,403 |
def visualize_code_vectors(code_vectors, cmap='Paired', inter='none',
origin='upper', fontsize=16, aspect='auto',
colorbar=True):
"""
Document
"""
to_plot = np.array(code_vectors)
# First the parameters
to_plot_title = 'Code Vectors in Time... | 30,404 |
def get_displacements_and_forces(disp_dataset):
"""Return displacements and forces of all atoms from displacement dataset.
This is used to extract displacements and forces from displacement dataset.
This method is considered more-or-less as a converter when the input is in
type-1.
Parameters
-... | 30,405 |
def GetUserAllBasicData(user_url: str) -> Dict:
"""获取用户的所有基础信息
Args:
user_url (str): 用户个人主页 Url
Returns:
Dict: 用户基础信息
"""
result = {}
json_obj = GetUserJsonDataApi(user_url)
html_obj = GetUserPCHtmlDataApi(user_url)
anniversary_day_html_obj = GetUserNextAnniversaryDayH... | 30,406 |
def get_trace(session, trace_uuid):
"""Retrieves traces given a uuid.
Args:
sesssion: db session
trace_uuid: uuid of trace in question
Returns 2-tuple of plop, flamegraph input or None if trace doesn't exist
(or was garbage collected.
"""
trace = session.query(PerfProfile).filt... | 30,407 |
def iter_package_families(paths=None):
"""Iterate over package families, in no particular order.
Note that multiple package families with the same name can be returned.
Unlike packages, families later in the searchpath are not hidden by earlier
families.
Args:
paths (list of str, optional)... | 30,408 |
def first_kind_discrete(orientations, order=4):
"""
Calc orientation tensors of first kind for given discrete vectors
"""
# Normalize orientations
orientations = [np.array(v) / np.linalg.norm(v) for v in orientations]
# Symmetrize orientations
# orientations_reversed = [-v for v in orien... | 30,409 |
def _reorganize_beam_groups(ed_obj):
"""
Maps Beam --> Sonar/Beam_group1 and Beam_power --> Sonar/Beam_group2.
Parameters
----------
ed_obj : EchoData
EchoData object that was created using echopype version 0.5.x
Notes
-----
The function directly modifies the input EchoData obj... | 30,410 |
def write_tsv(headerfields, features, outfn):
"""Writes header and generator of lines to tab separated file.
headerfields - list of field names in header in correct order
features - generates 1 list per line that belong to header
outfn - filename to output to. Overwritten if exists
"""
with ope... | 30,411 |
def create_tables():
""" Create all tables for the db
:returns: Nothing. Message is printed if connection error
"""
sql_create_web_addon_table = """ CREATE TABLE IF NOT EXISTS web_addon (
ID INTEGER PRIMARY KEY AUTOINCREMENT,
... | 30,412 |
def prep_pointcloud(input_dict,
root_path,
voxel_generator,
target_assigner,
db_sampler=None,
max_voxels=20000,
class_names=['Car'],
remove_outside_points=False,
... | 30,413 |
def fix_repo_url(repo_url, in_type='https', out_type='ssh', format_dict=format_dict):
""" Changes the repo_url format """
for old, new in izip(format_dict[in_type], format_dict[out_type]):
repo_url = repo_url.replace(old, new)
return repo_url | 30,414 |
def add_nodes_to_graph(
G: nx.Graph,
protein_df: Optional[pd.DataFrame] = None,
verbose: bool = False,
) -> nx.Graph:
"""Add nodes into protein graph.
:param G: ``nx.Graph`` with metadata to populate with nodes.
:type G: nx.Graph
:protein_df: DataFrame of protein structure containing nodes ... | 30,415 |
def mc(dataset):
"""
Modulus calculation.
Calculates sqrt(real^2 + imag^2)
"""
return np.sqrt(dataset.real ** 2 + dataset.imag ** 2) | 30,416 |
def _get_fields_list(data: Data) -> List[Field]:
"""Extracts all nested fields from the data as a flat list."""
result = []
def map_fn(value):
if isinstance(value, GraphPieceBase):
# pylint: disable=protected-access
tf.nest.map_structure(map_fn, value._data)
else:
result.append(value)
... | 30,417 |
def constructAdvancedQuery(qryRoot):
"""
Turns a qry object into a complex Q object by calling its helper and supplying the selected format's tree.
"""
return constructAdvancedQueryHelper(
qryRoot["searches"][qryRoot["selectedtemplate"]]["tree"]
) | 30,418 |
def slice_and_dice(text=text):
"""Strip the whitespace (newlines) off text at both ends,
split the text string on newline (\n).
Next check if the first char of each (stripped) line is lowercase,
if so split the line into words and append the last word to
the results list. Make sure ... | 30,419 |
def solution(data):
""" Solution to the problem """
seats, first_visible_seats, dim_y, dim_x = preprocess(data)
solver = Simulation(seats, first_visible_seats, dim_y, dim_x)
return solver.solve() | 30,420 |
def dump_line_delimited_json(data, filename):
"""Dump a list of objects to the file as line-delimited JSON.
Parameters
----------
data : list
filename : str
"""
with open(filename, "w") as f_out:
for obj in data:
f_out.write(json.dumps(obj))
f_out.write("\n"... | 30,421 |
def downloadNameActives():
""" """
nameActivesURL = exp_config.name_actives_url
nameActivesRemote = exp_config.name_actives_remote
nameActivesFile = nameActivesURL.split('/')[-1]
output_folder = os.path.split(nameActivesRemote)[0]
#nameActivesRemote = os.path.join(output_folder, nameActives... | 30,422 |
def test_next(circ_number, total):
"""Test total_matching_neighbours against known input and output"""
assert total_matching_neighbours(circ_number) == total | 30,423 |
def add_received_ip_tags(
rows: beam.pvalue.PCollection[Row],
ips_with_metadata: beam.pvalue.PCollection[Tuple[DateIpKey, Row]]
) -> beam.pvalue.PCollection[Row]:
"""Add tags for answer ips (field received.ip) - asnum, asname, http, cert
Args:
rows: PCollection of measurement rows
ips_with_meta... | 30,424 |
def set_selector(*args):
"""set_selector(sel_t selector, ea_t paragraph) -> int"""
return _idaapi.set_selector(*args) | 30,425 |
def other_features(tweet):
"""This function takes a string and returns a list of features.
These include Sentiment scores, Text and Readability scores,
as well as Twitter specific features"""
tweet_text = tweet["text"]
##SENTIMENT
sentiment = sentiment_analyzer.polarity_scores(tweet_text)
... | 30,426 |
def template(spec_fn):
"""
>>> from Redy.Magic.Classic import template
>>> import operator
>>> class Point:
>>> def __init__(self, p):
>>> assert isinstance(p, tuple) and len(p) is 2
>>> self.x, self.y = p
>>> def some_metrics(p: Point):
>>> return p.x + 2 * p... | 30,427 |
def remove_build_storage_paths(paths):
"""
Remove artifacts from build media storage (cloud or local storage).
:param paths: list of paths in build media storage to delete
"""
storage = get_storage_class(settings.RTD_BUILD_MEDIA_STORAGE)()
for storage_path in paths:
log.info('Removing %... | 30,428 |
def list_sum(*argv, **kwargs):
"""
Summarise items in provided list
Arguments:
- argv: list of item for summarise
Options:
- type: list item type (int if omitted)
Note: All types provided by this lib supported
Returns sum number in 'type' format
"""
_type_name = kwar... | 30,429 |
def _on_connect(dbapi_connection, **_):
"""Set MySQL mode to TRADITIONAL on databases that don't set this automatically.
Without this, MySQL will silently insert invalid values in the database, causing very long debugging sessions in the
long run.
http://www.enricozini.org/2012/tips/sa-sqlmode-tra... | 30,430 |
def locate_file(start_path, file_name):
""" locate filename and return file path.
searching will be recursive upward until current working directory.
Args:
start_path (str): start locating path, maybe file path or directory path
Returns:
str: located file path. None if file not fou... | 30,431 |
def image_upload(request):
"""
If it's a post, then upload the image or store it locally based on config. Otherwise, return
the html of the upload.html template.
"""
if request.method == 'POST':
image_file = request.FILES['image_file']
image_type = request.POST['image_type']
... | 30,432 |
def test_expected(mapper):
""" Test the expected method. """
# set addresses with hostname inside (IP addresses are not valid on purpose)
hostname = socket.gethostname()
node_lst = ['292.168.0.1', '292.168.0.2', hostname]
mapper.node_names = node_lst
# find expected address from list of aliases ... | 30,433 |
def werbo_c(topics, word_embedding_model, weight=0.9, topk=10):
"""
computes Word embedding based RBO - centroid
Parameters
----------
topics: a list of lists of words
word_embedding_model: word embedding space in gensim word2vec format
weight: p (float), default 1.0: Weight of each agreeme... | 30,434 |
def G_t(t, G, tau, Ge = 0.0):
"""this function returns the relaxation modulus in time"""
G_rel = np.zeros(np.size(t))
if np.size(G) == 1: #the model is the SLS
for i in range(np.size(t)):
G_rel[i] = Ge + G*np.exp(-t[i]/tau)
else: #the model has more than one arm
for i in ran... | 30,435 |
def iou_set(set1, set2):
"""Calculate iou_set """
union = set1.union(set2)
return len(set1.intersection(set2)) / len(union) if union else 0 | 30,436 |
def time_measured(fkt):
"""
Decorator to measure execution time of a function
It prints out the measured time
Parameters
----------
fkt : function
function that shall be measured
Returns
-------
None
"""
def fkt_wrapper(*args, **kwargs):
t1 = time.time()
... | 30,437 |
def test_dict():
"""Test dict accessor works."""
js = pw.line(range(3)).dict
expected = {
'layout': {},
'data': [
{
'mode': 'lines+markers',
'marker': dict(size=6),
'text': "",
'y': [0, 1, 2],
'x': [0... | 30,438 |
def test_find_codon(find_codon):
"""
A function to test another function that looks for a codon within
a coding sequence.
"""
synapto_nuc = ("ATGGAGAACAACGAAGCCCCCTCCCCCTCGGGATCCAACAACAACGAGAACAACAATGCAGCCCAGAAGA"
"AGCTGCAGCAGACCCAAGCCAAGGTGGACGAGGTGGTCGGGATTATGCGTGTGAACGTGGAGAAGGTCCT"
"GGAG... | 30,439 |
def test_command_line_interface():
"""Test the CLI."""
runner = CliRunner()
result = runner.invoke(main, ["show-servers"])
assert result.exit_code == 0
help_result = runner.invoke(main, ["--help"])
assert help_result.exit_code == 0
assert "--help Show this message and exit." in help_resul... | 30,440 |
def add_keys3(a, A, b, B):
"""
aA + bB
:param a:
:param A:
:param b:
:param B:
:return:
"""
return tcry.xmr_add_keys3_vartime_r(a, A, b, B) | 30,441 |
def complement(csv_files, output_prefix, delimiter=',', include_cols=None,
target=None):
"""Remove all shared rows from a list of csv/tsv files."""
dfs, headers = read_tables(csv_files, delimiter)
dfs = remove_shared_rows(dfs, include_cols)
output_filenames = [local.path(output_prefix + f... | 30,442 |
def cause_state(value):
"""
Usage::
{{ value|cause_state}}
"""
try:
if isinstance(value, (str, unicode)):
value = eval(value)
if Bushfire.CAUSE_STATE_POSSIBLE==value:
return Bushfire.CAUSE_STATE_CHOICES[Bushfire.CAUSE_STATE_POSSIBLE-1][1]
... | 30,443 |
def ReadRawSAData(DataDirectory, fname_prefix):
"""
This function reads in the raw SA data to a pandas dataframe
Args:
DataDirectory: the data directory
fname_prefix: the file name prefix
Returns:
pandas dataframe with the raw SA data
Author: FJC
"""
# get the... | 30,444 |
def not_valid_score(scores: List[int]):
"""Checks if the set of estimations is ambiguous (all scores are different)."""
return True if len(np.unique(scores)) == len(scores) else False | 30,445 |
def sendEmail(sendTo,textfile,logfile,img):
"""Retrieves the error.txt and an the taken image and sends an email
with those attached"""
# Open a plain text file for reading
msg = MIMEMultipart()
# Read the text file <-- Error msg from OCR module
if(textfile!=""):
fp = open(textf... | 30,446 |
def readd(
archive: str,
# uid: str = '{blake2b}', # option disabled for now
config: str = '',
hashes='blake2b',
v_hashes='dhash',
metadata='',
exts: str = '',
limit: int = 0,
thumb_sz: int = 64,
thumb_qual: int = 70,
thumb_type: str = 'webp',
dbname: str = 'imgdb.htm',
... | 30,447 |
def train(
train_op,
logdir,
log_every_n_steps=1,
graph=None,
master='',
is_chief=True,
global_step=None,
number_of_steps=None,
init_op=_USE_DEFAULT,
init_feed_dict=None,
init_fn=None,
summary_op=_USE_DEFAULT,
save_summaries_secs=600,
startup_delay_steps=0,
sa... | 30,448 |
def dlopen_enclave_test(
name,
**kwargs):
"""Thin wrapper around enclave test, adds 'asylo-dlopen' tag and necessary linkopts
Args:
name: enclave_test name
**kwargs: same as enclave_test kwargs
"""
asylo = internal.package()
enclave_test(
name,
backends ... | 30,449 |
def biom_to_pandas(biom_otu):
"""
Convert data from biom to SparseDataFrame (pandas) for easy access
:param biom_otu: Table
:rtype: DataFrame
"""
tmp_m = biom_otu.matrix_data
df = [SparseSeries(tmp_m[i].toarray().ravel()) for i in numpy.arange(tmp_m.shape[0])]
return (SparseDataFrame(df,... | 30,450 |
def __request(logger, cache, method, url, headers, body, keep_alive):
"""Returns file content for client request"""
if method == "HEAD" or method == "GET":
if url.startswith("/private/"):
base64_auth = base64.b64encode(
(settings.PRIVATE_USERNAME + ":" + settings.PRIVATE_PAS... | 30,451 |
def is_classmethod(method: t.Callable):
"""
A python method is a wrapper around a function that also
holds a reference to the class it is a method of.
When bound, it also holds a reference to the instance.
@see https://stackoverflow.com/questions/12935241/python-call-instance-method-using-func
... | 30,452 |
def masked_accuracy(y_true, y_pred):
"""An accuracy function that masks based on targets (value: 0.5)
Args:
y_true: The true training labels
y_pred: The predicted labels
Returns:
float: the masked accuracy
"""
a = kb.sum(kb.cast(kb.equal(y_true, kb.r... | 30,453 |
def get_shap_interaction_values(x_df, explainer):
"""
Compute the shap interaction values for a given dataframe.
Also checks if the explainer is a TreeExplainer.
Parameters
----------
x_df : pd.DataFrame
DataFrame for which will be computed the interaction values using the explainer.
... | 30,454 |
def plot_roc(
y_true: np.ndarray,
y_probas: np.ndarray,
labels: Optional[dict] = None,
classes_to_plot: Optional[list] = None,
plot_micro: Optional[bool] = False,
plot_macro: Optional[bool] = False,
title: str = "ROC Curve",
ax: Optional[matplotlib.axes.Axes] = None,
figsize: Optiona... | 30,455 |
def get_cpu_info(host_info={}):
"""populate host_info with cpu information"""
if sys.platform == 'darwin':
host_info["host_cpu_model"] = \
popen(["sysctl", "-n", "machdep.cpu.brand_string"])
host_info["host_cpu_cores"] = \
popen(["sysctl", "-n", "machdep.cpu.core_count"]... | 30,456 |
def _harmonize_input(data):
"""Harmonize different types of inputs by turning all inputs into dicts."""
if isinstance(data, (pd.DataFrame, pd.Series)) or callable(data):
data = {0: data}
elif isinstance(data, dict):
pass
else:
raise ValueError(
"Moments must be pand... | 30,457 |
def setup_testCase(self: unittest.TestCase, stop_when_sick: bool, login_success: bool, is_sick: bool) -> None:
"""
多个 TestCase 的 setUp 函数有公共代码,因此抽取出来。
:param self: 测试类实例
:param stop_when_sick: 是否开启 stop_when_sick 功能
:param login_success: (模拟的)登录是否成功
:param is_sick: 是否模拟用户数据带病的场景
:return: Non... | 30,458 |
def herd_closest_to_cluster(
x: np.ndarray,
y: np.ndarray,
t: np.ndarray,
features: np.ndarray,
nb_per_class: np.ndarray
) -> np.ndarray:
"""Herd the samples whose features is the closest to their class mean.
:param x: Input data (images, paths, etc.)
:param y: Labels of the data.
:... | 30,459 |
def main():
"""
This code, which must run on the EV3 ROBOT:
1. Makes the EV3 robot to various things.
2. Communicates via MQTT with the GUI code that runs on the LAPTOP.
"""
real_thing()
# run_test_ir(0)
# run_test_arm()
# run_test_camera() | 30,460 |
def generate_reference_config(config_entries: List[ConfigEntry]) -> {}:
"""
Generates a dictionary containing the expected config tree filled with default and example values
:return: a dictionary containing the expected config tree
"""
return config_entries_to_dict(config_entries, use_examples=True) | 30,461 |
def ShowStateTransition(dot_file, event_log_file, state_log_file, node_map_file):
"""
Take a dot file and log file and animate the state transition
"""
from matplotlib.pyplot import gca, figure
from numpy import genfromtxt
time_mult = __disp_defs__.TIME_MULTIPLIER
figure(figsize=__disp_defs... | 30,462 |
def reshape_tensor2list(tensor, n_steps, n_input):
"""Reshape tensor [?, n_steps, n_input] to lists of n_steps items with [?, n_input]
"""
# Prepare data shape to match `rnn` function requirements
# Current data input shape (batch_size, n_steps, n_input)
# Required shape: 'n_steps' tensors list of shape (batc... | 30,463 |
def test_flow_1():
"""
This MUST NOT fail
We simply add two blocks, each one with only the coinbase transaction
"""
coinbase_0 = Tx(
[TxIn(OutPoint("00" * 32, 0), Script.from_hex("00030000aa"))],
[TxOut(10 ** 10, Script())],
)
origin_transactions = [coinbase_0]
origin_h... | 30,464 |
def parse_arguments() -> dict:
"""Parse sys.argv arguments.
Args:
None
Returns:
A dictionary of arguments.
"""
parser = argparse.ArgumentParser(
formatter_class=argparse.RawDescriptionHelpFormatter,
epilog=textwrap.dedent("""
additional information:
... | 30,465 |
def squeeze(xray_obj, dimensions, dimension=None):
"""Squeeze the dimensions of an xray object."""
if dimension is None:
dimension = [d for d, s in dimensions.iteritems() if s == 1]
else:
if isinstance(dimension, basestring):
dimension = [dimension]
if any(dimensions[k] >... | 30,466 |
def write(settings_path, settings_data, merge=True):
"""Write data to a settings file.
:param settings_path: the filepath
:param settings_data: a dictionary with data
:param merge: boolean if existing file should be merged with new data
"""
settings_path = Path(settings_path)
if settings_pa... | 30,467 |
def server_db(request, cp_server, api_server):
"""Enable database access for unit test vectors."""
db = database.get_connection(read_only=False, integrity_check=False)
api_server.db = db # inject into api_server
cursor = db.cursor()
cursor.execute('''BEGIN''')
util_test.reset_current_block_inde... | 30,468 |
def click_exception(exc, error_format):
"""
Return a ClickException object with the message from an input exception
in a desired error message format.
Parameters:
exc (exception or string):
The exception or the message.
error_format (string):
The error format (see ``--erro... | 30,469 |
def build(program_code: str, data: Data = frozendict(), random_seed: Optional[int] = None) -> Model:
"""Build (compile) a Stan program.
Arguments:
program_code: Stan program code describing a Stan model.
data: A Python dictionary or mapping providing the data for the
model. Variable... | 30,470 |
def _exec_with_broadcasting(func, *args, **keywords):
"""Main function to broadcast together the shapes of the input arguments
and return results with the broadcasted shape."""
# Identify arguments needing broadcasting
arg_ranks = []
arg_indices = []
for k in range(len(args)) + keywords.keys()... | 30,471 |
def info_fba_optimization(input_file, model, target, sol):
"""
Print fluxes through relevan reactions if the target can be produced
If FBA with the exchange reaction of the target as objective
is feasible, this function prints the reaction rates of
relevant reactions
-------------------------... | 30,472 |
def compose_paths(path_0, path_1):
"""
The binary representation of a path is a 1 (which means "stop"), followed by the
path as binary digits, where 0 is "left" and 1 is "right".
Look at the diagram at the top for these examples.
Example: 9 = 0b1001, so right, left, left
Example: 10 = 0b1010, ... | 30,473 |
def combine(img1, img2, out_path, write=True):
"""combine(img1, img2, out_path, write=True)
Combines the data of two PyifxImages, ImageVolumes, or ImageLists to form new PyifxImages.
:type img1: pyifx.misc.PyifxImage, pyifx.misc.ImageVolume, list
:param img1: The first image to be added to the combination.
... | 30,474 |
def invert_index(i, window, step):
"""Convert truncated squareform index back into row, col, and slice index
Task indexing for LD pruning is based on several optimizations that utilize a
cyclic, truncated squareform pattern for pairwise comparisons (between rows). This pattern
is primarily controlle... | 30,475 |
def group_masses(ip, dm: float = 0.25):
"""
Groups masses in an isotope pattern looking for differences in m/z greater than the specified delta.
expects
:param ip: a paired list of [[mz values],[intensity values]]
:param dm: Delta for looking +/- within
:return: blocks grouped by central mass
... | 30,476 |
def normalize_ballots(ballots_resource):
"""Normalize the given ballots in place.
Arguments:
ballots_resource: a ballots resource.
"""
with ballots_resource.replacement() as temp_resource:
normalize_ballots_to(ballots_resource, temp_resource) | 30,477 |
def save_user_labels(*args):
"""
save_user_labels(func_ea, user_labels)
Save user defined labels into the database.
@param func_ea: the entry address of the function (C++: ea_t)
@param user_labels: collection of user defined labels (C++: const
user_labels_t *)
"""
return _ida_he... | 30,478 |
def add_play():
"""Adds a new play"""
if 'Logged in as: ' + flask_login.current_user.get_id():
play_json = request.json
if request.json is None and request.data:
play_json = request.data
if play_json:
try:
# insert the created by information in pla... | 30,479 |
def get_compliment(file_list, file):
"""Returns a file path from the provided list that has the same name as the
file passed as the second arugment.
:param file_list: A list of paths with the same filetype.
:type file_list: list
:param file: A single path with an opposite filetype.
:type file: ... | 30,480 |
def electron_cyclotron_emission_hardware(ods, pulse, fast_ece=False):
"""
Gathers DIII-D Electron cyclotron emission locations
:param pulse: int
:param fast_ece: bool
Use data sampled at high frequency
"""
unwrap(electron_cyclotron_emission_data)(ods, pulse, fast_ece=fast_ece, _measure... | 30,481 |
def load_string_list(file_path, is_utf8=False):
"""
Load string list from mitok file
"""
try:
with open(file_path, encoding='latin-1') as f:
if f is None:
return None
l = []
for item in f:
item = item.strip()
if ... | 30,482 |
def flash_dev(
disk=None, image_path=None, copy_method="default", port=None, program_cycle_s=4
):
"""Flash a firmware image to a device.
Args:
disk: Switch -d <disk>.
image_path: Switch -f <image_path>.
copy_method: Switch -c <copy_method> (default: shell).
port: Switch -p <... | 30,483 |
def _get_bucket_and_object(gcs_blob_path):
"""Extract bucket and object name from a GCS blob path.
Args:
gcs_blob_path: path to a GCS blob
Returns:
The bucket and object name of the GCS blob
Raises:
ValueError: If gcs_blob_path parsing fails.
"""
if not gcs_blob_path.startswith(_GCS_PATH_PREF... | 30,484 |
def dq_data(request):
"""Main home method and view."""
try:
cases = []
sdate, edate = None, None
sts = {0: 'Pending', 1: 'Open', 2: 'Closed'}
# Conditions
qa = request.GET.get('q_aspect')
va = request.GET.get('variance')
age = request.GET.get('age')
... | 30,485 |
def convert_to_differential(file_in, file_out):
"""
This function reformats the txt deAPA output file to file for
differential challenges
:param file_in: txt file to be reformatted
:param file_out: differential challenge output file
:return: N/A
"""
differential_out = open(file_out, "wt"... | 30,486 |
def create_round_model(
protocol: Protocol,
ber: float,
n_tags: int) -> 'RoundModel':
"""
Factory function for creating round model.
This routine is cached, so calling it multiple time won't add much
overhead.
Parameters
----------
protocol : Protocol
ber : floa... | 30,487 |
def AddPrivateIpv6GoogleAccessTypeFlag(api_version, parser, hidden=False):
"""Adds --private-ipv6-google-access-type={disabled|outbound-only|bidirectional} flag."""
messages = apis.GetMessagesModule('container', api_version)
util.GetPrivateIpv6GoogleAccessTypeMapper(
messages, hidden).choice_arg.AddToParser... | 30,488 |
def local_maxima(a_list):
"""
Takes a NoteList object.
Returns a list of tuples of the form returned by note_onsets().
Each of these (int: bar #, float: beat #) tuples will represent the onset
of a note that is a local maximum in the melody in a_list.
"""
return local_extremities(a_list, ma... | 30,489 |
def get_fitted_model(data: pd.DataFrame, dataframe: pd.DataFrame) -> CTGAN:
""" The function get_fitted_model uses a CTGAN Checkpoint (see chapter about checkpoints),
to load a trained CTGAN model if one is available with the desired hyperparameters, or
train a new one if none is available. The function the... | 30,490 |
def test_relu():
"""Tests relu"""
pf.set_backend("pytorch")
_test_elementwise(
ops.relu, [-1.0, -0.1, 0.0, 0.1, 1.0], [0.0, 0.0, 0.0, 0.1, 1.0]
) | 30,491 |
def point_based_matching(point_pairs):
"""
This function is based on the paper "Robot Pose Estimation in Unknown Environments by Matching 2D Range Scans"
by F. Lu and E. Milios.
:param point_pairs: the matched point pairs [((x1, y1), (x1', y1')), ..., ((xi, yi), (xi', yi')), ...]
:return: the rotat... | 30,492 |
async def async_setup_platform(hass, config, async_add_devices,
discovery_info=None):
"""Setup the sensor platform."""
if discovery_info is None:
return
data = hass.data[DOMAIN].data
if not data.cars:
_LOGGER.info("No Cars found.")
return
dev... | 30,493 |
def kb_ids2known_facts(kb_ids):
"""Creates list of all known facts from kb dict"""
facts = set()
for struct in kb_ids:
arrays = kb_ids[struct][0]
num_facts = len(arrays[0])
for i in range(num_facts):
fact = [x[i] for x in arrays]
facts.add(tuple(fact))
re... | 30,494 |
def vm_name_check(vm_names, item):
"""
Check vm name
:param vm_names: dictionary of vm name
:param item: vm name item in xml
:return: None
"""
for name_i, name_str in vm_names.items():
name_len = len(name_str)
if name_len > 32 or name_len == 0:
key = "vm:id={},{}"... | 30,495 |
def get_filepath(url, illustration, save_path='.', add_user_folder=False, add_rank=False):
"""return (filename,filepath)"""
if add_user_folder:
user_id = illustration.user_id
user_name = illustration.user_name
current_path = get_default_save_path()
cur_dirs = list(filter(os.path... | 30,496 |
def PUtilAvgT (inUV, outUV, err, scratch=False, timeAvg=1.0):
""" Average A UV data set in Time
returns Averaged UV data object
inUV = Python UV object to copy
Any selection editing and calibration applied before average.
outUV = Predefined UV data if scratch is False, ignored if
... | 30,497 |
def check_view_restrictions(request, page):
"""
Mimic default Wagtail core behaviour but throw a 403 exception instead of
a redirect.
See wagtail.wagtailcore.wagtail_hooks.check_view_restrictions
"""
restrictions = page.get_view_restrictions()
if restrictions:
passed_restrictions = ... | 30,498 |
def save_hist_batch(hist, idx_batch, idx_epoch, g_loss, d_loss, e_loss, d_x, d_g_z): #, d_fake
"""
Sauvegarde les données du batch dans l'historique après traitement
"""
d_x = d_x.detach().cpu().numpy()
# d_fake = d_fake.detach().cpu().numpy()
d_g_z = d_g_z.detach().cpu().numpy()
g_loss = g... | 30,499 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.