content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def experiment_queue(experiment_paths, dataset_paths, model_save_paths,
tensorboard_output_dirs, finished_experiments_dir_path,
class_weights_train=None):
"""
Starts list of experiments (models) for training models.
All models are trained one after another on same ... | 5,306,400 |
def relative_position_embedding(seq_length, out_dim, repeat_pos_encoding=1):
"""Creates a [seq_length x out_dim] matrix for rel. pos encoding.
Denoted as Phi in [2] and [3]. Phi is the standard sinusoid encoding
matrix.
Args:
seq_length (int): The max. sequence length (time axis).
out_di... | 5,306,401 |
def previous_line(view, sr):
"""sr should be a Region covering the entire hard line"""
if sr.begin() == 0:
return None
else:
return view.full_line(sr.begin() - 1) | 5,306,402 |
def __init__(self,account,username,password):
"""
__init__ method helps us define properties for our object
""" | 5,306,403 |
def Compress():
"""Compresses the go tool into tar.gz and generates sha1 code, renames the
archive to sha1.tar.gz and returns the sha1 code."""
print "Compressing go tool, this may take several minutes."
os.chdir(INSTALL_DIR)
with tarfile.open(os.path.join('a.tar.gz'), 'w|gz') as arch:
arch.add('andro... | 5,306,404 |
async def async_citybikes_request(hass, uri, schema):
"""Perform a request to CityBikes API endpoint, and parse the response."""
try:
session = async_get_clientsession(hass)
with async_timeout.timeout(REQUEST_TIMEOUT):
req = await session.get(DEFAULT_ENDPOINT.format(uri=uri))
... | 5,306,405 |
def times(allow_naive=None, timezones=None):
"""Return a strategy for generating times.
.. deprecated:: 3.9.0
use :py:func:`hypothesis.strategies.times` instead.
The allow_naive and timezones arguments act the same as the datetimes
strategy above.
"""
note_deprecation('Use hypothesis.s... | 5,306,406 |
def test_run_python_script_in_terminal(scriptpath, qtbot):
"""
Test running a Python script in an external terminal when specifying
explicitly the working directory.
"""
# Run the script
outfilepath = osp.join(scriptpath.dirname, 'out.txt')
run_python_script_in_terminal(
scriptpath.s... | 5,306,407 |
def split_by_returning(df_train, df_test):
"""
Split out clients by total number of sessions (single or >=2)
:param df_train:
:param df_test:
:return:
"""
df = pd.concat([df_train, df_test], axis=0, sort=True)
df_grp = df.groupby('fullVisitorId').agg({'sessionId': 'count'}).reset_index()... | 5,306,408 |
def test_nviolations_parking(parking):
"""Ensure we can select groups with exactly n=2 violations"""
groups = key_violations(df=parking, columns='Plate ID', n=2)
assert len(groups) == 3
groups = key_violations(df=parking, columns=['Plate ID', 'Meter Number'], n=2)
assert len(groups) == 2 | 5,306,409 |
def senel_noise(SPLt_dBA_max):
"""This method calculates the effective perceived noise level (EPNL) based on a time history
Perceived Noise Level with Tone Correction (PNLT).
Assumptions:
None
Source:
None
Inputs:
PNLT - Perceived Noise Level wit... | 5,306,410 |
def test_camo(scene = '../data/charlottesville-3', method = 'random'):
""" Camouflage a box in a given scene using the specified method. Generates a webpage showing the result """
scan = dset.Scan(scene)
mesh = box.load_from_mat(os.path.join(scene, 'cube.mat'))
texel_colors = camo(scan, mesh, method)[0]
box.... | 5,306,411 |
def test_list_non_negative_integer_enumeration_nistxml_sv_iv_list_non_negative_integer_enumeration_1_1(mode, save_output, output_format):
"""
Type list/nonNegativeInteger is restricted by facet enumeration.
"""
assert_bindings(
schema="nistData/list/nonNegativeInteger/Schema+Instance/NISTSchema-... | 5,306,412 |
def test_node_repair(mock_verify):
"""Test that repair() method calls verify(True)."""
node = Node()
node.repair()
mock_verify.assert_called_once_with(True) | 5,306,413 |
def convertToVerifaiType(value, strict=True):
"""Attempt to convert a Scenic value to a type known to VerifAI"""
ty = underlyingType(value)
if ty is float or ty is int:
return float(value)
elif ty is list or ty is tuple:
return tuple(convertToVerifaiType(e, strict=strict) for e in value)... | 5,306,414 |
def predecessor_to_forwarding(predecessor, source):
"""
Compute a forwarding table from a predecessor list.
"""
# Create variable to return (forwarding-table dictionary)
FT = {}
# Loop over all nodes that AREN'T the source
for (key, value) in predecessor.items():
if (key ... | 5,306,415 |
def index():
"""Handle index requests."""
return version.version_string(), 200 | 5,306,416 |
def init_atlas_grid(im_size, nb_patterns, rand_seed=None):
""" initialise atlas with a grid schema
:param tuple(int,int) im_size: size of image
:param int nb_patterns: number of pattern in the atlas to be set
:param rand_seed: random initialisation
:return ndarray: np.array<height, width>
>>> ... | 5,306,417 |
def block_diag(values, like=None):
"""Combine a sequence of 2D tensors to form a block diagonal tensor.
Args:
values (Sequence[tensor_like]): Sequence of 2D arrays/tensors to form
the block diagonal tensor.
Returns:
tensor_like: the block diagonal tensor
**Exampl... | 5,306,418 |
def tkinstall():
"""Replace tkinter's `Tk` class with a thread-enabled version"""
import platform
runtime = platform.python_implementation()
if 'cpython' not in runtime.lower():
raise RuntimeError('Requires CPython, not %s' % runtime)
tk.__dict__.setdefault('_Tk_original_', tk.Tk) # save t... | 5,306,419 |
def parse_menu_command(cmd_addr, sctp_client, keys):
"""Parse specified command from sc-memory and
return hierarchy map (with childs), that represent it
@param cmd_addr: sc-addr of command to parse
@param sctp_client: sctp client object to work with sc-memory
@param keys: keynodes ob... | 5,306,420 |
def main_crimmins_func(port_list: list = None) -> bool:
"""
The Crimmins complementary culling algorithm is used to remove speckle noise and smooth the edges.
It also reduces the intensity of salt and pepper noise. The algorithm compares the intensity of a pixel
in a image with the intensities of its 8 ... | 5,306,421 |
def find_builtin_server_type(type_name: str) -> Type[Any]:
"""Find first installed server implementation"""
supported_packages = ["sanic", "flask", "tornado"]
installed_builtins: List[str] = []
for name in supported_packages:
try:
import_module(name)
except ImportError: # p... | 5,306,422 |
def uriel_distance_vec(languages):
"""
Adapted from langrank [https://github.com/neulab/langrank/blob/master/langrank.py]
"""
geographic = l2v.geographic_distance(languages)
genetic = l2v.genetic_distance(languages)
inventory = l2v.inventory_distance(languages)
syntactic = l2v.syntactic_dist... | 5,306,423 |
def print_version(ctx, param, value):
"""Find version from file VERSION and print"""
# param is passed by click but not needed here
# pylint: disable=unused-argument
if not value or ctx.resilient_parsing:
return
click.echo('Version {}'.format(VERSION))
ctx.exit() | 5,306,424 |
def create_platform_product_gui(platforms: List[str],
products: List[str],
datacube: datacube.Datacube,
default_platform:str = None,
default_product:str = None,):
"""
Description:
... | 5,306,425 |
def bug(bot, update):
"""
Retrieve Debian BTS information according to bug number.
Currently, we only send the bug title.
"""
# make sure it is dedicated for self
#TODO FIXME
# make sure we have correct bug number
try:
bug_number = int(update.message.text.split(' ')[1])
... | 5,306,426 |
def validate_internal_function(code: ast.FunctionDef, sig: FunctionSignature) -> None:
""" Validate internal function defintion """
if sig.is_default_func():
raise FunctionDeclarationException("Default function may only be external.", code) | 5,306,427 |
def async_wraps(cls, wrapped_cls, attr_name):
"""Similar to wraps, but for async wrappers of non-async functions."""
def decorator(func):
func.__name__ = attr_name
func.__qualname__ = ".".join((cls.__qualname__, attr_name))
func.__doc__ = """Like :meth:`~{}.{}.{}`, but async.
... | 5,306,428 |
def commands_getter(manager_router):
"""
Gets the command processor using `Client.command_processor` of an ``_EventHandlerManagerRouter``.
Parameters
----------
manager_router : ``_EventHandlerManagerRouter``
The caller manager router.
Returns
-------
handlers : `list` ... | 5,306,429 |
def PowMod(a, e, m):
"""Deprecated. Use pow(a, e, m) instead."""
if e == 0:
return 1%m
if e == 1:
return a%m
return MulMod(PowMod(a, e/2, m), PowMod(a, e-e/2, m), m) | 5,306,430 |
def uniform_density_prior(d, rlim=30.):
"""
Uniform space density prior
Input:
d: distance (typically an array)
Optional:
rlim: Maximum allowed distance (default: 30 kpc)
Output:
Uniform density prior
"""
return np.piecewise(d, [d < 0, (d >= 0)*(d<=rlim), d>rlim]... | 5,306,431 |
def _load_cube(input_files, constraints):
"""Load single :class:`iris.cube.Cube`."""
with warnings.catch_warnings():
warnings.filterwarnings(
'ignore',
message='Ignoring netCDF variable',
category=UserWarning,
module='iris',
)
cubes = iris.... | 5,306,432 |
def dogfact(bot, trigger):
"""Posts a random dog fact."""
url = "https://dog-facts-api.herokuapp.com/api/v1/resources/dogs"
params = {"number": "1"}
try:
dog_fact = requests.get(url, params=params).json()[0]['fact']
bot.say(dog_fact)
except BaseException:
bot.reply("Error rea... | 5,306,433 |
def block_ndi_label_delayed(block, structure):
"""
Delayed version of ``scipy.ndimage.label``.
Parameters
----------
block : dask array (single chunk)
The input array to be labeled.
structure : array of bool
Structure defining the connectivity of the labeling.
Returns
-... | 5,306,434 |
def weighting_matrix(weights, name=None):
""" Creates a weighting matrix.
The ith weight is in the ith upper diagonal of the matrix.
All other entries are 0.
This functions is called once per curriculum update / iteration,
but then used for the entire batch.
Args:
weights: Curriculum w... | 5,306,435 |
def process_coordinate_file(filename):
"""
>>> points = process_coordinate_file("day10_example.txt")
>>> len(points)
31
>>> points[0].x
9
>>> points[0].y
1
>>> points[2].y
-2
>>> points[2].delta_x
-1
:param filename: The name of the file to parse.
:return: The li... | 5,306,436 |
async def test_task_create(aresponses):
"""Test creating a task."""
aresponses.add(
"api.getnotion.com",
"/api/users/sign_in",
"post",
aresponses.Response(
text=load_fixture("auth_success_response.json"),
status=200,
headers={"Content-Type": "a... | 5,306,437 |
def dflist_csvwrite(directory, filename, dataframe_list, idx_name):
"""
Print dataframes in csv files
"""
if not os.path.exists(directory):
os.makedirs(directory)
for df, dataframe in enumerate(dataframe_list):
dataframe.to_csv(
os.path.join(directory, str(''.join((filena... | 5,306,438 |
def log_fail(LF, errStr):
"""
Record a fatal error in the log file, echo to STDOUT and exit.
"""
if LF is None:
LF = sys.stdout
else:
print errStr
if not LF==sys.stdout:
LF.write(errStr + '\n')
LF.close()
sys.exit(1) | 5,306,439 |
def pattern(
text: str,
*,
pattern: Union[str, Collection[str]]
) -> str:
"""Remove strings from `text` using a regex pattern.
Args:
text (str): The text from which patterns will be removed.
pattern: The pattern to match.
Returns:
str
"""
if isinstance(pattern, ... | 5,306,440 |
def drawFrequencies(drawType,d,m,Sigma = None):
"""Draw the 'frequencies' or projection matrix Omega for sketching.
Arguments:
- drawType: a string indicating the sampling pattern (Lambda) to use, one of the following:
-- "gaussian" or "G" : Gaussian sampling > Lambda = N(0,Sigma... | 5,306,441 |
def check_server_audits(
ctx,
project: int,
form_id: str,
report_file: Path,
audit_dir: Path,
time: str,
since_prev: bool,
):
"""
Check audit files on ODK Central for correctness.
This command saves bad audits to disk so they can be corrected.
After correcting them, use repa... | 5,306,442 |
def edgearr_tcrude(edgearr, siglev, ednum, TOL=3., tfrac=0.33, verbose=False,
maxshift=0.15, bpm=None, skip_bad=True):
""" Use trace_crude to refine slit edges
It is also used to remove bad slit edges and merge slit edges
Parameters
----------
edgearr : ndarray
Edge array
... | 5,306,443 |
def convert_color(ms_convert, cv_convert, plot=False):
"""
ConvertColor with different mode.
"""
# First dataset
dataset1 = ds.TFRecordDataset(DATA_DIR, SCHEMA_DIR, shuffle=False)
decode_op = c_vision.Decode()
convertcolor_op = c_vision.ConvertColor(ms_convert)
dataset1 = dataset1.map(op... | 5,306,444 |
def _get_trigger(model, machine, trigger_name, *args, **kwargs):
"""Convenience function added to the model to trigger events by name.
Args:
model (object): Model with assigned event trigger.
machine (Machine): The machine containing the evaluated events.
trigger_name (str): Name of the ... | 5,306,445 |
def variogram(stats, t):
"""
Helper function that computes the variogram for a given lag t. The variogram
is the mean of the mean squared sum of deviations of lag t of each sequence.
Args:
stats: A list of sequences
"""
m = len(stats)
n = stats[0].size
return sum([np.sum((s[t+1:... | 5,306,446 |
def _environ_cols_wrapper(): # pragma: no cover
"""
Return a function which gets width and height of console
(linux,osx,windows,cygwin).
"""
import platform
current_os = platform.system()
_environ_cols = None
if current_os == 'Windows':
_environ_cols = _environ_cols_windows
... | 5,306,447 |
def _get_parser():
"""Return :class:`argparse.ArgumentParser`."""
import argparse
parser = argparse.ArgumentParser(
description=__doc__
)
parser.add_argument(
'-f', '--force', dest='force',
help='Force installation of packages.',
action='store_true',
)
pars... | 5,306,448 |
def test_after_get_with_frameset(frameset_with_6_frames, test_db_cursor):
"""Ensure that the frame object contains its frameset name, if any."""
frameset_obj = entities.Frameset.get(frameset_with_6_frames)
frameset_name = frameset_obj.name
for frame_obj in frameset_obj.child_frames:
assert frame... | 5,306,449 |
def os_cwd():
"""Returns the pathlib object for the current working directory
Examples:
>>> os_cwd()\n
'/home/cooluser/pyplay'
"""
import os
return os.getcwd() | 5,306,450 |
def from_timestamp_to_datetime(timestamp, unit='ms'):
"""
:param timestamp: timestamp in unix format.
:param unit: measurement unit used in the timestamp.
:return: the timestamp in date_time format.
"""
import pandas
return pandas.to_datetime(timestamp, unit=unit) | 5,306,451 |
def multi_classif_inference(
all_outputs,
all_labels,
criterion,
**kwargs
):
"""Multi classification inference.
Parameters
----------
all_outputs
All outputs of a forward process of a model.
all_labels
All labels of the corresponding inputs to the out... | 5,306,452 |
def as_unit_vector(vec):
"""Divides a vector by its length to give a vector of length 1
(unit vector)"""
return vec / np.linalg.norm(vec) | 5,306,453 |
def followers(request, username, template_name="microblogging/followers.html"):
"""
a list of users following the given user.
"""
return _follow_list(request, username, template_name) | 5,306,454 |
def calc_total_fuel_reqs(filename):
"""
This function iterates through all modules and find total fuel
requirements.
"""
input_file = open(filename, "r")
cumulative_total = 0 # initialize sum as 0
# iterate through list
for input_line in input_file:
try:
mass = input... | 5,306,455 |
def test_clean_populate_slug(mock_super_clean):
"""
Cleaning an instance with no slug should generate a new slug.
"""
name = "foo"
inst = models.SlugModel()
setattr(inst, models.SlugModel.SLUG_SOURCE, name)
slug = "foo-bar"
with mock.patch.object(
inst, "generate_slug", return_v... | 5,306,456 |
def check_valid_user(function):
"""
Custom decorator for batch views.
Check if the authenticated user is a user in the batch database and make
the record available in the decorated function.
"""
@wraps(function)
def wrap(request, *args, **kwargs):
user = get_user_from_request(reques... | 5,306,457 |
def formatTarget(data):
"""
:param data: int
"""
good = 0
bad = 0
avg = np.mean(data)
for index in range(data.shape[0]):
val = data[index]
if val < avg:
data[index] = 0
good += 1
else:
data[index] = 1
bad += 1
# prin... | 5,306,458 |
def session_maker(engine): # pylint: disable=redefined-outer-name
"""Create an ORM session from the engine"""
return sessionmaker(bind=engine) | 5,306,459 |
def test_to_class(requests_mock: Mock) -> None:
"""Tests required information from json."""
items = [
{
"id": "54aae292e7798909064f1575",
"item_name": "Secura Dual Cestra",
"thumb": (
"icons/en/thumbs/secura_dual_cestra"
".3d47a4ec6675f... | 5,306,460 |
def log_me(name: str = "NetEmbs", folder: Optional[str] = None, file_name: Optional[str] = "logs.log",
level: Optional[int] = logging.INFO) -> logging.Logger:
"""
Attach logger to specific file and location
Parameters
----------
name : str, default is 'NetEmbs'
The logger name.
... | 5,306,461 |
def kernel_generator(x_gen, size=(36, 64, 1), phase_shifted=False):
"""Generator for sample images (e.g. proxy for MEIs)
This will infer the dimensionality of the latent space to create images, using
a default if there is less
dim1 - orientation
dim2 - xoffset
dim3 - yoffset
dim4 - spatial... | 5,306,462 |
def getNextMineToFinish(games: List[Game]) -> Game:
"""Given a list of games, return the mine that is open and
next to finish; returns None if there are no unfinished games
(finished=past the 4th our, regardless of whether the reward
has been claimed)
If a game is already finished, it won't be ... | 5,306,463 |
def test_parse_multiline_with_incomplete_comment(parser):
"""A terminator within a comment will be ignored and won't terminate a multiline command.
Un-closed comments effectively comment out everything after the start."""
line = 'multiline command /* with comment in progress;'
statement = parser.parse(l... | 5,306,464 |
def caller_module() -> Path:
"""Returns the name of the file containing the module from which this
function was called. This ignores all modules located directly inside the
parent directory of the current file (tsfile/*)."""
this_file_parent = Path(__file__).parent
for frame in inspect.stack():
... | 5,306,465 |
def read_file(file_path='', sheet_name=0, na_values=NA_VALUES, encoding='ISO-8859-1', delimiter=None, **kwargs):
"""
Read pandas dataframe or file.
Parameters
----------
file_path : dataframe or string
string must refer to file. Currenlty, Excel and csv are supported
sheet_name : integer... | 5,306,466 |
def sequences_generator(batch_size=32,
seq_len=100, n_samples=1000):
""" Generate sequences for training the Neural Network.
vocab_len (int): length of the vocabulary
batch_size (int): size of mini batches
seq_len (int): the max length of the sequences
n_samples (int): number... | 5,306,467 |
def get_matrices(src, domain):
"""Reads the STIX and returns a list of all matrices in the STIX"""
matrices = src.query([
stix2.Filter('type', '=', 'x-mitre-matrix'),
])
# Filter out by domain
matrices = [x for x in matrices if not hasattr(x, 'x_mitre_domains') or domain in x.get('x_mitre_... | 5,306,468 |
def get_test_queue_contents(vmcfg, courseId):
"""Get the contents of the test queues for all testers configured
in the system."""
try:
tstcfg = vmcfg.testers()
queue_contents = {} # dict of strings
for tester_id in tstcfg:
queue_contents[tester_id] = submit.get_tester_que... | 5,306,469 |
def qgrams_to_char(s: list) -> str:
"""Converts a list of q-grams to a string.
Parameters
----------
s : list
List of q-grams.
Returns
-------
A string from q-grams.
"""
if len(s) == 1:
return s[0]
return "".join([s[0]] + [s[i][-1] for i in range(1, len(s))]) | 5,306,470 |
def traverse(coord, np_mask, coord_str):
"""Edge case: if pixel value in mask is 0 at coord, then
bounding box has captured the extreme points in this corner
of the image
"""
x, y = coord
if np_mask[y, x] == 0.0:
return (x, y)
height, width = np_mask.shape
store_x, store_y = 0,... | 5,306,471 |
def collect_pc(grasp_, pc):
"""
grasp_bottom_center, normal, major_pc, minor_pc
"""
grasp_num = len(grasp_)
grasp_ = np.array(grasp_)
grasp_ = grasp_.reshape(-1, 5,
3) # prevent to have grasp that only have number 1
grasp_bottom_center = grasp_[:, 0]
approach... | 5,306,472 |
def change_ids(dataset: Dataset, change_id: Callable, methods: Iterable[str] = ()) -> Dataset:
"""
Change the ``dataset``'s ids according to the ``change_id`` function and adapt the provided ``methods``
to work with the new ids.
Parameters
----------
dataset: Dataset
the dataset to perf... | 5,306,473 |
def main():
"""Program wrapper"""
parser = ArgumentParser(description='Process server parameters')
create_arguments(parser)
args = parser.parse_args()
#print "Len of args", len(args)
update_config(args)
start_server() | 5,306,474 |
def test_user_list_endpoint_get(client, is_public, is_author, user):
"""Test learning path endpoint"""
author = UserFactory.create()
user_list = UserListFactory.create(
author=author,
privacy_level=PrivacyLevel.public.value
if is_public
else PrivacyLevel.private.value,
)
... | 5,306,475 |
def _configure_learning_rate(num_samples_per_epoch, global_step):
"""Configures the learning rate.
Args:
num_samples_per_epoch: The number of samples in each epoch of training.
global_step: The global_step tensor.
Returns:
A `Tensor` representing the learning rate.
Raises:
ValueE... | 5,306,476 |
def train_model():
"""
Train the job application model and save the model
:return:
"""
jobs_training = get_training_data(TRAINING__DATA_PATH)
jobs_labels = get_training_labels("applications")
logging.info("Transforming data")
jobs_prepared = full_pipeline.fit_transform(jobs_training)
... | 5,306,477 |
def filter(self, mods=None, name_records=None, pattern=None, regex=None):
"""
Return filtered list of records.
Args:
mods: Name(s) of modules to preserve
name_records: Id(s)/Name(s) of name_records to preserve
Return:
None
"""
r = copy.deepcopy(self)
... | 5,306,478 |
def power(inputArray, power_index=3.0, scale_min=None, scale_max=None):
"""Performs power scaling of the input numpy array.
@type inputArray: numpy array
@param inputArray: image data array
@type power_index: float
@param power_index: power index
@type scale_min: float
@param scale_min: min... | 5,306,479 |
def test_dbfr_requires_filename(script_runner):
"""Test ``dbfr`` requires a filename argument."""
ret = script_runner.run("dbfr")
assert not ret.success | 5,306,480 |
def get_key_for_player_ui(game_id: int, player_name: str) -> JSONResponse:
"""
Method used to generate user private access token for view ui and send moves
:param game_id: integer value of existing game
:param player_name: string with name of player
:return: Response with access token as string
... | 5,306,481 |
def load_speakers(fileobj):
"""Load a list of speakers from a yaml file.
This is a legacy wrapper around load_real_layout; see its documentation for
format info.
Parameters:
file: a file-like object to read yaml from
Returns:
list of Speaker
"""
return load_real_layout(fil... | 5,306,482 |
def test_are_different(left, right):
"""
Test that :func:`are_different` identify different values.
"""
assert utils.are_different(left, right) | 5,306,483 |
def update_tiles():
"""
scan for data with tags with MSAM-Tile name and include in those named tiles
"""
try:
ddb_table_name = CONTENT_TABLE_NAME
ddb_resource = boto3.resource('dynamodb')
ddb_table = ddb_resource.Table(ddb_table_name)
# very broad textual scan
res... | 5,306,484 |
def softmax(x):
"""Compute softmax values for each sets of scores in x.
Copied from Andrew Ng's Deep Learning courses on Coursera
"""
e_x = np.exp(x - np.max(x))
return e_x / e_x.sum() | 5,306,485 |
def find_libgfortran():
"""Get the directory and name of ``libgfortran``.
Assumes and checks that this ``libgfortran`` is **only** for
``x86_64``.
Exits the program with a status code of 1 if:
* there is more than one (or zero) directories that contain
``libgfortran.dylib``.
* the ``lib... | 5,306,486 |
def test_calc_sum():
"""Test sum valid inputs."""
from app.cli import sum as s
runner = CliRunner()
result = runner.invoke(s, ["1", "0.2", "0.3"])
assert result.exit_code == 0
assert pytest.approx(float(result.output)) == 1.5 | 5,306,487 |
def parse_args(args):
"""Parse command-line arguments.
Parameters
----------
args : list of strings
command-line arguments.
Returns
-------
options : :class:`argparse.ArgumentParser`
Command line arguments.
"""
parser = argparse.ArgumentParser(description = __doc__... | 5,306,488 |
def test_settings_env_names_func_no_env_prefix() -> None:
"""
is an error raised if the settings class does not define a valid
env_prefix
"""
raise NotImplementedError | 5,306,489 |
def result(app: dash.Dash, data: GameData) -> html:
"""Layout for the result page. This page get display after every user prediction.
This pages displays the predictions from the user and the ai together with
the ground truth. An explanation for the ai prediction is also provided.
Arguments:
ap... | 5,306,490 |
def iterate_module_func(m, module, func, converged):
"""Call function func() in specified module (if available) and use the result to
adjust model convergence status. If func doesn't exist or returns None, convergence
status will not be changed."""
module_converged = None
iter_func = getattr(module,... | 5,306,491 |
def trace_color_table(measurement):
"""
Returns one of the standard color tables for TRACE JP2 files.
"""
if measurement == 'WL':
return cmap_from_rgb_file(f'TRACE {measurement}', 'grayscale.csv')
try:
return cmap_from_rgb_file(f'TRACE {measurement}', f'trace_{measurement}.csv')
... | 5,306,492 |
def redeemBLVT(tokenName, amount, recvWindow=""):
"""# Redeem BLVT (USER_DATA)
#### `POST /sapi/v1/blvt/redeem (HMAC SHA256)`
### Weight:
1
### Parameters:
Name |Type |Mandatory |Description
--------|--------|--------|--------
tokenName |STRING |YES |BTCDOWN, BTCUP
amount |DECIMAL |YES |
recvWindow |LONG |NO |
ti... | 5,306,493 |
def simulate():
"""
Use the tool to simulate genotypes
"""
pass | 5,306,494 |
def getGitInfo():
"""Make a build string for svn
Returns a string or None if not in a git repository"""
(gitLocalVersion, local) = ("","")
# need to do a 'git diff' because 'describe --dirty' can get confused by timestamps
(gitLocalVersion,stderr) = Popen("git diff --shortstat", shell=True, s... | 5,306,495 |
def computational_form(data):
"""
Repackages numbers, Series, or DataFrames
.. deprecated:: 2.2.0
`computational_form` will be removed in pysat 3.0.0, it will
be added to pysatSeasons
Regardless of input format, mathematical operations may be performed on the
output via the same pandas... | 5,306,496 |
def _check_df_load(df):
"""Check if `df` is already loaded in, if not, load from file."""
if isinstance(df, str):
if df.lower().endswith("json"):
return _check_gdf_load(df)
else:
return pd.read_csv(df)
elif isinstance(df, pd.DataFrame):
return df
else:
... | 5,306,497 |
def disableOne(jobID=None):
"""
Disable one record in PlaceJob table.
:param jobID: Database record ID for PlaceJob table.
:return: None
"""
if not jobID:
jobID = int(input("jobManager. Disable - enter PlaceJob ID /> "))
db.PlaceJob.get(jobID).setDisabled()
print("Disabled job ... | 5,306,498 |
def delete_channel(accountId, apiKey, channelId, verbose=False):
"""Deletes a channel.
Parameters
----------
accountId: str
apiKey: str
channelId: str
the channel ID to delete
verbose: bool, optional
Returns
-------
bool
True if the channel was deleted, False if... | 5,306,499 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.