content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def test_compress_fastq_real_with_integrity(
first_tmp_file, second_tmp_file, spring_tmp_path, real_base_context
):
"""Test to run the compress fastq command with integrity check"""
# GIVEN the path to a existing two existing fastq files and a non existing spring
runner = CliRunner()
assert not spri... | 5,304,300 |
def width_track(omega, m_b, release_every=1, n_particles=1, **kwargs):
"""Function takes in an array of unitless pattern speeds, an integer of released
particles and unitless a bar_mass, then calls stream generating function, and
calculates the stream width and track from the simulated streams.
The func... | 5,304,301 |
def p_contents_append_assign(p):
"""contents : contents assign"""
p[0] = p[1]
p[0].append(p[2]) | 5,304,302 |
def main():
"""Parse arguments and call in_toto_mock. """
parser = argparse.ArgumentParser(
formatter_class=argparse.RawDescriptionHelpFormatter,
description="""
A stripped down variant of 'in-toto-run' that can be used to create unsigned
link metadata for the passed command, recording all files in the c... | 5,304,303 |
def compute_mse_labels(params, delta, X, Y, labels, use_sigmoid):
"""
assume a, b, c, delta, X, Y are all in the right dimensions
"""
if use_sigmoid:
sig0, sig1 = params
else:
a,b,c = params
N_patients, N_visits, N_dims = Y.shape
all_mse = 0.
for i in range(... | 5,304,304 |
def main(args):
"""
Discovers bounding boxes and class. Overlays boxes
on original image and saves to same folder.
Arguments
---------
args : dict
Contents:
args.image - image path on disk
args.model_local - model path on disk
args.classes_path - classes file on... | 5,304,305 |
def produce_columns(df):
"""Reports columns for use in model."""
columnsNames = []
for i in df.columns:
if i == 'Survived' or i == 'PassengerId':
pass
else:
columnsNames.append(i)
return columnsNames | 5,304,306 |
def fixture_ref_6_2_3_5():
"""Reference for (load, bins) of 6, [2, 3, 5]."""
ref = {
"load": 6,
"bins": [2, 3, 5],
"solutions": {
key: [(3, 3)] for key in ["length", "capacity", "combo"]
}
}
return ref | 5,304,307 |
def compute_population_threshold(df_entire, base_population_threshold=500):
"""Computes a population threshold to use when deciding whether or not to display a sub-dimension's anomaly detection analysis
:param df_entire: Entire pandas DataFrame which anomaly detection is run on
:type df_entire: pandas.core... | 5,304,308 |
def read_variable_bounds(filename, verbose=False):
"""Read permissible lower and upper bounds for decision variables used in forcefields optimization
:param filename: Name of text file listing bounds for each decision variable that must be optimized
:type filename: str
:param verbose: Print all variab... | 5,304,309 |
def parse_spec_storage_location(location: str) -> SpecStorageLocation:
"""
Parse the spec storage location into components.
Args:
location: The spec storage location to parse.
Returns:
The parsed spec storage location.
"""
sub, spec_id, filename = location.split("/")
versi... | 5,304,310 |
def datastore(plugin, key, string=None, hex=None, mode="must-create", generation=None):
"""Add/modify a {key} and {hex}/{string} data to the data store,
optionally insisting it be {generation}"""
key = normalize_key(key)
khex = key_to_hex(key)
if string is not None:
if hex is not None:
... | 5,304,311 |
def print_footer(html_file):
"""
@summary prints footer of report html file
"""
html_file.write("</BODY>\n\n")
html_file.write("</HTML>") | 5,304,312 |
def recreate_knob_from_optimizer_values(variables, opti_values):
""" recreates knob values from a variable """
knob_object = {}
# create the knobObject based on the position of the opti_values and variables in their array
for idx, val in enumerate(variables):
knob_object[val] = opti_values[... | 5,304,313 |
def make_cube_marker(box_center, box_dim):
""" a reasonable default box marker.
"""
marker = CubeMarker(box_dim)
marker.set_translation(box_center)
marker.set_color_float([1., 0., 0.])
marker.set_alpha(0.80)
return marker.to_msg() | 5,304,314 |
def KDPReadPhysMEM(address, bits):
""" Setup the state for READPHYSMEM64 commands for reading data via kdp
params:
address : int - address where to read the data from
bits : int - number of bits in the intval (8/16/32/64)
returns:
int: read value from memory.
... | 5,304,315 |
def parse_args(args:typing.Sequence[str]=sys.argv[1:]):
"""
Parse the command-line arguments
:param args: argument strings
:return: the options dictionary
"""
parser = argparse.ArgumentParser()
parser.add_argument(
"--input",
required=True,
help="The directory of the... | 5,304,316 |
def query_for_requests(last_time, new_last_time, logger):
"""
Return the rows from the sqlite database after last_time
(and before new_last_time if test mode)
"""
database = SQL_DATABASE
if TEST_MODE:
database = TEST_SQL_DATABASE
conn = sqlite3.connect(database)
rows = []
try... | 5,304,317 |
def combine(
meshes: List[pv.PolyData],
data: Optional[bool] = True,
clean: Optional[bool] = False,
) -> pv.PolyData:
"""
Combine two or more meshes into one mesh.
Only meshes with faces will be combined. Support is not provided for combining
meshes that consist of only points or lines.
... | 5,304,318 |
def magician(*cards, n=1):
"""Determine the fifth card with only four cards."""
# Obviously not a random card, put your code here instead.
show = cards[(n-1)%4]
pile1 = [i for i in cards]
pile1.pop((n-1)%4)
pile2 = deepcopy(pile1)
pile2.sort(key = lambda i: (RANKS.index(i[:i.index(' ')]),SU... | 5,304,319 |
def create_users_from_csv(connection: "Connection", csv_file: str) -> List["User"]:
"""Create new user objects from csv file. Possible header values for the
users are the same as in the `User.create()` method.
Args:
connection: MicroStrategy connection object returned by
`connection.Con... | 5,304,320 |
def catl_keys_prop(catl_kind, catl_info='members', return_type='list',
Program_Msg=fd.Program_Msg(__file__)):
"""
Dictionary key sfor the different galaxy/group properties of
catalogues
Parameters
----------
catl_kind: string, optional (default = 'data')
type of catalogue to use
... | 5,304,321 |
def pa_max_pool(in_dict):
"""Implement `local max pooling` as `masking + global max pooling`.
Args:
feat: pytorch tensor, with shape [N, C, H, W]
mask: pytorch tensor, with shape [N, pC, pH, pW]
Returns:
feat_list: a list (length = pC) of pytorch tensors with shape [N, C]
vis... | 5,304,322 |
def _create_validate(cls, validators):
"""
Create a new validate method with extra validator functions.
"""
def validate(self, value):
super(cls, self).validate(value)
for validator in validators:
validator(value)
validate.__doc__ = validators[0].__doc__
return vali... | 5,304,323 |
def predict_roi(roi, ground_truth, model, device, in_trans=None, batch_size=1, tile_size=256, overlap=0, n_jobs=1,
zoom_level=0):
"""
Parameters
----------
roi: BaseCrop
The polygon representing the roi to process
ground_truth: iterable of Annotation|Polygon
The groun... | 5,304,324 |
def get_ceed_stages(
stage_factory: StageFactoryBase) -> Iterable[Type[StageType]]:
"""Returns all the stage classes defined and exported in this file
(currently none for the internal plugin).
:param stage_factory: The :class:`~ceed.function.FunctionFactoryBase`
instance currently active in... | 5,304,325 |
def scale_quote_of_type(
df: pd.DataFrame, mapping: dict, file_type: str = "quotes"
) -> (pd.DataFrame, dict):
"""
Scales quote values of quotes of a specified type
This function appends an extra row (__adjusted_quote) to a dataframe that contains quotes that have been scaled by
a scale factor spec... | 5,304,326 |
def mysql_metadata_connection_config(host: Text, port: int, database: Text,
username: Text, password: Text
) -> metadata_store_pb2.ConnectionConfig:
"""Convenience function to create mysql-based metadata connection config.
Args:
host: The... | 5,304,327 |
def _update_database(source_folder):
"""更新数据库文件"""
ask_update_db = _inpute_value("是否需要更新数据库表格:Y or N")
if ask_update_db.upper() == 'N':
return
mysql_db_name = _inpute_value("请输入网站使用的数据库名:")
mysql_user = _inpute_value("请输入mysql数据库用户名:")
mysql_password = _inpute_value("请输入mysql数据库密码:")
... | 5,304,328 |
def _status(self):
"""status -> Returns the Shot status. None if no Status is set."""
status = None
tags = self.tags()
for tag in tags:
if tag.metadata().hasKey('tag.status'):
status = tag.metadata().value('tag.status')
return status | 5,304,329 |
def merge_sort(items):
"""Sort given items by splitting list into two approximately equal halves,
sorting each recursively, and merging results into a list in sorted order.
TODO: Running time: ??? Why and under what conditions?
TODO: Memory usage: ??? Why and under what conditions?"""
# TODO: Check ... | 5,304,330 |
def convert_onnx_less(operator, device=None, extra_config={}):
"""
Converter for `ai.onnx.Less`.
Args:
operator: An operator wrapping a `ai.onnx.Less` model
device: String defining the type of device the converted operator should be run on
extra_config: Extra configuration used to s... | 5,304,331 |
def instantiator(objects):
"""
Returns list of java source lines, which encode an instantiator that
binds classes in the root package (and subpackages) to exported objects with the same name.
"""
j = os.path.join
src_root = ut.src_root()
relevant_dirs = ut.listdir(src_root, dirs_only=Tru... | 5,304,332 |
def capped(value, minimum=None, maximum=None, key=None, none_ok=False):
"""
Args:
value: Value to cap
minimum: If specified, value should not be lower than this minimum
maximum: If specified, value should not be higher than this maximum
key (str | None): Text identifying 'value' ... | 5,304,333 |
def conditional_MARC21(record, rule):
"""Function takes a conditional and a mapping dict (called a rule)
and returns the result if the test condition matches the antecedient
Parameters:
record -- MARC21 record
rule -- Rule to match MARC field on
"""
output = []
if rule.has_key('cond... | 5,304,334 |
def evaluate(mc, eval_graph, eval_sess, eval_ops, eval_saver, eval_writer):
"""
Evaluate the model obtained from the last checkpoint
and create the tensorboard summaries.
"""
ckpt = tf.train.get_checkpoint_state(mc["TRAIN_DIR"])
# global_vars = tf.global_variables()
# is_not_initialized = eval_sess.ru... | 5,304,335 |
def row(ctx):
"""Get this cell's row."""
return ctx["cell"].row | 5,304,336 |
def apply_parallel_iter(items, num_procs, func, *args, progress_bar=False, total=None, num_groups=None, backend='loky'):
""" This function parallelizes applying a function to all items in an iterator using the
joblib library. In particular, func is called for each of the items in the list. (Unless
... | 5,304,337 |
def compilest(*args, **kwargs): # real signature unknown
""" Compiles an ST object into a code object. """
pass | 5,304,338 |
def get_external_admin_connection_string(db_name=None, db_prefix=None):
"""Get an admin connection string for access from outside the cluster"""
admin_user, admin_password, admin_db_name = get_admin_db_credentials(db_prefix=db_prefix)
if not db_name:
db_name = admin_db_name
db_host, db_port = ge... | 5,304,339 |
def calc_room_positions_square(side_length, num_rooms):
"""
Calculate the central positions of the square rooms.
"""
sqrt_num_rooms = int(math.sqrt(num_rooms))
if sqrt_num_rooms ** 2 != num_rooms:
raise ValueError("num_rooms must be a perfect square number")
int_positions = np.unravel_... | 5,304,340 |
def plot_polygon(polygons, width: int, height: int):
"""
Plot list of polygons
:param polygons numpy.darray: list of polygons
:param width int: width of image
:param height int: height of image
"""
shapes = []
for p in polygons:
po = Polygon(np.array(list(zip(p[::2], p[1::2]))... | 5,304,341 |
def logout(request: HttpRequest, default_redirect="/"):
"""
This function logs a user out and redirect him to a certain location
:param request: the current HTTP request
:param default_redirect: The location to redirect if no next GET request is given
:return: The HTTP_RESPONSE containing the redire... | 5,304,342 |
def check_nonnegative_number(value, name=""):
"""Ensure that the value is a nonnegative number"""
check_numeric(value, name)
if value < 0:
raise ValueError(f"{name} value must be nonnegative.") | 5,304,343 |
def charging_bar( nb_iter, curr_iter, bar_len=30, msg="", char=u"\u2588"):
"""
Print a charging bar
"""
global last_percent
percent = (100*curr_iter)/nb_iter
if( curr_iter == nb_iter ):
sys.stdout.write('\r'+' '*(bar_len+len(msg)+30)+'\r')
last_percent = -1
elif( last_percen... | 5,304,344 |
def test_last_line(capsys):
"""Check regression of last line ending with space, a char, and no newline.
It wrongly raised a "trailing whitespace".
"""
check("test.rst", "Hell o")
out, err = capsys.readouterr()
assert not err
assert "trailing whitespace" not in out | 5,304,345 |
def cell_slice(payload):
"""Retrieve the next cell from the payload and truncate that one.
:param payload: bytearray
"""
payload_len = len(payload)
if payload_len < 7: # (payload too small, need data)
return None, payload
cmd = cell_get_cmd(payload)
if cell_is_variable_length(cmd):... | 5,304,346 |
def approx_equal(x, y, tol=1e-12, rel=1e-7):
"""approx_equal(x, y [, tol [, rel]]) => True|False
Test whether x is approximately equal to y, using an absolute error
of tol and/or a relative error of rel, whichever is bigger.
>>> approx_equal(1.2589, 1.2587, 0.003)
True
If not given, tol=1e-12... | 5,304,347 |
def calc_entropy(logits):
"""
Calculates the entropy of the output values of the network
:param logits: (TensorFlow Tensor) The input probability for each action
:return: (TensorFlow Tensor) The Entropy of the output values of the network
"""
# Compute softmax
a_0 = logits - tf.reduce_max(i... | 5,304,348 |
def make_environment(domain_name, task_name, rng, frame_stack, action_repeat):
"""Create a visual DMC environment"""
env = suite.load(
domain_name=domain_name,
task_name=task_name,
environment_kwargs={"flat_observation": True},
task_kwargs={"random": rng},
)
camera_id = 2... | 5,304,349 |
def validate_options(options, args):
"""
Given a set of command line options, performs various validation checks
"""
if options.max_length < options.min_length:
sys.stderr.write("The maximum length of a word can not be "
"lesser then minimum length.\n"
... | 5,304,350 |
def convert_examples_to_features(examples, label_list, max_seq_length, tokenizer):
"""Loads a data file into a list of `InputBatch`s."""
label_map = {label: i for i, label in enumerate(label_list)}
features = []
for (ex_index, example) in enumerate(examples):
tokens_a = tokenizer.tokenize(example.text_a)
... | 5,304,351 |
def org_resource_list_layout(list_id, item_id, resource, rfields, record):
"""
Default dataList item renderer for Resources on Profile pages
@param list_id: the HTML ID of the list
@param item_id: the HTML ID of the item
@param resource: the S3Resource to render
@param rfiel... | 5,304,352 |
async def test_setup_with_adbkey(hass):
"""Test that setup succeeds when using an ADB key."""
config = CONFIG_ANDROIDTV_PYTHON_ADB.copy()
config[DOMAIN][CONF_ADBKEY] = hass.config.path("user_provided_adbkey")
patch_key, entity_id = _setup(hass, config)
with patchers.PATCH_ADB_DEVICE, patchers.patch... | 5,304,353 |
def get_post_by_id(request, post_id):
"""Read: Get a post with given event_id
e.g. http://127.0.0.1:8000/api/post/2
"""
if request.method == 'GET':
# key_flag = len(request.GET['eventID'])
# if key_flag:
# record = GISource.objects.filter(event_id=post_id)
# ser... | 5,304,354 |
def fetch_created_ruleset(creator_id):
"""
Get a user ID that want to filter the ruleset that this user make and return a list of ruleset
with the User object of that ruleset.
If the program cannot find the User object,it will append `None` to the return value.
:param creator_id: A user ID
... | 5,304,355 |
def Run(benchmark_spec):
"""Executes the given jar on the specified Spark cluster.
Args:
benchmark_spec: The benchmark specification. Contains all data that is
required to run the benchmark.
Returns:
A list of sample.Sample objects.
"""
spark_cluster = benchmark_spec.spark_service
start = ... | 5,304,356 |
def threshold_stats_img(stat_img=None, mask_img=None, alpha=.001, threshold=3.,
height_control='fpr', cluster_threshold=0,
two_sided=True):
""" Compute the required threshold level and return the thresholded map
Parameters
----------
stat_img : Niimg-like... | 5,304,357 |
def _export_doc_requirements(toml: dict, file: pathlib.Path, *packages) -> int:
"""
Export the provided packages versions.
Return values:
0 no changes
1 exported new requirements
2 file does not exist
3 invalid packages
"""
file = pathlib.Path(file)
if not file.exists():
... | 5,304,358 |
def _extract_function_from_js(name, js):
""" Find a function definition called `name` and extract components.
Return a dict representation of the function.
"""
dbg("Extracting function '%s' from javascript", name)
fpattern = r'function\s+%s\(((?:\w+,?)+)\)\{([^}]+)\}'
m = re.search(fpattern %... | 5,304,359 |
def info():
"""Print a oneliner on stdout for debugging."""
print("%s: sim=%d robotnum=%d teamname=%s ip=%s port=%d" % (sys.argv[0], get_simulated(), get_robot_num(), get_team_name(), get_ip_address(), get_pyro_port())) | 5,304,360 |
def edit_files(files: dict, path: str, clear_all: bool, do_rename: bool):
"""
Set, edit or delete the metadata of the selected file and rename these files
:param files: information from user about the metadata of each file
:param path: the directory where these files are located
:param clear_all: T... | 5,304,361 |
def bootstrap(opt, logger):
"""Bootstrap the engine."""
if not opt.conda_available and not opt.freeze:
logger.warning(
"Command `pip install` may not work, "
"in that case you may want to add `--freeze`"
)
if opt.freeze:
logger.warning(
"You are r... | 5,304,362 |
def test_marginalise_augment(proposal):
"""Test the marginalise augment function"""
proposal.n_marg = 5
proposal.augment_dims = 2
x = np.concatenate([np.random.randn(3, 2), np.zeros((3, 2))], axis=1)
z = np.random.randn(15, 4)
log_prob = np.random.randn(15)
proposal.flow = MagicMock()
pr... | 5,304,363 |
def _check_call(argv, stdin_input=None, **kwargs):
"""Wrapper for subprocess.check_call that adds logging."""
logging.info('running %r', argv)
if stdin_input is not None:
kwargs['stdin'] = subprocess.PIPE
proc = subprocess.Popen(argv, **kwargs)
proc.communicate(input=stdin_input)
if proc.returncode:
... | 5,304,364 |
def above_the_line(x_array, x1, x2):
"""
Return states above a specified line defined by (x1, x2).
We assume that a state has only two coordinates.
Parameters
----------
x_array: `np.array`
A 2-d matrix. Usually, an embedding for data points.
x1: `np.array`
A list or array ... | 5,304,365 |
def run_exec(exec_path,exec_options_list,input_data=None, stdout=None, stderr=None):
"""Basic function to run an executable using `subprocess` (only tested with .exe files).
Parameters
----------
exec_path : str/os.path
path to an executable.
exec_options_list : list
list of option s... | 5,304,366 |
def cel_num_div(cel_mat: Tensor, rc: float) -> Tensor:
"""Number of percel for each direction.
Args:
cel_mat: cell.
rc: cutoff radius.
Returns:
num_div(int[bch, dim]): number of percel for each direction.
"""
num_div = ((cel_mat / rc).norm(p=2, dim=-1) - 1e-4).floor().to(to... | 5,304,367 |
def confusion_samples(prediction, truth, names):
""" Computes the confusion matrix and returns a list with
the TP/FP/TN/FN names
"""
confusion_vector = prediction / truth
# Element-wise division of the 2 tensors returns a new tensor which holds a
# unique value for each case:
# 1 ... | 5,304,368 |
def post_upload_finished(uid):
"""
ask the server to finish the upload
:param uid: upload session ID
:return: status of upload
"""
uploaded = require_integer_array_json_parameter("uploaded")
with slycat.web.server.upload.get_session(uid) as session:
return session.post_upload_finishe... | 5,304,369 |
def info():
"""Returns information about a worker.
Useful for testing that the system is functioning.
Returns
-------
metadata: :class:`dict`
A collection of key-value pairs containing information describing the
local worker.
"""
return buildcat.info() | 5,304,370 |
def parse_xml(path):
""" Returns representation of the root node in the XML file. """
try:
return XMLElement(ET.parse(path).getroot())
except ET.ParseError as e:
raise XMLParseError(str(e)) | 5,304,371 |
def test_process_nontransferable():
"""
Test process of generating and validating key event messages
"""
# Ephemeral (Nontransferable) case
skp0 = Signer(transferable=False) # original signing keypair non transferable
assert skp0.code == MtrDex.Ed25519_Seed
assert skp0.verfer.code == MtrDe... | 5,304,372 |
def fastq_pe_pipeline(project, sample_identifier=None, end_identifier=None):
"""Functional profiling pipeline for entire project
Args:
project (:obj:Project): current project
sample_identifier (str, optional): sample identifier
end_identifier (str, optional): end identifier
"""
... | 5,304,373 |
def lpp_voltage_to_bytes(data):
"""Encode voltage into CayenneLPP and return byte buffer."""
logging.debug("lpp_voltage_to_bytes")
data = __assert_data_tuple(data, 1)
val = data[0]
if val < 0:
logging.error("Negative Voltage value is not allowed")
raise AssertionError("Negative value... | 5,304,374 |
def test_data_path() -> Path:
"""Fixture to Fetch reports for unit testing."""
return repo_path / 'tests' / 'data' | 5,304,375 |
def createSequentialVector(size, vector_type, communicator=None):
"""Create a sequential vector in petsc format.
:param int size: vector size.
:param int vector_type: vector type for parallel computations.
:param str communicator: mpi communicator.
:return: sequential vector.
:rtype: petsc sequ... | 5,304,376 |
def create_gunicorn_worker():
"""
follows the gunicorn application factory pattern, enabling
a quay worker to run as a gunicorn worker thread.
this is useful when utilizing gunicorn's hot reload in local dev.
utilizing this method will enforce a 1:1 quay worker to gunicorn worker ratio.
"""
... | 5,304,377 |
def geth_bare_genesis(genesis_path, private_keys, random_marker):
"""Writes a bare genesis to `genesis_path`.
Args:
genesis_path (str): the path in which the genesis block is written.
private_keys list(str): iterable list of privatekeys whose corresponding accounts will
have... | 5,304,378 |
def downsampler_gpu(input, down_scale, kernel_name='bspline', normalize_kernel=True, a=-0.5, default_pixel_value=0):
"""
Downsampling wiht GPU by an integer scale
:param input: can be a 2D or 3D numpy array or sitk image
:param down_scale: an integer value!
:param kernel_name:
:param normalize_k... | 5,304,379 |
async def test_setup_component_with_config(hass, config_entry):
"""Test setup of the netatmo component with dev account."""
fake_post_hits = 0
async def fake_post(*args, **kwargs):
"""Fake error during requesting backend data."""
nonlocal fake_post_hits
fake_post_hits += 1
r... | 5,304,380 |
def numerical_grad(theta, f, dx=1e-3, order=1):
""" return numerical estimate of the local gradient
The gradient is computer by using the Taylor expansion approximation over
each dimension:
f(t + dt) = f(t) + h df/dt(t) + h^2/2 d^2f/dt^2 + ...
The first order gives then:
df/dt = (f(t +... | 5,304,381 |
def putIterationsPerSec(frame, iterations_per_sec):
"""Add iterations per second text to lower-left corner of a frame."""
cv2.putText(frame,
"{:.0f} iterations/sec".format(iterations_per_sec),
(10, 450),
cv2.FONT_HERSHEY_SIMPLEX,
1.0,
... | 5,304,382 |
def _filter_by_filename(kind, universe, include_files, exclude_files):
"""
Filters out what tests to run solely by filename.
Returns either the set of files from 'universe' that are present in 'include_files', or the
set of files from 'universe' that aren't present in 'exclude_files', depending on whic... | 5,304,383 |
def eqPoints(POINT):
"""
Get point and make all combinations of ones and zeros by addding numbers in binary
"""
zera = np.where(POINT == 0)[0]
ilepow = 2**zera.size
mylist = np.empty((ilepow-1,3))
for n in range(1,ilepow):
val = f"{n:b}"
jkl = zera.size - len(val)
... | 5,304,384 |
def clip(base, color):
"""Gamut clipping."""
channels = util.no_nan(color.coords())
gamut = color._range
fit = []
for i, value in enumerate(channels):
a, b = gamut[i]
is_bound = isinstance(gamut[i], GamutBound)
# Wrap the angle. Not technically out of gamut, but we will cl... | 5,304,385 |
def load(name):
"""The function 'load(filename)' loads prepared data basing on its 'name'
and returns stacked points and the target cluster; this works for 2D data"""
import os
script_dir = os.path.dirname(__file__)
rel_path = name+".txt"
abs_file_path = os.path.join(script_dir, rel_path)
da... | 5,304,386 |
def clustal_omega_alignment(seqrecs, preserve_order=True, **kwargs):
"""Align sequences using Clustal Omega
:param seqrecs: a list or dict of SeqRecord that will be aligned to ref
:param preserve_order: if True, reorder aligned seqrecs to match input order.
:param **kwargs: additional arguments for ali... | 5,304,387 |
def guess_track_title(fname: str) -> typing.Tuple[int, str]:
""" Get the track number and title from a filename """
basename, _ = os.path.splitext(fname)
if match := re.match(r'([0-9]+)([^0-9]*)$', basename):
return int(match.group(1)), match.group(2).strip().title()
return 0, basename.title() | 5,304,388 |
def hass_tz_info(hass):
"""Return timezone info for the hass timezone."""
return dt_util.get_time_zone(hass.config.time_zone) | 5,304,389 |
def _get_lq_l(m: np.ndarray) -> np.ndarray:
""" Calculate L term from LQ decomposition, ensuring the diagonal is non-negative.
Parameters
----------
m
Matrix to process.
Returns the L term in the LQ decomposition, using the convention that all diagonal
elements are non-negative. This i... | 5,304,390 |
def csv_serving_input_fn():
"""Build the serving inputs."""
csv_row = tf.placeholder(shape=[None], dtype=tf.string)
features = _decode_csv(csv_row)
features.pop(constants.LABEL_COLUMN)
return tf.estimator.export.ServingInputReceiver(features,
{'csv... | 5,304,391 |
def test_error_root(caplog):
"""
emits a log with error level into root logger.
"""
caplog.clear()
message = 'this is an error root log.'
caplog.set_level(logging.ERROR)
logging_services.error(message)
assert caplog.records is not None and len(caplog.records) > 0
assert message in c... | 5,304,392 |
def fix_literals(args):
"""make up argument names for literals in call"""
res = args[:]
index = 0
for i, el in enumerate(res):
if not (identifier(el) or keyword_argument(el)):
while f'arg{index}' in res:
index += 1
res[i] = f'arg{index}'
return res | 5,304,393 |
def EVLAUVLoadArch(dataroot, Aname, Aclass, Adisk, Aseq, err, \
selConfig=-1, selBand="", selChan=0, selNIF=0, selChBW=-1.0, \
dropZero=True, calInt=0.5, doSwPwr=False, Compress=False, \
logfile = "", check=False, debug = False):
"""
Read EVLA archive in... | 5,304,394 |
def declarative_base(bind=None, metadata=None, mapper=None, cls=object,
name='Base', constructor=_declarative_constructor,
metaclass=DeclarativeMeta, engine=None):
"""Construct a base class for declarative class definitions.
The new base class will be given a metaclass... | 5,304,395 |
def detect_encoding(bytesobject):
"""Read the first chunk of input and return its encoding"""
# unicode-test
if isutf8(bytesobject):
return 'UTF-8'
# try one of the installed detectors
if cchardet is not None:
guess = cchardet.detect(bytesobject)
LOGGER.debug('guessed encodin... | 5,304,396 |
def test_help():
""" Test object inspection.
"""
f = TestPrefilterFrontEnd()
f.input_buffer += "def f():"
f._on_enter()
f.input_buffer += "'foobar'"
f._on_enter()
f.input_buffer += "pass"
f._on_enter()
f._on_enter()
f.input_buffer += "f?"
f._on_enter()
assert 'traceba... | 5,304,397 |
def drop_subscription(bindable: Bindable, handle: SubscriptionHandle) -> None:
"""Remove a subscription from a bindable."""
(prop_name, handler_id) = handle
handlers = bindable.__coil_bindings__.get(prop_name, [])
handler = next((h for h in handlers if id(h) == handler_id), None)
if handler is not... | 5,304,398 |
def complete_graph(n):
""" returns a complete graph with n vertices
"""
return wgraph_from_adjacency(np.ones((n, n))) | 5,304,399 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.