content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def update_exception_behavior(behavior_input, id):
"""
Executes a "update exception behavior" mutation with graphql-client
:param behavior_input: the behavior input
:param id: The id of the behavior to update
:return: Server response
"""
behavior_variables = {
"behaviorInput": behavi... | 50,500 |
def ps_dim(tasks):
"""
Dimension a Polling Server such that it fits into the provided task set.
Parameters
----------
tasks : list of pSyCH.tasks.Periodic
Task set whose schedulability is to be checked.
Returns
-------
sched : bool
True if the task set is schedulable, F... | 50,501 |
def signature(obj, *, follow_wrapped=True):
"""Get a signature object for the passed callable."""
return Signature.from_callable(obj, follow_wrapped=follow_wrapped) | 50,502 |
def ingest_epv_into_graph(epv_details):
"""Handle implementation of API for triggering ingestion flow.
:param epv_details: A dictionary object having list of packages/version as a nested object.
Ex:
{
"ecosystem": "<ecosystem_name>", (*required)
"packages": [
{
... | 50,503 |
def create_sys(Model, size, epsi, dens, init, bd_cond='periodic'):
"""Creates a instance of the LdftModel `Model` under the parameters `size`,
`epsi`, `dens`. The `init`-parameter determines the initial density profile
of the created system.
Parameters
----------
Model : `class`
The... | 50,504 |
def CItest(df,alpha):
""" test whether the lower range of CI is larger than 0 or not"""
ci = norm(*norm.fit(df['ED'])).interval(alpha)
print(ci)
if ci[0] < 0:
print(str(alpha*100)+"%","Confidence: ED not significantly different from 0")
else:
print(str(alpha*100)+"%","Confidence: ED ... | 50,505 |
def predict_house_values(n, feature, label):
"""Predict house values based on a feature."""
batch = training_df[feature][10000:10000 + n]
predicted_values = my_model.predict_on_batch(x=batch)
print("feature label predicted")
print(" value value value")
print(" i... | 50,506 |
def limit(resource, value):
"""
Check if this is a valid limit for the number of matching resources to be specified.
:param resource:
:type resource:
:param value: specified limit
:type value: int
:return: True if valid limit, False otherwise
:rtype: bool
"""
return value > 0 | 50,507 |
def sequence(values, rasts):
"""
Iterates through a sequence of linearly interpolated rasters.
Args:
values:
The unknown values for which new rasters will be interpolated and returned.
rasts:
A dictionary of the known values and rasters between which the interpolated... | 50,508 |
def is_native_xmon_op(op: cirq.Operation) -> bool:
"""Check if the gate corresponding to an operation is a native xmon gate.
Args:
op: Input operation.
Returns:
True if the operation is native to the xmon, false otherwise.
"""
return isinstance(op, cirq.GateOperation) and is_native... | 50,509 |
def mono_extractor(b_format, azis=None, eles=None, mode='beam'):
"""
:param b_format: (frames, channels) IN SN3D
:param mode: 'beamforming' or 'omni'
:return:
"""
frames, channels = b_format.shape
x = np.zeros(frames)
if mode == 'beam':
# MaxRE decoding
b_format_n... | 50,510 |
def get_ranking_order_switches(list):
"""list has to be list of quadruples (obs_id, sent_id, score, rank) output from get_ranks function
as in Ranking-Based Evaluation of Regression Models, Rosset et al."""
ranking_order_switches=0
#itearte over list, get observation i
n = len(list)
for i ... | 50,511 |
def b58_to_bytes(val: str) -> bytes:
"""
Convert a base 58 string to bytes
"""
return base58.b58decode(val) | 50,512 |
def generate_sphere(phi, theta, r):
"""
Generate points for structured grid for a spherical shell volume.
This method is useful for generating a structured cylindrical mesh for VTK.
:param phi: azimuthal angle array
:param theta: polar angle array
:param r: radius of sphere
:return: grid poi... | 50,513 |
def get_target_langs(request):
"""
Get Target Languages for a CI Pipeline
:param request: Request object
:return: HttpResponse object
"""
if not request.is_ajax():
return HttpResponse("Not an Ajax Call", status=400)
post_params = request.POST.dict()
ci_pipeline = post_params.get... | 50,514 |
def _reciprocal_calculate(a): # pragma: no cover
"""
TODO: Replace this with more efficient algorithm
From Fermat's Little Theorem:
a^(p^m - 1) = 1 (mod p^m), for a in GF(p^m)
a * a^-1 = 1
a * a^-1 = a^(p^m - 1)
a^-1 = a^(p^m - 2)
"""
if a == 0:
raise ZeroDivisionError... | 50,515 |
def page_list_return(total, current=1):
"""
page
分页,返回本次分页的最小页数到最大页数列表
"""
min_page = current - 4 if current - 6 > 0 else 1
max_page = min_page + 6 if min_page + 6 < total else total
return range(min_page, max_page + 1) | 50,516 |
def get_compatibility_tags(filename):
"""Get the python version and os architecture to check against.
Args:
filename (str): Wheel filename that ends in .whl or sdist filename that ends with .tar.gz.
Returns:
pyver (str)['py3']: Python version of the library py3 or cp38 ...
abi (str... | 50,517 |
def brokerStatsRecord(mrktSym, cost_share, profLossShare, profit_Loss, quantity, price, postionDollarVal,
dayChange, cost, profitLossPercent):
"""
Creates a record for the broker Statistics
table in persistent storage.
:param: mrktSym: String
:param: cost_share: float
:para... | 50,518 |
def _plot_field_layout(X, Y, Z, L_min):
"""Plot field layout."""
# Collector heights is illustrated with colors from a colormap
norm = mcolors.Normalize(vmin=min(Z)-0.000001, vmax=max(Z)+0.000001)
# 0.000001 is added/subtracted for the limits in order for the colormap
# to correctly display the midd... | 50,519 |
def recv_msg():
"""Receive a message from the extension."""
# Each message is serialized using JSON, UTF-8 encoded and is preceded with
# 32-bit message length in native byte order.
# Read the message length (first 4 bytes).
length_bytes = sys.stdin.read(4)
if len(length_bytes) < 4:
rais... | 50,520 |
def test_agg_friction(gid):
"""Test SC Aggregation with friction by checking friction factors and LCOE
against a hand calc."""
warnings.filterwarnings('ignore')
for gid in [100, 114, 130, 181]:
s = SupplyCurveAggregation.summary(EXCL_FPATH, GEN, TM_DSET,
... | 50,521 |
async def test_catch_request_error_unavailable(
device_source_mock: DmsDeviceSource,
) -> None:
"""Test the device is checked for availability before trying requests."""
device_source_mock._device = None
with pytest.raises(DeviceConnectionError):
await device_source_mock.async_resolve_object("i... | 50,522 |
def get_deployment_dates(site, node, sensor, deploy):
"""
Based on the site, node and sensor names and the deployment number, determine the start and end times for a
deployment.
:param site: Site name to query
:param node: Node name to query
:param sensor: Sensor name to query
:param deploy... | 50,523 |
def delete_documents_by_filter(filters: FilterRequest):
"""
Can be used to delete documents from a document store.
:param filters: Filters to narrow down the documents to delete.
Example: '{"filters": {{"name": ["some", "more"], "category": ["only_one"]}}'
To delete ... | 50,524 |
def jpgs_in_dir(dir):
"""
(provided, DO NOT MODIFY)
Given the name of a directory, returns a list of the .jpg filenames
within it.
Input:
dir (string): name of directory
Returns:
filenames(List[string]): names of jpg files in directory
"""
filenames = []
for filename... | 50,525 |
def ensure_credential_server_running( foreground=False, run_once=False ):
"""
Instantiate our credential server and keep it running.
"""
# is the watchdog running?
pids = syndicate_watchdog.find_by_attrs( "syndicate-credential-server-watchdog", {} )
if len(pids) > 0:
# it's running
ret... | 50,526 |
def main():
"""
Run DARC Master
"""
parser = argparse.ArgumentParser(description="DARC master service")
parser.add_argument('--config', default=CONFIG_FILE, help="Path to config file, loaded from $HOME/darc/config.yaml "
"if it exists, el... | 50,527 |
def test_create_plotmon_from_historical(tmp_test_data_dir):
"""
Test for creating a plotmon based on a provided tuid
"""
set_datadir(tmp_test_data_dir)
tuid = "20200504-191556-002-4209ee"
plotmon = create_plotmon_from_historical(tuid)
curves_dict = plotmon._get_curves_config()
x = curv... | 50,528 |
def load_dbc(folder, verbose=True):
"""
Load all dbc files from specified folder add to dbc database.
Parameters
----------
folder : str
Absolute or relative path to folder, which contains dbc files.
verbose : bool, optional
Set to False to have no readout. The default is True.
... | 50,529 |
def unique_timestamps(data):
"""
Identify unique timestamps in a dataframe
:param data: dataframe. The 'Time' column is used by default
:returns: returns a sorted numpy array
"""
unique_timestamps = sorted(data['Time'].unique())
return unique_timestamps | 50,530 |
def printf_format_for_type(t, types):
""" Returns a format string for printing the given type
(either atomic or struct). """
description = type_description(t, types)
if "struct" in description:
specifer = printf_format_for_struct(t, types)
else:
specifer = description["printf_specifi... | 50,531 |
def get_operator_artifact_type(operatorArtifactString):
"""get_operator_artifact_type takes a yaml string and determines if it is
one of the expected bundle types.
:param operatorArtifactString: Yaml string to type check
"""
# Default to unknown file unless identified
artifact_type = UNKNOWN_F... | 50,532 |
def is_occ_conflict_exception(e):
"""
Is the exception an OccConflictException?
:type e: :py:class:`botocore.exceptions.ClientError`
:param e: The ClientError caught.
:rtype: bool
:return: True if the exception is an OccConflictException. False otherwise.
"""
is_occ = e.response['Error... | 50,533 |
def summariseTests(tests):
"""
Iterates through a list of GPUVerifyTestKernel objects and prints out a summary
"""
OpenCLCounter=0
CUDACounter=0
passCounter=0
failCounter=0
xfailCounter=0
skipCounter=0
for test in tests:
#Record kernel type
if test.path.ends... | 50,534 |
def replace_list_element(l, before, after):
"""Helper function for get_cluster_idx
"""
for i, e in enumerate(l):
if e == before:
l[i] = after
return l | 50,535 |
def _verify_tf_cond_branch_vars(vars_, symbol_names, branch_name):
"""Verifies variables output by a conditional branch for consistency."""
for name, var_ in zip(symbol_names, vars_):
if isinstance(var_, variables.Undefined):
raise ValueError(
"'{}' must also be initialized in the {} branch".for... | 50,536 |
def hit_counter_from_list(filenames, barcode):
"""
:param filenames: all files from a single barcode - just the same hit_counter but for a list of filenames
:param barcode: the barcode associated to our experiment
:return: a dict {genome:hits}
"""
genomes = dict()
for name in filenames:
... | 50,537 |
def test_get_na_switch_game_no_box_art_value_error():
"""Test we use no box art url if the games doesn't have a box art url."""
wishlist = ["title1"]
eshop = EShop("US", Mock(), wishlist)
game = {
"msrp": 14.99,
"nsuid": 70010000532,
"salePrice": 8.24,
"title": "Aggelos",... | 50,538 |
def test_access_token(token):
"""Test checks if the token is not None"""
assert token is not None | 50,539 |
def average(v):
"""
:param v: a list of numerical values
:return: average for a list of values expressed as a float
"""
return sum(v) * 1.0 / len(v) | 50,540 |
def create_file2(file_list):
"""
Function to merge ascii files.
Parameters
-------------
file_list : 'str'
Path to the files. Taken automatically.
Returns
-------------
Merged file: output_file.txt
"""
with open('output_file.txt', 'w') as file3:
readers = [open(file) for file in file_list]
... | 50,541 |
def get_all_projects_of_type(project_type: int):
"""Get the project ids for active and inactive projects in Firebase DB."""
project_id_list = []
fb_db = firebaseDB()
# we neglect private projects here
# since there are no projects set up in production yet
status_list = ["active", "inactive"]
... | 50,542 |
def leaf_actions(
root: morello.impl.base.Impl, include_inner_impl=False, skip_sliding=False
) -> Iterable[tuple[Callable, int]]:
"""Yields callables for each action possible in root's leaves.
More specifically, this yields from a concatenation of all leaves' actions wrapped
in functions that yield, no... | 50,543 |
def set_engine(filename, *,
resolve: bool = False,
require: bool = False,
title: typing.Optional[str] = None,
title_memory_tag: str = _globals.MEMORY_TAG):
"""Return new sqlite3 engine and set it as default engine for treedb."""
log.info('set_engine: %... | 50,544 |
def test_external_program_page_faculty_subpage():
"""
FacultyMembersPage should return expected values if associated with ExternalProgramPage
"""
external_program_page = ExternalProgramPageFactory.create()
assert not external_program_page.faculty
FacultyMembersPageFactory.create(
... | 50,545 |
def camel_split(string):
# test: (str) -> str
"""
>>> print('(%s)' % ', '.join("'%s'" % s for s in camel_split('theBirdsAndTheBees')))
('the', 'Birds', 'And', 'The', 'Bees')
>>> print('(%s)' % ', '.join("'%s'" % s for s in camel_split('theBirdsAndTheBees123')))
('the', 'Birds', 'And', 'The', 'Be... | 50,546 |
def iSP(a: Point, b: Point, c: Point) -> Turn:
"""iSP
Determine the positional relationship of the three Points.
Returns
-------
Turn direction
"""
flg = sign((b - a).det(c - a))
if flg == 1:
return Turn.CCW
elif flg == -1:
return Turn.CW
else:
if si... | 50,547 |
def init_particle_set():
"""
Initialize the particles uniformly across the entire map.
Thresholded map is available
-> Randomly select free cells in the occupancy map
-> Assign particles to those cells along with a random orientation value [0,360]
Inputs: occupancy_map {(X,Y)->(row, colu... | 50,548 |
def generatePathsACS(ants: list, graph: np.ndarray, H: np.ndarray, P: np.ndarray, alpha: float,
beta: float, decay: float, pher_init: float, Q: float,
exp_heuristic: bool = True) -> list:
"""
Function that performs the exploration of the graph using the Ant Colony Syste... | 50,549 |
def test_exception(exception_phase: ProcessPhase) -> None:
"""
Tests that we can run multiple processes where one of them raises an exception.
"""
manager = ProcessManager(
processes=(
ProcessInfo(
module=__name__,
name="proc1",
args=(
... | 50,550 |
def fit_a_model(args):
"""
Parallelizable
"""
model, model_args, x_train, y_train, x_test, y_test = args
classifier = model(**model_args)
# NOTE: Not best practice, but otherwise warnings pollute
try:
with warnings.catch_warnings():
classifier.fit(x_train, y_train.va... | 50,551 |
def detect_hfo_cs_beta(sig, fs=5000, threshold=0.1, cycs_per_detect=4., mp=1):
"""
Beta version of CS detection algorithm. Which was used to develop
CS detection algorithm.
Parameters
----------
sig: numpy array
1D numpy array with raw data
fs: int
Signal sampling frequency
... | 50,552 |
def get_comments(user):
"""Returns all of the user's comments"""
comments = ''
for comment in user.get_comments(limit=None):
comments = comments + ' ' + comment.body
return comments | 50,553 |
def is_supported():
"""Get whether Dialite is supported for the current platform."""
return not isinstance(_the_app, StubApp) | 50,554 |
def _check_axes_range(axes, ndim):
"""
Check axes are within the number of dimensions of tensor x and normalize the negative axes.
Args:
axes (Union[int, tuple(int), list(int)]): Axes of the tensor.
ndim (int): The number of dimensions of the tensor.
Return:
Axes (Union[int, tupl... | 50,555 |
def testunit(func, start, end):
"""
Test unit that records elapsed time
"""
start_time = time()
func(start, end)
end_time = time()
resultStr = ""
resultStr += "Function:\t{}\nElapsed time:\t{}\n".format(func.__name__,
end_time ... | 50,556 |
def compare_token_sets(qset, iset,
intersector, counter, high_intersection_filter,
len_legalese, unique,
rule,
filter_non_matching=True,
high_resemblance_threshold=0.8):
"""
Compare a `qset` query set or multiset with a `iset` index rule set or
multiset. Return a tupl... | 50,557 |
def write_task_group(task_group, task_path):
"""Write a valid task group to a path.
Parameters
----------
task_group : tcor.group.TaskGroup
A prepared task group
"""
with open(task_path, "wb") as f:
if task_group.valid_group_task is True:
json.dump(task_group, f)
... | 50,558 |
def cm_LU_USGS24():
"""Land use colormap.
https://github.com/blaylockbk/pyBKB_v2/blob/master/BB_cmap/landuse_colormap.py
# MUST SET VMAX AND VMIN LIKE THIS TO SCALE COLOR RANGE CORRECTLY
cm, labels = LU_MODIS21()
plt.pcolormesh(LU_INDEX, cmap=cm, vmin=1, vmax=len(labels) + 1)
"""
C =... | 50,559 |
def lazy_value(fce):
""" The decorator for only once computed value. Same a functools.cache,
but there is no need to take care of arguments.
"""
x = []
""" Hack for staticmethod decorator, which is in fact binded by the descriptor protocol """
if isinstance(fce, staticmethod):
fce =... | 50,560 |
def identity_by_descent(dataset, maf=None, bounded=True, min=None, max=None) -> Table:
"""Compute matrix of identity-by-descent estimates.
.. include:: ../_templates/req_tvariant.rst
.. include:: ../_templates/req_biallelic.rst
Examples
--------
To calculate a full IBD matrix, using minor al... | 50,561 |
def sanitize_cloud(cloud: str) -> str:
"""Fix rare cloud layer issues"""
if len(cloud) < 4:
return cloud
if not cloud[3].isdigit() and cloud[3] not in ("/", "-"):
# Bad "O": FEWO03 -> FEW003
if cloud[3] == "O":
cloud = cloud[:3] + "0" + cloud[4:]
# Move modifiers ... | 50,562 |
def list_permission(request):
"""显示权限名称的列表"""
tpl_name = 'user/list_permission.html'
perms = Permission.objects.all()
info = {'perms':perms}
return render(request,tpl_name,info) | 50,563 |
def compute_sphercial_clustering_loss(centroids, features, batch_memberships):
"""Compute repulsive chain loss
Args:
features: [B, C] l2 normalized data, cf) B: batch size, C: feature dimension
memberships (int): [B, ] current membership
centroids: [K, C] cluster centers
... | 50,564 |
def av_client_start(
tutk_platform_lib: CDLL,
session_id: Union[int, c_int],
username: bytes,
password: bytes,
timeout_secs: int,
channel_id: int,
) -> typing.Tuple[c_int, c_uint]:
"""Start an AV client.
Start an AV client by providing view account and password. It shall pass
the au... | 50,565 |
def client_match_template(template_img_location, conf=0.8, region_=(0, 0, 1920, 1080)):
"""
Using pyautogui.locateCenterOnScreen() to check where are buttons to click.
Parameters
----------
template_img_location : template img path
conf : confidence The default is 0.8.
Returns
-------
... | 50,566 |
def print_queues(policies) -> None:
"""Join list which are the queues. Add worw titles to row using zip(tuple)"""
cat = ("Queue ->", "Class Rate ->",
"Class Pkts ->", "Class Bytes ->",
"Out Bytes ->", "Out Pkts ->",
"Drop Bytes ->", "Drop Pkts ->",
... | 50,567 |
def balance_data(data):
""" DEPRECATED """
survived, died = count_survivors(data['Survived'])
remove_n = abs(survived - died)
dropId = []
if survived > died:
dropid = np.random.choice(data[data['Survived'] == 1].index, remove_n, replace=false)
elif survived < died:
dropId = np.ra... | 50,568 |
def main():
"""Create cylc public database, then run diagram creation tool."""
with tempfile.NamedTemporaryFile() as tf:
# is_public=False triggers the creation of tables
CylcSuiteDAO(db_file_name=tf.name, is_public=False)
db_name = "sqlite:///{}".format(tf.name)
render_er(db_nam... | 50,569 |
def log_concave_rejection_sampler(
mode,
prob_fn,
dtype,
sample_shape=(),
distribution_minimum=None,
distribution_maximum=None,
seed=None):
"""Utility for rejection sampling from log-concave discrete distributions.
This utility constructs an easy-to-sample-from upper bound for a discret... | 50,570 |
def login(user_name, password):
""" This function takes user name and password to login into Github account.
Args:
:param user_name: Github username
:param password: Github password
Returns:
error_dict (dict): If it's logged in successfully or not with the error m... | 50,571 |
def make_tukey(n, a=0.5):
"""Make a tukey window
Args:
n (int): Number of points
a (float, optional): Width of window. Defaults to 0.5.
Returns:
np.array: Weights
"""
x = np.arange(n)
weights = np.ones_like(x, dtype=float)
weights[0:int(a*n/2)] = 1/2*(1-np.cos(2*np.... | 50,572 |
def PhaseLegalization(fun: ir.Fun, unit: ir.Unit, _opt_stats: Dict[str, int], fout):
"""
Does a lot of the heavily lifting so that the instruction selector can remain
simple and table driven.
* lift almost all regs to 32bit width
* rewrite Ins that cannot be expanded
* rewrite immediates that ca... | 50,573 |
def remove_excessive_pdf():
"""
this function equivalently checks the difference between pdf and xml sets
and removed any unmatched pdf files
"""
categories = get_excessive_pdf() # a generator which contains the category name and corresponding file names
for articles in categories:
... | 50,574 |
def linear_gradient(start_hex: str, finish_hex: str = "#FFFFFF", n: int = 11) -> color_dict:
""" returns a gradient list of (n) colors between
two hex colors. start_hex and finish_hex
should be the full six-digit color string,
including the number sign ("#FFFFFF") """
# Starting and ending colors in... | 50,575 |
def bast_label_to_number(annotation, label):
"""Given an annotation file and a label convert it to its corresponding
number for the BAST dataset."""
return bast_label_to_number_dict(annotation).get(label, None) | 50,576 |
def most_recent_timestamp(dir):
"""Returns the file with the most recent timestamp in the directory."""
most_recent = datetime.datetime.min
file = None
for cur in os.listdir(dir):
timestr = cur.split("-", maxsplit=1)[0]
cur_time = datetime.datetime.strptime(timestr, '%y%m%d%H%M%S')
... | 50,577 |
def function_with_exception(val):
"""Return a `val` if it is non-negative"""
if val < 0:
raise ValueError("val cannot be negative.")
return val | 50,578 |
def _c(obj: model.Component):
"""Convert :class:`.Component`."""
# Raises AttributeError if the concept_identity is missing
return str(obj.concept_identity.id) | 50,579 |
def get_power_instance(wildcards):
"""
Returns a formatted template
Arguments:
rest_base - Base URL of the RESTful interface
ident - Identifier of the chassis
"""
c = copy.deepcopy(_TEMPLATE)
c['@odata.context'] = c['@odata.context'].format(**wildcards)
c['@odata.id'] =... | 50,580 |
def get_user_history(history_type):
"""
:param history_type: 'click' or 'top' or 'play'
:return:
"""
spark.sql('use {}'.format(user_pre_db))
if history_type == 'play':
tmp_df = spark.sql('select user_id, movie_id, cate_id, datetime, play_time from merge_action').where(
'play_... | 50,581 |
def display_on_frame(self, image, left_curverad, right_curverad, car_off):
"""
Display texts on image using passed values
"""
font = cv2.FONT_HERSHEY_COMPLEX
curve_disp_txt = 'Curvature: Right = ' + str(np.round(right_curverad,2)) + 'm, Left = ' + str(np.round(left_curverad,... | 50,582 |
def path_is_relative_to(path: Path, other: PathOrStr) -> bool:
"""
This is copied from :meth:`pathlib.PurePath.is_relative_to` to support older Python
versions (before 3.9, when this method was introduced).
"""
try:
path.relative_to(other)
return True
except ValueError:
r... | 50,583 |
def add_known_bug(bug_id, description=None, type=LAUNCHPAD):
"""
Fetch the current plugin known_bugs.yaml if it exists and add new bug with
description of the bug.
"""
if not os.path.isdir(PLUGIN_TMP_DIR):
raise Exception("plugin tmp dir '{}' not found".
format(PLUGI... | 50,584 |
def generate_tokens( parser, lines, flags, keywords):
"""
This is a rewrite of pypy.module.parser.pytokenize.generate_tokens since
the original function is not RPYTHON (uses yield)
It was also slightly modified to generate Token instances instead
of the original 5-tuples -- it's now a 4-tuple of
... | 50,585 |
def main():
"""Entry point to the script."""
# Basic parsing of command line arguments to allow a filename
# to be passed when running this code in the debugger.
file_handle = sys.stdin
if 2 <= len(sys.argv):
file_handle = open(sys.argv[1], "r")
expander = GvcfExpander(bin_size=1000,
... | 50,586 |
def test_settle_channel_event(
web3,
get_accounts,
token_network,
create_channel,
channel_deposit,
create_balance_proof,
create_balance_proof_update_signature,
event_handler,
):
""" A successful settleChannel() call causes a SETTLED event """
ev_ha... | 50,587 |
def get_days_word_ending(days: int) -> str:
"""Определяет окончание слова "дня", "дней" и т.д. в зависимости от входящего числа"""
last_numeral = days % 10
prelast_numeral = days % 100
prelast_numeral = prelast_numeral // 10
if prelast_numeral == 1:
return 'дней'
if last_numeral == 0 or ... | 50,588 |
def _init_hoomd_rb_torsions(structure, ref_energy=1.0):
"""RB dihedrals (implemented as OPLS dihedrals in HOOMD)."""
# Identify the unique dihedral types before setting
dihedral_type_params = {}
for dihedral in structure.rb_torsions:
t1, t2 = dihedral.atom1.type, dihedral.atom2.type
t3, ... | 50,589 |
def tpg():
"""[DEPRECATED] use "taurus plot" or "taurus trend" instead"""
print('"taurus tpg" subcommand is deprecated. '
+ 'Use "taurus plot" or "taurus trend" instead\n')
sys.exit(1) | 50,590 |
def moments(data):
"""Returns (height, x, y, width_x, width_y)
the gaussian parameters of a 2D distribution by calculating its
moments """
total = data.sum()
X, Y = np.indices(data.shape)
x = (X * data).sum() / total
y = (Y * data).sum() / total
col = data[:, int(y)]
width_x = np.sqr... | 50,591 |
def compute_throughputs(batch_size, gpu_times):
"""
Given a batch size and an array of time running on GPU,
returns an array of throughputs
"""
return [batch_size / gpu_times[i] * 1000 for i in range(len(gpu_times))] | 50,592 |
def load_trained_model(args, config_class, model_class, label_count_info, n_gpu, device):
"""Load trained model for evaluation"""
model = _build_pretrained_model(args, config_class, model_class, label_count_info)
model.to(device)
model_path = args.output_dir + "/epoch_%d" % args.load_n_epoch
ckpt_s... | 50,593 |
def parse_filter_field(string_filters) -> dict:
"""
Parses string with sets of name, value and comparison into a dict
Args:
string_filters: A string of the form 'name=<name1>,value=<value1>,comparison=<comparison1>;name=<name2>...'
Returns:
A dict of the form {<name1>:[{'Value': <value1... | 50,594 |
def create_empty_image_like(im: Image) -> Image:
""" Create an empty image like another in shape and wcs
:param im:
:return: Image
"""
assert type(im) == Image, "Type is %s" % type(im)
fim = Image()
fim.polarisation_frame = im.polarisation_frame
fim.data = numpy.zeros_like(im.data)... | 50,595 |
def convert_to_one_hot(integer_vector, dtype=None, max_labels=None,
mode='stack', sparse=False):
"""
Formats a given array of target labels into a one-hot
vector.
Parameters
----------
max_labels : int, optional
The number of possible classes/labels. This means th... | 50,596 |
def get_constraints(
guesses: list[str], calls: list[Sequence[Call]]
) -> tuple[dict[int, str], set[str], set[str]]:
"""Get constraints."""
positions = {}
appears = set()
no_appears = set()
for call, guess in zip(calls, guesses):
for i, c, x in zip(itt.count(), call, guess):
... | 50,597 |
def apply_trained_model(
trained_model_object, input_table, feature_names, replace_missing,
standardize, transform_via_svd, replacement_dict_for_training_data=None,
standardization_dict_for_training_data=None,
svd_dict_for_training_data=None):
"""Uses a trained model to make predicti... | 50,598 |
def extract_host(host, level='backend', default_pool_name=False):
"""Extract Host, Backend or Pool information from host string.
:param host: String for host, which could include host@backend#pool info
:param level: Indicate which level of information should be extracted
from host string.... | 50,599 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.