content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def MobileNetV3_Large_Base(num_classes,
in_channels):
"""构建基础(大型)MobileNetV3
"""
return MobileNetV3_Large(num_classes=num_classes,
in_channels=in_channels,
alpha=1.0) | 5,321,500 |
def test_random_obscurity():
"""Check obfuscation for 1000 randomly generated ASCII strings."""
for _ in range(1000):
text = ''.join(choices(printable, k=randint(1, 1024)))
assert unobscure(obscure(text)) == text | 5,321,501 |
def arg_show(cli_args):
"""Show a card summary"""
board = backlog_board()
card = card_by_id(cli_args.card_id, board)
if not card:
return
print(f'{colorama.Fore.YELLOW}{colorama.Style.BRIGHT}{card.name}{colorama.Fore.RESET}')
print(f'Due: {format_due_date(card)}{colorama.Fore.RESET}{c... | 5,321,502 |
def compute_trajectory_points(path, sgrid,
ugrid, xgrid,
dt=1e-2, smooth=True,
smooth_eps=1e-4):
"""Compute trajectory with uniform sampling time.
Note
----
Additionally, if `smooth` is True, the return trajectory... | 5,321,503 |
def get_split_parser():
"""
Returns the parser used for the split tool which defines all the available arguments.
This can be used for generating documentation about the tool using Sphinx.
:return: the parser object
:rtype: :class:`argparse.ArgumentParser`
"""
parser = argparse.ArgumentPar... | 5,321,504 |
def build():
""" Build the package to be uploaded to PyPI. """
build_dir = os.path.join(os.path.dirname(os.path.dirname(__file__)),
"build")
dist_dir = os.path.join(os.path.dirname(os.path.dirname(__file__)),
"dist")
eggs_dir = os.path.join(os.pat... | 5,321,505 |
def _reorder_cols(
df, key_columns: Tuple[str], master_grouping_key: str
) -> pd.DataFrame:
"""
Helper function for creating a user-friendly schema structure for the output prediction
dataframe that mirrors what would be expected (grouping columns preceding data).
:param df: dataframe with grouping... | 5,321,506 |
def ExecExternalProgram(argv, environ):
"""
"""
# TODO: If there is an error, like the file isn't executable, then we should
# exit, and the parent will reap it. Should it capture stderr?
try:
os.execvpe(argv[0], argv, environ)
except OSError as e:
log('Unexpected error in execvpe(%r, %r, ...): %s'... | 5,321,507 |
def clip(text):
"""
Attempts to copy the specified text to the clipboard, returning
a boolean indicating success.
"""
text_bytes = text.encode()
try:
pbcopy = subprocess.Popen("pbcopy", stdin=subprocess.PIPE, stdout=subprocess.PIPE)
pbcopy.communicate(text_bytes)
return(not pbcopy.returncode)
except ... | 5,321,508 |
def work_pause(calculations):
"""
Pause running work calculations
"""
from aiida import work
from aiida.work import RemoteException, DeliveryFailed, CommunicationTimeout
controller = work.AiiDAManager.get_process_controller()
for calculation in calculations:
if calculation.is_termi... | 5,321,509 |
def testWriteContentVolume_always_contentIsPersistedToVolume():
"""Creates a volumes, a check its content by reading it using a mounted container."""
volumes.create_volume('unitest_ostorlab_volume', {'test': b'Cat is alive! :)', 'notest': b'Cat is dead! :('})
client = docker.from_env()
out = client.con... | 5,321,510 |
def create_rule(rule: Dict[str, Any]) -> Dict[str, Any]:
"""Create a rule, returning the result from SmartThings."""
url = _url("/rules")
params = {"locationId": CONTEXT.get().location_id}
response = requests.post(url=url, headers=_headers(), params=params, json=rule)
_raise_for_status(response)
... | 5,321,511 |
def _get_bot_config():
"""Returns the bot_config.py module. Imports it only once.
This file is called implicitly by _call_hook() and _call_hook_safe().
"""
global _BOT_CONFIG
if not _BOT_CONFIG:
from config import bot_config as _BOT_CONFIG
return _BOT_CONFIG | 5,321,512 |
async def test_login_success_extra(opp, oppio_client_supervisor):
"""Test auth with extra data."""
with patch(
"openpeerpower.auth.providers.openpeerpower."
"OppAuthProvider.async_validate_login",
) as mock_login:
resp = await oppio_client_supervisor.post(
"/api/oppio_aut... | 5,321,513 |
def img_post_process(img_tensor):
"""Image postprocess
Convert torch.tensor() images into list of cv2 images.
1. Convert torch.tensor() to np.array(), and transpose [C, H, W] to [H, W, C].
2. Scale [0., 1.] into [0, 255].
3. Convert data format float to np.uint8.
4. Convert color channels from R... | 5,321,514 |
def detect():
"""Detect devices and applications"""
pass | 5,321,515 |
def InterruptibleSleep(sleep_time):
"""Puts thread to sleep, checking this threads exit_flag four times a second.
Args:
sleep_time: Time to sleep.
"""
slept = 0.0
epsilon = .0001
thread = threading.currentThread()
while slept < sleep_time - epsilon:
remaining = sleep_time - slept
this_sleep_t... | 5,321,516 |
def test_get_ticket_failure_noticket(td_instance, resp, requests_mock):
"""
Test the get_ticket() method, make sure it returns {} when the ticket details cannot
be fetched.
"""
MOCK_TICKET_URL: str = "https://zccsammdu.zendesk.com/api/v2/tickets/2.json"
MOCK_USER_URL: str = "https://zccsammdu.ze... | 5,321,517 |
def apply_grid(dataset, masker=None, scale=5, threshold=None):
""" Imposes a 3D grid on the brain volume and averages across all voxels
that fall within each cell.
Args:
dataset: Data to apply grid to. Either a Dataset instance, or a numpy
array with voxels in rows and features in column... | 5,321,518 |
def draw_lines(img, lines, color=[255, 0, 0], thickness=6):
"""
NOTE: this is the function you might want to use as a starting point once you want to
average/extrapolate the line segments you detect to map out the full
extent of the lane (going from the result shown in raw-lines-example.mp4
to that... | 5,321,519 |
def cookiecutter_template(
output_dir: Path,
repo: Repo,
cruft_state: CruftState,
project_dir: Path = Path("."),
cookiecutter_input: bool = False,
checkout: Optional[str] = None,
deleted_paths: Optional[Set[Path]] = None,
update_deleted_paths: bool = False,
) -> CookiecutterContext:
... | 5,321,520 |
def get_item():
"""Returns a dict representing an item."""
return {
'name': 'Nikon D3100 14.2 MP',
'category': 'Cameras',
'subcategory': 'Nikon Cameras',
'extended_info': {}
} | 5,321,521 |
def humanify_ms(ms: int) -> str:
""" Converts an amount of millis to a more readable string.
Args:
ms (int): the amount of millis to convert
Returns:
The human string that represents the given amount of millis
"""
if ms > TimeUnits.MS_IN_MIN:
return "{:d}m {:d}s".format(
... | 5,321,522 |
def abs_(input):
"""
In-place version of :func:`treetensor.torch.abs`.
Examples::
>>> import torch
>>> import treetensor.torch as ttorch
>>> t = ttorch.tensor([12, 0, -3])
>>> ttorch.abs_(t)
>>> t
tensor([12, 0, 3])
>>> t = ttorch.tensor({
... | 5,321,523 |
def n_age_sex():
"""Return DataFrame of population split by age and sex."""
path = os.path.join(INPUT_DIR, 'census/sex_by_age.xlsx')
data = pd.read_excel(path, 'Sheet 1', header=10, skipfooter=3, index_col=0)
data = data[2:][['Males', 'Females']].reset_index(drop=True)
return data | 5,321,524 |
def get_filepath(filepath, overwrite):
"""
Get the filepath to download to and ensure dir exists.
Returns
-------
`pathlib.Path`, `bool`
"""
filepath = pathlib.Path(filepath)
if filepath.exists():
if not overwrite:
return str(filepath), True
if overwrite == '... | 5,321,525 |
def argparse_is_valid_hostname(hostname):
""" Validate the hostname passed in.
Returns the hostname if it is valid, otherwise it raises an exception.
"""
if len(hostname) > 255:
raise argparse.argumenttypeerror("Argument 'hostname' is not valid. " +
... | 5,321,526 |
def test_initialization():
"""Class initialization test."""
sdnc = OranSdnc()
assert isinstance(sdnc, OranSdnc) | 5,321,527 |
def test_found_priority_of_value_in_queue_is_correct(filled_queue):
"""Test that the priority found is correct."""
assert filled_queue.priority('c') == 4 | 5,321,528 |
def compute_census(img_l: np.ndarray = None, img_r: np.ndarray = None, offset: int = 7) -> (np.ndarray, np.ndarray):
"""
Census feature extraction (for more details see https://en.wikipedia.org/wiki/Census_transform)
:param img_l: left image
:param img_r: right image
:param offset: pixel offset on ... | 5,321,529 |
def dedent(text):
"""Remove any common leading whitespace from every line in a given text."""
return textwrap.dedent(text) | 5,321,530 |
def get_agents(agents: Dict, nr_players: int, action_num: int, state_shape: List):
"""
Initalize agents to play the game.
:param nr_players: Number of players, amount of agents generated
:param agents: Dictionary of agent_name: number of agents pairs
"""
agent_list = list()
i = 0
for age... | 5,321,531 |
def enumerate_square(i, n):
"""
Given i in the range(n^2-n) compute a bijective mapping
range(n^2-n) -> range(n)*range(n-1)
"""
row = int(i // (n-1))
col = int(i % (n-1))
if col >= row:
col += 1
return row, col | 5,321,532 |
def cprint(msg: str, *args: Any, **kw: Any):
""" Print colored message to stdout. """
if len(args) or len(kw):
msg = msg.format(*args, **kw)
print(fmt('{}<0>'.format(msg))) | 5,321,533 |
def universal_transformer_with_lstm_as_transition_function(
layer_inputs, step, hparams, ffn_unit, attention_unit,
pad_remover=None):
"""Universal Transformer which uses a lstm as transition function.
It's kind of like having a lstm, filliped vertically next to the Universal
Transformer that co... | 5,321,534 |
async def test_set_position(hass, start_ha, service_calls):
"""Test the set_position command."""
with assert_setup_component(1, "cover"):
assert await setup.async_setup_component(
hass,
"cover",
{
"cover": {
"platform": "template",
... | 5,321,535 |
def extract_names(bigrams):
"""
Tag each of the bigram tuples with the appropriate Part of Speech.
"""
named_bigrams = []
NUM_BIGRAMS = len(bigrams)
stemmer = LancasterStemmer()
for index, bigram in enumerate(bigrams):
if bigram[0].upper() in FIRST_NAMES:
person = " ".joi... | 5,321,536 |
def GetActiveProjectAndAccount():
"""Get the active project name and account for the active credentials.
For use with wrapping legacy tools that take projects and credentials on
the command line.
Returns:
(str, str), A tuple whose first element is the project, and whose second
element is the account.
... | 5,321,537 |
def csrf_protection(func):
"""
Protect resource from common CSRF attacks by checking user agent and referrer
"""
import falcon
def wrapped(self, req, resp, *args, **kwargs):
# Assume curl and python-requests are used intentionally
if req.user_agent.startswith("curl/") or req.user_age... | 5,321,538 |
async def get_system(
system_id: UUID = Path(
..., description="ID of system to get", example=models.SYSTEM_ID
),
storage: StorageInterface = Depends(StorageInterface),
) -> models.StoredPVSystem:
"""Get a single PV System"""
with storage.start_transaction() as st:
return st.get_syst... | 5,321,539 |
def test_create_user(clean_db):
"""Try to create a user that doesn't exist"""
Users.create(PROFILE)
user = Users.find_by_email(EMAIL)
assert user
assert user.email == EMAIL | 5,321,540 |
def get_playback_time(playback_duration):
""" Get the playback time(in seconds) from the string:
Eg: PT0H1M59.89S
"""
# Get all the numbers in the string
numbers = re.split('[PTHMS]', playback_duration)
# remove all the empty strings
numbers = [value for value in numbers if value != '']
... | 5,321,541 |
def FindAddressAsync(fabricid: int, nodeid: int, callback, timeout_ms=1000):
"""Discovers the IP address(es) of a node.
Args:
fabricid: the fabric to which the node is attached
nodeid: the node id to find
callback: Will be called once node resolution completes.
"""
_GetDiscoveryLib... | 5,321,542 |
def rate_limit(state, task_name, rate_limit, **kwargs):
"""Tell worker(s) to modify the rate limit for a task by type.
See Also:
:attr:`celery.task.base.Task.rate_limit`.
Arguments:
task_name (str): Type of task to set rate limit for.
rate_limit (int, str): New rate limit.
... | 5,321,543 |
def listdict2dictlist(listdict: list, to_array=False) -> dict:
"""
@type listdict: list
@param listdict: list of dicts with the same keys
@return: dictlist: dict of lists of the same lengths
@rtype: dict
"""
d = {k: [d[k] for d in listdict] for k in listdict[0].keys()}
if to_array:
... | 5,321,544 |
def hitLine(lineA, lineB, point, lineWidth):
"""Checks whether the point is in line or out.
lineA tuple: a point of the line.
lineB tuple: another point of the line.
point tuple: point we want to check.
lineWidth float: width of the line.
returns: True if in and False if out.
"""
if li... | 5,321,545 |
def parse_args() -> Namespace:
"""
Parse arguments.
Parse optional arguments passed to the application during runtime and
return the results.
Returns
-------
Namespace
Returns a ``Namespace`` containing all of the arguments passed by the
user including defaults.
"""
... | 5,321,546 |
def PatchWord(ea, value):
"""
Change value of a program word (2 bytes)
@param ea: linear address
@param value: new value of the word
@return: 1 if successful, 0 if not
"""
return idaapi.patch_word(ea, value) | 5,321,547 |
def _binary_array_to_hex(arr):
"""
internal function to make a hex string out of a binary array
"""
h = 0
s = []
for i, v in enumerate(arr.flatten()):
if v:
h += 2**(i % 8)
if (i % 8) == 7:
s.append(hex(h)[2:].rjust(2, '0'))
h = 0
return "... | 5,321,548 |
def float_nsf(num, precision=17):
"""n-Significant Figures"""
return ('{0:.%ie}' % (precision - 1)).format(float(num)) | 5,321,549 |
def _update_bundle_configuration(args):
"""Update bundle configuration to reflect
correct random seed if rollouts not run during
the execution (e.g. bundle-only execution)
:args: Argparse.Args: User-defined arguments
"""
name_components = args.bundle_only_dir.split("/")[-1].split("_")
try:... | 5,321,550 |
def write_to_log_on_success(repo, logFileDir, source):
""" Write log data to log file in case of successful operation
Args:
repo (str): repo of site being scrapped
logFileDir (str): path to log directory
"""
logData = build_log_data_on_success(repo, source)
write_to_file(logFileDir... | 5,321,551 |
def logit_layer_for_bitext(
nb_classes, # V
inputs, # [B, M, dim]
outputs, # [B, N]
dim,
nb_softmax_samples, # S
is_training,
approximation='botev-batch',
support=None, # [S]
importance=None, # [S]
name='logit'
):
"""
Logit st... | 5,321,552 |
def get_counts_filename(align_path, output_dir):
"""returns counts output path
Arguments:
- align_path: path to the alignment file. The basename will be
modified to use a .txt suffix
- output_dir: directory where the counts file is to be written
"""
fn = os.path.basename(alig... | 5,321,553 |
def run_command(client: ParallelSSHClient, command: str) -> CommandResult:
"""Executes identical command on all hosts attached to client.
Will wait until all hosts complete the command execution or timeout is reached.
Re-raises pssh exceptions.
# TODO Handle more specific exceptions
"""
# stop_... | 5,321,554 |
def test_hash_tableau(doctest):
"""
! (define ht #hash((1.0 . 3) (1 . 2)))
! (define ht2 '#hash(((a . b) . 1)))
> (hash-ref ht 1.0)
3
> (hash-ref ht 1)
2
> (hash-ref ht2 (cons 'a 'b) 2)
1
""" | 5,321,555 |
def angle_close(angle1, angle2):
""" Determines whether an angle1 is close to angle2. """
return abs(angle_difference(angle1, angle2)) < np.pi/8 | 5,321,556 |
def server_url():
# type: () -> Optional[str]
"""Get the configured server URL
"""
url = toolkit.config.get(SERVER_URL_CONF_KEY)
if not url:
raise ValueError("Configuration option '{}' is not set".format(
SERVER_URL_CONF_KEY))
if url[-1] == '/':
url = url[0:-1]
re... | 5,321,557 |
def clean_data():
"""
Method for cleaning the data and removing unnecessary features
Args:
None
Returns:
df (pandas dataframe): Return pandas dataframe
"""
df = pd.read_csv("dashboard/asset/data/kl_billboard.csv")
# Drop different types of roads such as motorway, trunk etc... | 5,321,558 |
def test_run_psi4(tmp_path):
"""Tests qcengine run with psi4 and JSON input"""
def check_result(stdout):
output = json.loads(stdout)
assert output["provenance"]["creator"].lower() == "psi4"
assert output["success"] is True
inp = AtomicInput(molecule=get_molecule("hydrogen"), driver... | 5,321,559 |
def load_dataset_from_intermediate_file(fname):
"""Save Stingray object to intermediate file."""
from stingray.lightcurve import Lightcurve
from stingray.events import EventList
from stingray.crossspectrum import Crossspectrum
from hendrics.io import get_file_type
from stingray.io import _retri... | 5,321,560 |
def _FlowMethod(func):
"""Decorator that checks the if port_id exists on board."""
@functools.wraps(func)
def wrapper(instance, port_id, *args, **kwargs):
if port_id not in instance.flows:
raise FlowManagerError('Not a exist port_id %d' % port_id)
return func(instance, port_id, *args, **kwargs)
re... | 5,321,561 |
def merge_noddi_ped(in_file, in_bvec, in_bval, alt_file, alt_bvec, alt_bval):
"""
This is to merge the two ped images and also concatenate the bvecs and bvals
:return:
"""
from clinica.utils.dwi import merge_volumes_tdim
import os.path as op
import os
out_bvals_tab = op.abspath('merged.... | 5,321,562 |
def rainbow_text(x, y, strings, colors, orientation='horizontal',
ax=None, **kwargs):
"""
Take a list of *strings* and *colors* and place them next to each
other, with text strings[i] being shown in colors[i].
Parameters
----------
x, y : float
Text position in data coo... | 5,321,563 |
def _xml_column_name_orig_to_new(column_name_orig):
"""Converts name of XML column from original (segmotion) to new format.
:param column_name_orig: Column name in original format.
:return: column_name: Column name in new format.
"""
orig_column_flags = [c == column_name_orig for c in XML_COLUMN_N... | 5,321,564 |
def friendly_tb() -> None:
"""Shows the a simplified Python traceback,
which includes the hint/suggestion if available.
"""
explain("friendly_tb") | 5,321,565 |
def create_table():
""" create table if not exists """
CURSOR.execute("""CREATE TABLE IF NOT EXISTS {} (
[ID] NVARCHAR NOT NULL PRIMARY KEY,
[Name] NVARCHAR,
[Definition] NVARCHAR)""".format(TABLE_NAME)) | 5,321,566 |
def copy_from_file(conn, df, table):
"""
Here we are going save the dataframe on disk as
a csv file, load the csv file
and use copy_from() to copy it to the table
"""
# Save the dataframe to disk
tmp_df = "./tmp_dataframe.csv"
df.to_csv(tmp_df, header=False)
f = open(tmp_df, 'r')
... | 5,321,567 |
def get_ocp_repo(rhel_major_version=None):
"""
Get ocp repo file, name will be generated dynamically based on
ocp version.
Args:
rhel_major_version (int): Major version of RHEL. If not specified it will
take major version from config.ENV_DATA["rhel_version"]
Returns:
st... | 5,321,568 |
def update_collection(collection):
"""Create or update a collection."""
pass | 5,321,569 |
def ndwi(raster):
"""
Normalized Difference Water Index (NDWI)
NDWI := factor * (Green - NIR1) / (Green + NIR1)
:param raster: xarray or numpy array object in the form (c, h, w)
:return: new band with SI calculated
"""
nir1, green = _get_band_locations(
raster.attrs['band_names'], ['... | 5,321,570 |
def get_settings():
"""Utility function to retrieve settings.py values with defaults"""
return {
"DJANGO_WYSIWYG_MEDIA_URL": getattr(settings, "DJANGO_WYSIWYG_MEDIA_URL", urljoin(settings.STATIC_URL, "ckeditor/")),
"DJANGO_WYSIWYG_FLAVOR": getattr(settings, "DJANGO_WYSIWYG_FLAVOR", "yui"),
... | 5,321,571 |
def einsum_via_matmul(input_tensor, w, num_inner_dims):
"""Implements einsum via matmul and reshape ops.
Args:
input_tensor: float Tensor of shape [<batch_dims>, <inner_dims>].
w: float Tensor of shape [<inner_dims>, <outer_dims>].
num_inner_dims: int. number of dimensions to use for in... | 5,321,572 |
def cost(guess, tdoa, array):
""" Calculate the sum of the squares of the loss function of hyperbolic
least squares problem
guess : 1D or 2D row ndarray with one or more guesses coordinates
tdoa : column 2D ndarray with the TDOA from some reference sensor
receptorsPosit... | 5,321,573 |
def from_literal(tup):
"""Convert from simple literal form to the more uniform typestruct."""
def expand(vals):
return [from_literal(x) for x in vals]
def union(vals):
if not isinstance(vals, tuple):
vals = (vals,)
v = expand(vals)
return frozenset(v)
if not isinstance(tup, tuple):
... | 5,321,574 |
def find_nearest_claims(search_set, candidate_set, cfg):
"""
Finds and prints the nearest claims for each tweet. Serves as a
controller function that dispatches work to various other helper
functions.
:param search_set: string denoting what data to use for the search set
:param candidate_set: s... | 5,321,575 |
def distill_resnet_32_to_15_cifar20x5():
"""Set of hyperparameters."""
hparams = distill_base()
hparams.teacher_model = "resnet"
hparams.teacher_hparams = "resnet_cifar_32"
hparams.student_model = "resnet"
hparams.student_hparams = "resnet_cifar_15"
hparams.optimizer_momentum_nesterov = True
# (base_lr... | 5,321,576 |
def timestamp() -> datetime.datetime:
"""
Returns a datetime object representing the current UTC time. The last 3 digits of the microsecond frame are set
to zero.
:return: a UTC timestamp
"""
# Get tz-aware datetime object.
dt = arrow.utcnow().naive
# Set the last three ms digits to 0... | 5,321,577 |
def main(base_url, node, sample_size, from_date, to_date):
"""Make-like execution flow
Function will not run if dependent file exists
"""
getAllPages(base_url, node, from_date=from_date, to_date=to_date) # Depends on document.csv
sampleDocuments(sample_size) # Depends on sampled_documents.csv
getAndSaveDocuments... | 5,321,578 |
def next_fake_batch():
"""
Return random seeds for the generator.
"""
batch = np.random.uniform(
-1.0,
1.0,
size=[FLAGS.batch_size, FLAGS.seed_size])
return batch.astype(np.float32) | 5,321,579 |
def print_result(error, real_word):
"""" print_result"""
if error == 5:
print("You lost!")
print("Real word is:", real_word)
else:
print("You won!")
return 0 | 5,321,580 |
def tune_knn(x_train, y_train, x_test, y_test):
"""
KNN regressor with grid search
:param x_train:
:param y_train:
:param x_test:
:param y_test:
:return:
"""
n_range = range(1, 10, 1)
tuned_parameters = [{
"n_neighbors": n_range
}]
knn_reg = GridSearchCV(neighbors... | 5,321,581 |
def test_cray_ars_uploads_create(cli_runner, rest_mock):
""" Test cray ars uploads create ... """
runner, cli, config = cli_runner
artifact_id = 'foo'
result = runner.invoke(cli, ['ars', 'uploads', 'create', '--artifact-id', artifact_id])
assert result.exit_code == 0
data = json.loads(result.out... | 5,321,582 |
def read_cpu_info():
"""Return the CPU model number & number of CPUs."""
try:
with open('/proc/cpuinfo') as f:
models = [line[line.index(':')+2:] for line in f if line.startswith('model name')]
return models[0].strip(), len(models)
except:
log.exception('Failed to read CP... | 5,321,583 |
def _yaml_parse(s):
"""Uses yaml module to parse s to a Python value.
First tries to parse as an unnamed flag function with at least two
args and, if successful, returns s unmodified. This prevents yaml
from attempting to parse strings like '1:1' which it considers to
be timestamps.
"""
try... | 5,321,584 |
def test_planar_set_blend_radius_for_horizontal_layers():
""" Tests set_blend_radius on planar slicer. """
#
# # copy to avoid altering the classes, so that all test functions can start from same setup
# print_organizer_copy = copy.deepcopy(print_organizer)
# slicer_copy = copy.deepcopy(slicer)
... | 5,321,585 |
def mongo_convert(sch):
"""Converts a schema dictionary into a mongo-usable form."""
out = {}
for k in sch.keys():
if k == 'type':
out["bsonType"] = sch[k]
elif isinstance(sch[k], list):
out["minimum"] = sch[k][0]
out["maximum"] = sch[k][1]
elif is... | 5,321,586 |
def filter_normalize(rs, construct=range):
"""
Normalize ranges iteratively.
Iterate over all ranges in the given range iterable *rs*, yielding
normalized ranges
"""
for r in rs:
yield normalize(r, construct=construct) | 5,321,587 |
def files_identical(a, b):
"""Return a tuple (file a == file b, index of first difference)"""
a_bytes = open(a, "rb").read()
b_bytes = open(b, "rb").read()
return bytes_identical(a_bytes, b_bytes) | 5,321,588 |
def discounted_cumulative_gain(rank_list):
"""Calculate the discounted cumulative gain based on the input rank list and return a list."""
discounted_cg = []
discounted_cg.append(rank_list[0])
for i in range(1, len(rank_list)):
d = rank_list[i]/math.log2(i+1)
dcg = d + discounted_cg[i-1]
... | 5,321,589 |
def adapter(js_constructor, base=Adapter):
"""
Allows a class to implement its adapting logic with a `js_args()` method on the class itself.
This just helps reduce the amount of code you have to write.
For example:
@adapter('wagtail.mywidget')
class MyWidget():
...
... | 5,321,590 |
def ancienne_fonction_chemin_absolu(relative_path):
"""
Donne le chemin absolu d'un fichier.
PRE : -
POST : Retourne ''C:\\Users\\sacre\\PycharmProjects\\ProjetProgra\\' + 'relative_path'.
"""
base_path = getattr(sys, '_MEIPASS', os.path.dirname(os.path.abspath(__file__)))
p... | 5,321,591 |
def test_no_split_line_wave_algo_3_png() -> None:
"""Failed to detect wave due to missing wave at the bottom."""
MockDisableSeparatePage(MAX_VAL, FUZZING).treat_file(
get_absolute_from_current_path(
__file__, "no_split_line_wave_algo_3.png"
),
{
ConstString.separa... | 5,321,592 |
def main():
"""Main function"""
module = GcpModule(
argument_spec=dict(
state=dict(default='present', choices=['present', 'absent'], type='str'),
name=dict(required=True, type='str'),
disable_dependent_services=dict(type='bool'),
)
)
if not module.pa... | 5,321,593 |
def ha_discover(client: mqtt.Client, userdata: HatchMQTT) -> None:
"""
Open 3 json files, send contents to the correct topics
"""
configs = [
('{}/lightconfig.json'.format(JSON_LOC), userdata.configs['light']),
('{}/soundconfig.json'.format(JSON_LOC), userdata.configs['soun... | 5,321,594 |
def test_download_to_file(req, tmpdir):
"""Test downloading things from NCBI."""
req.get(ENTREZ_URL, text='This works.')
outdir = tmpdir.mkdir('outdir')
filename = outdir.join('foo')
expected = outdir.join('foo.gbk')
config = core.Config(molecule='nucleotide', verbose=False)
core.download_t... | 5,321,595 |
def data(input, name_func=None, doc_func=None, skip_on_empty=False, **legacy):
""" A "brute force" method of parameterizing test cases. Creates new
test cases and injects them into the namespace that the wrapped
function is being defined in. Useful for parameterizing tests in
subclasses of '... | 5,321,596 |
def get_form_field_names(form_class):
"""Return the list of field names of a WTForm.
:param form_class: A `Form` subclass
"""
unbound_fields = form_class._unbound_fields
if unbound_fields:
return [f[0] for f in unbound_fields]
field_names = []
# the following logic has been taken fr... | 5,321,597 |
def gen_empty_structure_data_array(number_of_atoms):
"""
Generate an array data structure to contain structure data.
Parameters
----------
number_of_atoms : int
The number of atoms in the structure.
Determines the size of the axis 0 of the structure array.
Returns
-------
... | 5,321,598 |
def actives_alerts_table(strategy, style='', offset=None, limit=None, col_ofs=None,
group=None, ordering=None, datetime_format='%y-%m-%d %H:%M:%S'):
"""
Returns a table of any active alerts.
"""
COLUMNS = ('Symbol', '#', 'Label', 'TF', 'Created', 'Expiry', 'Countdown', 'Conditio... | 5,321,599 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.