content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def test_data_filename() -> str:
"""Return filename containing eveuniverse testdata."""
return Path(__file__).parent / "eveuniverse.json" | 5,313,900 |
def sample_run(df, window_size = 500, com = 12):
"""
This functions expects a dataframe df as mandatory argument.
The first column of the df should contain timestamps, the second machine IDs
Keyword arguments:
n_machines_test: the number of machines to include in the sample
ts_per_machine... | 5,313,901 |
def MRBL (cases, layersize):
"""
* Maximal Rectangles Bottom Left *
Similar to the guilliotine, but every time a new case is placed, no cut is made, both
newly generated spaces are kept in memory. This introduce the necessity to make some
additional controls on overlaps an... | 5,313,902 |
def test_kill():
""" KILL command """
assert like("KILL WiZ :Spamming joins", pack_command(
"KILL", nick="WiZ", message="Spamming joins")) | 5,313,903 |
def main():
"""
Main function that calls all the other functions and classes when the user inputs commands via terminal
This program is meant to recognize multiple faces but has some added features such as a symmetry test
Refer to the conditional statements below to see which commands are acceptable.
... | 5,313,904 |
def test_pex_repl_cli():
"""Tests the REPL in the context of the pex cli itself."""
stdin_payload = b'import sys; sys.exit(3)'
with temporary_dir() as output_dir:
# Create a temporary pex containing just `requests` with no entrypoint.
pex_path = os.path.join(output_dir, 'pex.pex')
results = run_pex_c... | 5,313,905 |
def test_repr_(value, expected):
"""Confirm value types are represented correctly in the TOML output."""
assert fru.toml_format.repr_(value) == expected | 5,313,906 |
def zenodo_records_json():
"""Load JSON content from Zenodo records file."""
data = None
with open(join_path(TEST_DIR, 'data/zenodo_records.json'), 'r') as f:
data = f.read()
return data | 5,313,907 |
def set_season():
"""
Facilitates the user entering what season it is. Returns the appropriate
string.
"""
error = False
while True:
clear_screen()
options = ["Spring", "Summer", "Fall"]
print("What season is it?")
# Prints out the options array in a numbered fas... | 5,313,908 |
def extract_rooms_or_global(req, admin=True):
"""
Extracts the rooms / global parameters from the request body checking them for validity and
expanding them as appropriate.
Throws a flask abort on failure, returns (rooms, global) which will be either ([list of Rooms],
None) for a room operation or ... | 5,313,909 |
def info(msg):
"""
Informational logging statement
:param msg: the message to print
:returns: True -- to allow it as an #assert statement
"""
return log("info", msg, logger) | 5,313,910 |
def error_correct_BC_or_UMI(records, key, threshold=1):
"""
:param records: should be list of records all from the same gene!
"""
assert key in ('BC', 'UMI')
merge_map = {}
bc_count = Counter()
for r in records: bc_count[r[key]] += 1
# most common BC, in decreasing order
bc_sorted =... | 5,313,911 |
def setJointParent(child, parent):
"""
Parent the given `child` joint to `parent`. Handles parenting the joint
directly rather than inserting a buffer transform.
Args:
child: A joint to be parented
parent: A joint to be the new parent of child
"""
pm.parent(child, parent, a=True... | 5,313,912 |
def add_category():
"""
Create category for database.
Inject all form data to new category document on submit.
"""
all_plant_types = mongo.db.plant_types.find()
all_shade_tolerance = mongo.db.shade_tolerance.find()
return render_template('addcategory.html',
... | 5,313,913 |
def load_seed_from_file(seed_path):
"""Load urls seed from file"""
seed_urls = urls.load_urls_from_file(seed_path)
return seed_urls | 5,313,914 |
def loads(csvdoc, columns=None, cls=Row, delimiter=",", quotechar='"',
typetransfer=False, csv_size_max=None, newline="\n"):
"""Loads csv, but as a python string
Note: Due to way python's internal csv library works, identical headers will overwrite each other.
"""
return _loads(csvdoc, co... | 5,313,915 |
def main():
"""
Main program.
"""
global ERROR # prevent local creation of variable
global VERBOSE # prevent local creation of variable
global GEN_TEST_CODE # indicate if test code should be generated
global DEPLOYMENT # deployment set in topology xml only and used to install new instanc... | 5,313,916 |
def cluster_association_test(res, y_col='cmember', method='fishers'):
"""Use output of cluster tallies to test for enrichment of traits within a cluster.
Use Fisher's exact test (test='fishers') to detect enrichment/association of the neighborhood
with one variable.
Tests the 2 x 2 table for each clon... | 5,313,917 |
def enable_caching(cache_dir = None):
"""Enables caching request-wide for all cachable calls.
* cache_dir: A directory path to use to store the caching data. Set to None to use a temporary directory.
"""
global __cache_dir
global __cache_enabled
if cache_dir == None:
import tempfile
__cache_dir = tempfile... | 5,313,918 |
def test_copy_tree(tmp_path):
"""Test the ``Repository.copy_tree`` method."""
node = Data()
node.put_object_from_filelike(io.BytesIO(b'content'), 'relative/path')
node.copy_tree(tmp_path)
dirpath = pathlib.Path(tmp_path / 'relative')
filepath = dirpath / 'path'
assert dirpath.is_dir()
a... | 5,313,919 |
def SetOutputFileNames(file_name, apps, output_dir):
"""Sets the output file names inside the Application.
Args:
file_name: The input file name that needs to be stamped. This
is used for deciding whether to use TEST in the name,
and the directory. The names of this file is expecte... | 5,313,920 |
def main():
"""
Create the output folder for each of the conversion types.
"""
for xsl_file_name, output_folder, checker in CONVERSIONS:
# Get the conversion output folder.
output_path = os.path.join(OUTPUT_PATH, output_folder)
if os.path.exists(output_path):
logger.info('%s already exists.', output_path... | 5,313,921 |
def parse_collection_page(wikitext):
"""Parse wikitext of a MediaWiki collection page created by the Collection
extension for MediaWiki.
@param wikitext: wikitext of a MediaWiki collection page
@type mwcollection: unicode
@returns: metabook.collection
@rtype: metabook.collection
""... | 5,313,922 |
def test_get_singular_alias() -> None:
"""Test get_singular_alias function."""
assert ModelUtils.get_singular_alias(alias_path='catalog') == 'catalog'
# Not fullpath. It should be 'catalog.metadata' instead
with pytest.raises(TrestleError):
ModelUtils.get_singular_alias(alias_path='metadata.som... | 5,313,923 |
def get_track_info(srcpath, job):
"""Use HandBrake to get track info and updatte Track class\n
srcpath = Path to disc\n
job = Job instance\n
"""
charset_found = False
logging.info("Using HandBrake to get information on all the tracks on the disc. This will take a few minutes...")
cmd = '{... | 5,313,924 |
def _ensure_hms(inner_result: ParsedDate, remain_tokens: List[str]) -> ParsedDate:
"""
This function extract value of hour, minute, second
Parameters
----------
inner_result
already generated year, month, day value
remain_tokens
remained tokens used for generating hour, minute, s... | 5,313,925 |
def create_app(config=Config):
"""App factory."""
app = Flask(__name__)
app.config.from_object(config)
db.init_app(app)
migrate.init_app(app, db)
bcrypt.init_app(app)
login_manager.init_app(app)
from . import auth, tally
app.register_blueprint(auth.bp)
app.register_blueprint(t... | 5,313,926 |
def helper(n, largest_digit):
"""
:param n: int, a number
:param largest_digit: int,
:return: int, the largest digit
"""
if n == 0: # base case
return largest_digit
else:
if n < 0: # convert negative n into positive if any
n = n * -1
if n % 10 > largest_digit:
largest_digit = n % 10
return help... | 5,313,927 |
def peak_compare_data(request, peak_compare_list):
"""
:param request: Request for the peak data for the Peak Explorer page
:return: The cached url of the ajax data for the peak data table.
"""
analysis = Analysis.objects.get(name='Tissue Comparisons')
if peak_compare_list == "All":
pe... | 5,313,928 |
def _generic_filtering_element(F, Q, H, R, y):
"""
Equation 10 in "GPR in Logarithmic Time"
"""
S = H @ (Q @ H.T) + R
chol = cho_factor(S)
Kt = cho_solve(chol, H @ Q)
A = F - (Kt.T @ H) @ F
b= Kt.T @ y
C = Q - (Kt.T @ H) @ Q
HF = H @ F
eta = HF.T @ np.squeeze(cho_solve(ch... | 5,313,929 |
def main(argv=sys.argv[1:]):
"""Main script function.
Calls run method of selected sub commandos.
Args:
argv (list[str]): List of command line arguments
"""
parser = make_parser()
args = parser.parse_args(argv)
fargs = vars(args)
if 'func' in fargs:
func = args.func
... | 5,313,930 |
def _run_app_thread(server: webserver.WebServer, port: int):
"""Run the webserver in a separate thread.
Args:
server (webserver.WebServer):
Required. A webserver to accept requests.
port (int):
Required. The port to run the webserver on.
"""
daemon = threading.Th... | 5,313,931 |
def packdb(name, packs, visibility):
"""Pack database rule.
Args:
name: Name of the library.
packs: List of packs to include.
visibility: Sets the visibility in the py_library rule.
"""
modules = [
p.replace("//", "/").replace("/", ".").replace(":", ".")
for p in... | 5,313,932 |
def getStrFromAngles(angles):
"""
Converts all angles of a JointState() to a printable string
:param angles (sensor_msgs.msg.JointState): JointState() angles to be converted
:return (string): string of the angles
"""
d=getDictFromAngles(angles)
return str( dict(d.items())) | 5,313,933 |
def test_common_ledger_items(session):
"""Assert that common ledger items works as expected."""
identifier = 'BC1234567'
founding_date = datetime.utcnow() - datedelta.datedelta(months=len(Filing.FILINGS.keys()))
business = factory_business(identifier=identifier, founding_date=founding_date, last_ar_date... | 5,313,934 |
def jit_user_function(func: Callable, nopython: bool, nogil: bool, parallel: bool):
"""
JIT the user's function given the configurable arguments.
"""
numba = import_optional_dependency("numba")
if isinstance(func, numba.targets.registry.CPUDispatcher):
# Don't jit a user passed jitted funct... | 5,313,935 |
def aggregate_on_dns(ip_values, ip_fqdns, is_numeric=True):
"""
Aggregates the values in ip_values based on domains accessed from
ip_fqdns. Values from same ip_addresses same domain names are combines
Args:
ip_values (dictionary): maps ip address to some computed value
... | 5,313,936 |
def create_load_balance(vlb_name, pools, vnet_id, listeners, vlb_desc, is_table, wait):
"""Create load balance by name
:param vlb_name: Enter Load Balancer name
:type vlb_name: string
"""
if not name_validator(vlb_name):
raise ValueError(
"Name '{0}' is not valid. '^[a-z][a-z-_0... | 5,313,937 |
def check_string_length(value, name, min_length=0, max_length=None,
allow_all_spaces=True):
"""Check the length of specified string.
:param value: the value of the string
:param name: the name of the string
:param min_length: the min_length of the string
:param max_length: t... | 5,313,938 |
def get_users():
"""
Fetch a dictionary of username and their IDs from Slack
"""
slack_api_client = connect()
api_call = slack_api_client.api_call('users.list')
if api_call.get('ok'):
user_list = dict([(x['name'], x['id']) for x in api_call['members']])
return user_list
else:
print 'Error Fetching Users'
... | 5,313,939 |
def topological_sort(graph):
# type: Dict[str, List[str]] -> Optional[List[Tuple[Union[str, int]]]]
"""Return linear ordering of the vertices of a directed graph.
https://leetcode.com/problems/course-schedule (analogous)
"""
result = []
counter = len(graph)
# Select random node
node = ... | 5,313,940 |
def lower_bound(expressions):
"""Creates an `Expression` lower bounding the given expressions.
This function introduces a slack variable, and adds constraints forcing this
variable to lower bound all elements of the given expression list. It then
returns the slack variable.
If you're going to be lower-bound... | 5,313,941 |
def get_tensorboard_args(tb_version: str, tfevents_dir: str, add_args: List[str]) -> List[str]:
"""Build tensorboard startup args.
Args are added and deprecated at the mercy of tensorboard; all of the below are necessary to
support versions 1.14, 2.4, and 2.5
- Tensorboard 2+ no longer exposes all por... | 5,313,942 |
def do_to_networkx(do):
"""Return a networkx representation of do"""
terms = do.get_terms()
dox = networkx.MultiDiGraph()
dox.add_nodes_from(term for term in terms if not term.obsolete)
for term in dox:
for typedef, id_, name in term.relationships:
dox.add_edge(term, do.get_term(... | 5,313,943 |
def resolve_executable(name_variants: List[str], env_override: Optional[str] = None) -> str:
"""Resolve platform-specific path to given executable.
Args:
name_variants: List of executable names to look for.
env_override: Environment variable name to use as override if available.
Returns:
... | 5,313,944 |
def _prepare_data(data):
"""Takes the raw data from the database and prepares it for a sklearn workflow"""
# Get the number of turbines
n_turb = data[0]["lat"].size
# Split the data into the prediction and learning sets
data_learn = [d for d in data if not np.isnan(d["power"])]
data_new = [d fo... | 5,313,945 |
def parse_gset_format(filename):
""" parse gset format """
# pylint: disable=import-outside-toplevel
from .common import parse_gset_format as redirect_func
warnings.warn("parse_gset_format function has been moved to "
"qiskit.optimization.ising.common, "
"the method h... | 5,313,946 |
def get_sentence_ngrams(
mention: Union[Candidate, Mention, TemporarySpanMention],
attrib: str = "words",
n_min: int = 1,
n_max: int = 1,
lower: bool = True,
) -> Iterator[str]:
"""Get the ngrams that are in the Sentence of the given Mention, not including itself.
Note that if a candidate i... | 5,313,947 |
def find_largest(line: str) -> int:
"""Return the largest value in line, which is a whitespace-delimited string
of integers that each end with a '.'.
>>> find_largest('1. 3. 2. 5. 2.')
5
"""
# The largest value seen so far.
largest = -1
for value in line.split():
# Remove the tra... | 5,313,948 |
def get_arch(bv):
"""Arch class that gives access to architecture-specific functionality."""
name = bv.arch.name
if name == "x86_64":
return AMD64Arch()
elif name == "x86":
return X86Arch()
elif name == "aarch64":
return AArch64Arch()
else:
raise UnhandledArchitec... | 5,313,949 |
def magic_auth(request, magic_token=None):
"""
"""
if request.method == 'POST':
# Validate form
magic_auth_form = MagicAuthForm(request.POST)
if magic_auth_form.is_valid():
# Try to find the user or create a new one
try:
user = User.objects.get... | 5,313,950 |
def _volume_1_atm(_T, ranged=True):
"""m**3 / mol"""
return 1 / _ro_one_atm(_T, ranged) | 5,313,951 |
def isAmdDevice(device):
""" Return whether the specified device is an AMD device or not
Parameters:
device -- DRM device identifier
"""
vid = getSysfsValue(device, 'vendor')
if vid == '0x1002':
return True
return False | 5,313,952 |
def pre_sif_mean_inner(mat, freqs, a, dtype=None):
"""
From *A Simple but Tough-to-Beat Baseline for Sentence Embeddings*
https://openreview.net/forum?id=SyK00v5xx
https://github.com/PrincetonML/SIF
"""
# 1. Normalize
mat = normalize(mat)
# 2. Reweight
rows, cols = mat.shape
for ... | 5,313,953 |
def v1() -> Response:
"""
Handle Endpoint: /a2j/v1/
:return: HTTP Response.
:rtype: Response
"""
return Response(json.dumps({
"endpoints": ["parse", "clean"]
}), mimetype="application/json") | 5,313,954 |
def apply_phase(signal, phase, frequency, fs):
"""Apply phase fluctuations.
:param signal: Pressure signal.
:param phase: Phase fluctuations.
:param frequency: Frequency of tone.
:param fs: Sample frequency.
Phase fluctuations are applied through a resampling.
"""
delay = delay_fluctu... | 5,313,955 |
def MissingDependencyError(Exception):
"""Optional dependency not available."""
pass | 5,313,956 |
def generate_tiles(w, h, f):
"""
Generates 2**f tiles for the given rectangle
@param w: int
@param h: int
@param f: int
@return: list
"""
x_step, y_step = w, h
for i in range(0, f):
if i % 2:
y_step /= 2
else:
x_step /= 2
y_min, y_max = 0,... | 5,313,957 |
def __load_aug_img__(path, img_size, img_aug):
"""
"""
img = image.img_to_array(image.load_img(path, target_size=img_size))
if img_aug is not None:
img = img_aug.random_transform(img)
return img | 5,313,958 |
def print_corr3_params():
"""Print information about the valid parameters that may be given to the `corr3` function.
"""
treecorr.config.print_params(corr3_valid_params) | 5,313,959 |
def _shot_id_to_int(shot_id):
"""
Returns: shot id to integer
"""
tokens = shot_id.split(".")
return int(tokens[0]) | 5,313,960 |
def get_native_pointer_type(pointer_size: int):
"""
:return: A type that can represent a pointer.
"""
return {
ctypes.sizeof(ctypes.c_uint32): ctypes.c_uint32,
ctypes.sizeof(ctypes.c_uint64): ctypes.c_uint64,
}[pointer_size] | 5,313,961 |
def get_bootinfo():
"""build and return boot info"""
vmraid.set_user_lang(vmraid.session.user)
bootinfo = vmraid._dict()
hooks = vmraid.get_hooks()
doclist = []
# user
get_user(bootinfo)
# system info
bootinfo.sitename = vmraid.local.site
bootinfo.sysdefaults = vmraid.defaults.get_defaults()
bootinfo.serve... | 5,313,962 |
def monkey_all_handler():
"""
@api {get} /v1/monkey/all 查询 Monkey 测试列表
@apiName GetMonkeyAll
@apiGroup 自动化测试
@apiDescription 查询 所有的 monkey 测试信息
@apiParam {int} [page_size] 分页-单页数目
@apiParam {int} [page_index] 分页-页数
@apiParam {int} [user_id] 用户 ID,获取当前用户 ID 的 monkey 测试信息
@apiParam {in... | 5,313,963 |
def get_all_schedules(db_cur, server_id, is_async):
"""Extract all candidate schedules for a server
+--------- minute (0 - 59)
| +--------- hour (0 - 23)
| | +--------- day of the month (1 - 31)
| | | +--------- month (1 - 12)
| | | | +--------- day of the week (0 - 7) (Sunday to Saturday; 7 is ... | 5,313,964 |
def predicted_win(board: Board, draws: list[int]) -> Prediction:
"""
Goes through the drawn numbers and returns a Prediction, which is a tuple of
two numbers:
- the turn on which the board wins
- the score of the board at that moment
"""
lines = board_lines(board)
for i, draw in enumerat... | 5,313,965 |
def quantity_data_frame(bundle: Union[InstanceBundle, Sequence[InstanceBundle]],
quantity_name: str,
us: Optional[Iterable[float]] = None,
steps: Optional[Iterable[int]] = None,
simulated: bool = False
... | 5,313,966 |
def trim_name(names: Union[List[str], str]) -> Union[List[str], str]:
"""Trims the name from the web API, specifically from IFTTT (removes extra "the ")"""
# Single name
if isinstance(names, str):
trimmed_name = names.lower().replace("the", "").strip()
return trimmed_name
elif isinstanc... | 5,313,967 |
def concat(*streams, **kwargs):
"""Concatenate audio and video streams, joining them together one after the other.
The filter works on segments of synchronized video and audio streams. All segments
must have the same number of streams of each type, and that will also be the number
of streams at output.... | 5,313,968 |
def error_logger(error, project_id):
"""Creates database entries for failed / erroneous runs"""
ExecutionStats.objects.create(
project_id = project_id,
exec_date = datetime.datetime.now(),
exec_status = 'FAIL',
fail_reason = error
) | 5,313,969 |
def get_variants_from_sites_vcf(sites_vcf):
"""
Parse sites VCF file and return iter of variant dicts
sites_vcf is a file (gzipped), not file path
"""
vep_field_names = None
for line in sites_vcf:
try:
line = line.strip('\n')
# if line.startswith('##INFO=<ID=CSQ'):... | 5,313,970 |
def ping_thread(ws):
"""
A thread to ping the server every 25 secs to keep the connection alive
"""
print("Started pinging")
while True:
ws.send("2")
sleep(25) | 5,313,971 |
def proj(ax,s,ds,
axis='z',title='',vmin=1e0,vmax=1e3,dat=xr.Dataset(),**kwargs):
"""Draw projection plot at given snapshot number
Args:
ax: axes to draw.
s: LoadSim object.
ds: AthenaDataSet object.
axis: axis to project (default:'z').
title: axes title (defaul... | 5,313,972 |
def printProgressBar(
iteration,
total,
prefix='',
suffix='',
decimals=1,
length=100,
fill='█'):
"""
Call in a loop to create terminal progress bar
@params:
iteration - Required : current iteration (Int)
total - Required : tot... | 5,313,973 |
def print_object_dict_as_df(object_dict_form):
"""
instead of using pprint, uses pandas dataframe to better display content of object dictionary form
:param object_dict_form:
:return:
"""
from copy import deepcopy
pd.set_option("max_rows", None)
xdict = deepcopy(object_dict_form)
... | 5,313,974 |
async def fetch_network_node_health(
network_name: str,
time_s: int,
interval_s: int,
node_stats: Dict,
session: aiohttp.ClientSession,
) -> None:
"""Fetch health metric for all nodes from network test service."""
try:
url = f"{environ.get('NETWORK_TEST_URL', 'http://network_test:808... | 5,313,975 |
def get_ingress_address(endpoint_name):
"""Returns an ingress-address belonging to the named endpoint, if
available. Falls back to private-address if necessary."""
return get_ingress_addresses(endpoint_name)[0] | 5,313,976 |
async def test_2():
"""
Add two chains
"""
application = Application()
context = await application.add_context()
track = await context.add_track()
rack_device = await track.add_device(RackDevice)
chain_one = await rack_device.add_chain()
chain_two = await rack_device.add_chain()
... | 5,313,977 |
def evaluate_sfp(logits_cls, labels, flag):
""" evaluate same family prediction """
result = {}
result["n"] = len(logits_cls)
result["avg_loss"] = F.binary_cross_entropy_with_logits(logits_cls, labels.float())
if flag["acc"]:
samefamily_hat = logits_cls > 0.5
result["correct"] = to... | 5,313,978 |
def function():
"""Function docstring
"""
pass | 5,313,979 |
def test_fix_access_researcher_not_allowed(client):
"""Researcher cannot give access."""
response = client.post(
tests.DDSEndpoint.PROJECT_ACCESS,
headers=tests.UserAuth(tests.USER_CREDENTIALS["researchuser"]).token(client),
)
assert response.status_code == http.HTTPStatus.FORBIDDEN | 5,313,980 |
def soft_assert_mentioning_format_in_comment(
comments_panel, soft_assert, email
):
"""Soft assert mentioned email appears in comment with '+' sign before it
and it is a link.
"""
soft_assert.expect(comments_panel.scopes[0].get('description') ==
str_formats.MENTIONED_EMAIL.format(email=... | 5,313,981 |
def round(x):
"""Round tensor to nearest integer. Rounds half to even. """
return np.round(x) | 5,313,982 |
def regnet_y_8gf(
pretrained: bool = False, progress: bool = True, **kwargs: Any
) -> RegNet:
"""
Constructs a RegNetY-8GF architecture from
`"Designing Network Design Spaces" <https://arxiv.org/abs/2003.13678>`_.
Args:
pretrained (bool): If True, returns a model pre-trained on ImageNet... | 5,313,983 |
def write_config(filename: str, args: dict):
""" Write a dictionary to a .yml file"""
with open(filename, 'w') as file:
documents = dump(args, file) | 5,313,984 |
def fit_single_univariate_sample(samples):
""" Fit a univariate gaussian model based on the samples given """
gaussian = UnivariateGaussian()
return gaussian.fit(samples) | 5,313,985 |
def get_durations_from_alignment(batch_alignments, mels, phonemes, weighted=False, binary=False, fill_gaps=False,
fix_jumps=False, fill_mode='max'):
"""
:param batch_alignments: attention weights from autoregressive model.
:param mels: mel spectrograms.
:param phone... | 5,313,986 |
def summarize_preds_token_max(document):
"""Summarize Token predictions using the maximum value."""
for sentence in document.sentences:
for word in sentence.words:
for token in word.tokens:
probs = np.stack([p[1] for p in token.predictions])
token.pred_summary... | 5,313,987 |
def argparser_course_required_wrapper(with_argparser):
"""
When applied to a do_x function in the Clanvas class that takes in argparser opts,
will convert/replace course attribute with a corresponding course object either
using the course string as a query or the current (cc'd) course if not supplied.
... | 5,313,988 |
def read_csv_and_filter_prediction_target(csv: Path, prediction_target: str,
crossval_split_index: Optional[int] = None,
data_split: Optional[ModelExecutionMode] = None,
epoch: Optional[int] = N... | 5,313,989 |
def compare(Target, Population):
"""
This function takes in two picture objects and compares them.
:param Target: target image
:type Target: Picture object
:param Population: The population of the current generations
:type Population: A list of picture objects
:return: Two best members of... | 5,313,990 |
def test_get_filenames_with_attachments_data(
signal_notification_service: SignalNotificationService,
) -> None:
"""Test getting filenames with 'attachments' in data."""
data = {"attachments": ["test"]}
result = signal_notification_service.get_filenames(data)
assert result == ["test"] | 5,313,991 |
def test_mean_group_min_count():
"""Test mean for groups in df, normalising by a minimum valuee"""
df = pd.DataFrame({"idx": [1, 1, 1, 1, 2, 2], "value": [1, 1, 1, 1, 2, 2]})
mean_1 = mean_group_min_count(df, "idx", "value", min_count=1)
assert mean_1.loc[1] == 1
assert mean_1.loc[2] == 2
mean... | 5,313,992 |
def normalize_AE_state(states, noSOC=True): # return normalized states for AE (no pred, soc)
"""
:param states: (9, seq, 27)
:return: (9, seq, 19)
"""
state_list = np.split(states, SPLIT_IDX, -1)
result_list = []
for state, func in zip(state_list, func_callbacks):
result_list.append... | 5,313,993 |
def one_set_logistic(input_pars, file='', N=10, S=None):
""" Generates N time series of logistic systems according to input parameters and writes summary
of the statistics of time series to file."""
width_growth, noise = input_pars
line_stat = ''
for k in range(N):
# Set parameters.
... | 5,313,994 |
def test_1_5_aromatic_heteroatom_canonicalization():
"""1,5 aromatic heteroatom H shift"""
assert canonicalize_tautomer_smiles('Oc1cccc2ccncc12') == 'Oc1cccc2ccncc12' | 5,313,995 |
def load(image_file):
"""Load the image from file path."""
image = tf.io.read_file(image_file)
image = tf.image.decode_jpeg(image)
width = tf.shape(image)[1]
width = width // 2
real_image = image[:, :width, :]
input_image = image[:, width:, :]
input_image = tf.cast(input_image, tf.flo... | 5,313,996 |
def get_corpus_directory():
"""Return path of Data/Corpus directory"""
data_directory = get_data_directory()
corpus_directory = data_directory / "Corpus"
return corpus_directory | 5,313,997 |
def reconstruction(freq, nfreq, A, d, damping='hysteretic', type='a', residues=False, LR=0, UR=0):
"""generates a FRF from modal parameters.
There is option to consider the upper and lower residues (Ewins, D.J.
and Gleeson, P. T.: A method for modal identification of lightly
damped structures)
... | 5,313,998 |
def main(python_file: "Path", notebook: "Path", notebook_info: NotebookInfo) -> None:
"""
Replace :code:`source` code cells of original notebook.
Parameters
----------
python_file
Temporary Python file notebook was converted to.
notebook
Jupyter Notebook third-party tool is run ... | 5,313,999 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.