content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def cache_instance(get_instance_fn: Callable[..., data.TrainingInstance] = None, *, cache_dir, **instance_config):
"""Decorator to automatically cache training instances."""
if get_instance_fn is None:
return partial(cache_instance, cache_dir=cache_dir)
cache_data_id = create_hash_id(json.dumps(in... | 48,400 |
def keep_alive(context: dict, flumine) -> None:
"""Attempt keep alive if required or
login if keep alive failed
"""
client = flumine.client
if client.betting_client.session_token:
try:
resp = client.keep_alive()
if resp is None or resp.status == "SUCCESS":
... | 48,401 |
def get_definitions_query_filter(request_args):
""" Get query_filter for alert_alarm_definition list route.
"""
query_filters = None
display_retired = False
valid_args = ['array_name', 'platform_name', 'instrument_name', 'reference_designator']
# Process request arguments
if 'retired' in req... | 48,402 |
def main():
"""
Main execution script.
"""
print('demo 2')
print('demo 3')
print('demo4')
return | 48,403 |
def _read_dictionary_page(file_obj, schema_helper, page_header, column_metadata):
"""Read a page containing dictionary data.
Consumes data using the plain encoding and returns an array of values.
"""
raw_bytes = _read_page(file_obj, page_header, column_metadata)
io_obj = io.BytesIO(raw_bytes)
va... | 48,404 |
def num_songs(t):
"""Return the number of songs in the pyTunes tree, t.
>>> pytunes = make_pytunes('i_love_music')
>>> num_songs(pytunes)
3
"""
"*** YOUR CODE HERE ***"
if is_leaf(t):
return 1
else:
sum_songs = 0
for subt in branches(t):
sum_songs += ... | 48,405 |
def generate_sections_from_pyquery(body):
"""Given a pyquery object, generate section dicts for each section."""
# Capture text inside h1 before the first h2
h1_section = body('.section > h1')
if h1_section:
div = h1_section.parent()
h1_title = h1_section.text().replace(u'¶', '').strip()... | 48,406 |
def _get_parameter_value(potential: Potential, handler: str, parameter: str) -> float:
"""Returns the value of a parameter in its default units"""
return (
potential.parameters[parameter].to(_DEFAULT_UNITS[handler][parameter]).magnitude
) | 48,407 |
def my_func():
"""This is docstring for my_func."""
return | 48,408 |
def test_peek_empty():
"""Test peek empty PriorityQ raises index error."""
from priorityq import PriorityQueue
test_instance = PriorityQueue()
with pytest.raises(IndexError):
test_instance.peek() | 48,409 |
def triplets_in_range(mini, maxi):
"""
Finds all the triplets in a given range that meet the condition a ** 2 + b ** 2 = c ** 2
>>> triplets_in_range(2, 10)
{(3, 4, 5), (6, 8, 10)}
:param mini: The minimum in the range
:param maxi: Maximum in the rnage
:return: a set of tuples (with length... | 48,410 |
def targetInCol(df, target):
"""
Return meta information (Line or Area) from information in a column of DF.
Arguments:
doc -- csv Promax geometry file
target -- meta information to get (Line or Area)
"""
c = list(df.columns)
ptarget = r''+re.escape(target)
i = [i for i, x in enumera... | 48,411 |
def default_monitor(verbose=1):
"""Returns very simple monitor object to summarize training progress.
Args:
verbose: Level of verbosity of output.
Returns:
Default monitor object.
"""
return BaseMonitor(verbose=verbose) | 48,412 |
def pca(X, k = 30, optim = "fastest"):
"""Use PCA to project X to k dimensions."""
# Center/scale the data.
s = np.std(X, axis=0)
s = np.where(s==0, 1, s)
X = (X - np.mean(X, axis=0))/s
if optim == "none":
# Compute covariance eigenvectors with numpy.
#
# T... | 48,413 |
def get_range(a_list):
"""
=================================================================================================
get_range(a_list)
This is meant to find the maximal span of a list of values.
=======================================================================================... | 48,414 |
def load_groups():
"""
__tablename__ = 'groups'
co_cou_id = db.Column(db.Integer)
co_parent_cou_id = db.Column(db.Integer, nullable=True)
name = db.Column(db.String())
description = db.Column(db.Text)
deleted = db.Column(db.Boolean, default=False)
"""
cous = api.cous_view_per_co().g... | 48,415 |
def create_config(solution, nodes, description_info):
"""Creates compact string representing input data file
Parameters:
solution (list) List of solutions
nodes (list) List of node specification
description_info (tuple) CSP description in form of tuple: (algorithm name, domains, constrai... | 48,416 |
def get_effective_option(metadata, settings, key):
"""
Return option with highest priority:
not-defined key < default < pelican config settings < file metadata
"""
return metadata.get(key, settings[DP_KEY].get(key)) | 48,417 |
def positions_sync_out_doc_view(request):
"""
Show documentation about positionsSyncOut
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = positions_sync_out_doc.positions_sync_out_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
r... | 48,418 |
def __build_caj_q_html_view__(data: object) -> any:
"""
popup's table for Caju Quality Information
"""
satellite_est = gettext("Satellite Estimation")
tns_survey = gettext("TNS Survey")
nut_count_average = gettext("Nut Count Average")
defective_rate_average = gettext("Defective Rate Average... | 48,419 |
def test_equal(dummy_pool):
"""Test the __eq__ method"""
assert dummy_pool == TransportPool(
transport_class=DebugEventTransport,
transport_config=DebugEventTransport.Config(),
config=Config.default(),
) | 48,420 |
def code(email):
"""
Returns the one-time password associated with the given user for the
current time window. Returns empty string if user is not found.
"""
print("route=/code/<email> : email:", email)
u = User.get_user(email)
if u is None:
print("user not found, returning ''")
... | 48,421 |
def blend_image_with_masks(image, masks, colors, alpha=0.5):
"""Add transparent colored mask to an image.
Args:
image: `np.ndarray`, the image of shape (width, height, channel) or (width, height).
masks: `np.ndarray`, the mask of shape (n, width, height).
colors: list, a list of RGB colors (from ... | 48,422 |
def plot_attacks (a_index, dataset= None, attacks_data = None):
""" Plot the % for each attack in a_index of the dataset """
if attacks_data is None:
attacks_percents = get_attacks_percent(a_index=a_index, dataset=dataset)
#other = []
#for attack, index in attacks_map.items():
... | 48,423 |
def edl_barrier(job_env, pod, timeout):
"""
pod under resource barrier togather
"""
start = time.time()
leader = get_pod_leader()
c = PodServerClient(leader.endpoint)
# all pods barrier on leader
while True:
try:
c.barrier(job_env.job_id, pod.get_id())
br... | 48,424 |
def get_trainee_and_group(func):
"""Decorator to insert trainee and group as arguments to the given function.
Creates new Trainee if did not exist in DB.
Creates new Group if did not exist in DB.
Adds the trainee to the group if it was not part of it.
Appends the trainee and group as last argument ... | 48,425 |
def get_bisect_info(good_commits, bad_commit):
"""Returns a dict with info about the current bisect run.
Internally runs `git rev-list --bisect-vars`. Information includes:
- bisect_rev: midpoint revision
- bisect_nr: expected number to be tested after bisect_rev
- bisect_good: bisect_nr if good
... | 48,426 |
def generate_chromatogram(
ms_data: dict,
chromatogram: str,
ms_level: int = 1
) -> list:
"""
Generates a either a Base Peak Chromatogram (BPC) or Total Ion Chromatogram
(TIC) from ripper data.
Args:
ms_data (dict): mzml ripper data in standard ripper format.
chromatogram (s... | 48,427 |
def get_tensor_batch_size(values):
"""Extracts batch size from tensor"""
return tf.gather(params=tf.shape(input=values), indices=tf.constant([0])) | 48,428 |
def generate_particle_timestamp(time_2000):
"""
This function calculates and returns a timestamp in epoch 1900
based on an ASCII hex time in epoch 2000.
Parameter:
time_2000 - number of seconds since Jan 1, 2000
Returns:
number of seconds since Jan 1, 1900
"""
return int(time_200... | 48,429 |
def clip_histogram(hist, clip_limit):
"""Perform clipping of the histogram and redistribution of bins.
The histogram is clipped and the number of excess pixels is counted.
Afterwards the excess pixels are equally redistributed across the
whole histogram (providing the bin count is smaller than the clipl... | 48,430 |
def aggregate_precision_recall(
labels_pred_iterable: Iterable,
precision_recall_fn: Callable = buffered_precision_recall,
) -> Tuple[float, float]:
"""
Computes aggregate range-based precision recall metrics for the given prediction labels.
Parameters
----------
labels_pred_iterable
... | 48,431 |
def find_tag_for(t):
"""If transaction matches a rule, returns corresponding tuple
(tag, ruler, match).
"""
res = []
for (tag, rulers) in list(TAGS.items()):
for ruler in rulers:
m, matches = match(ruler, t)
if m:
res.append((tag, ruler, matches))
... | 48,432 |
def DOMWidget(
layout: Union[Dict[str, Any], Element[ipywidgets.widgets.widget_layout.Layout]] = {},
on_layout: typing.Callable[[Union[Dict[str, Any], Element[ipywidgets.widgets.widget_layout.Layout]]], Any] = None,
) -> Element[ipywidgets.widgets.domwidget.DOMWidget]:
"""Widget that can be inserted into th... | 48,433 |
def delete(account):
"""
Delete an account both remotely and locally.
Note that this will fail if the account's balance is
non-zero.
"""
account.stripe_account.delete()
account.delete() | 48,434 |
def load(path, element_spec=None, compression=None, reader_func=None):
"""Loads a previously saved dataset.
Example usage:
>>> import tempfile
>>> path = os.path.join(tempfile.gettempdir(), "saved_data")
>>> # Save a dataset
>>> dataset = tf.data.Dataset.range(2)
>>> tf.data.experimental.save(dataset, p... | 48,435 |
def test_confusion_PRFAS():
"""
Line=True class, column=Prediction
TR_B [[1585 109 4]
TR_I [ 126 1233 17]
TR_O [ 20 12 82]]
(unweighted) Accuracy score = 90.97 % trace=2900 sum=3188
precision recall f1-score support
TR_B 0.916 0.933 0.924 1698
... | 48,436 |
def wrap(x, m, M):
"""
:param x: a scalar
:param m: minimum possible value in range
:param M: maximum possible value in range
Wraps ``x`` so m <= x <= M; but unlike ``bound()`` which
truncates, ``wrap()`` wraps x around the coordinate system defined by m,M.\n
For example, m = -180, M = 180 (... | 48,437 |
def execute_processors(processors: Iterable[ProcessorType], state: State) -> None:
"""Execute a sequence of processors to generate a Document structure. For block handling,
we use a recursive approach. Only top-level blocks are extracted and processed by block
processors, which, in turn, recursively call th... | 48,438 |
def record_app_use():
"""Record last app use in the session and the backend database."""
# session
now = UTC.localize(datetime.datetime.utcnow()).timestamp()
session["last_app_use"] = now
# database
db.session.add(AppUse(remote=str(get_remote_addr())))
db.session.commit() | 48,439 |
def date(repo, subset, x):
"""Changesets within the interval, see :hg:`help dates`.
"""
# i18n: "date" is a keyword
ds = getstring(x, _("date requires a string"))
dm = util.matchdate(ds)
return subset.filter(lambda x: dm(repo[x].date()[0]),
condrepr=('<date %r>', ds)) | 48,440 |
def addAuthor(author):
"""
Creates an Author dictionary
:param author: Author instance
:return: Dict
"""
author_dict = dict()
# author_dict['id'] = "{}/api/{}".format(DOMAIN, author.id)
author_dict['id'] = "{}/api/author/{}".format(DOMAIN, author.id)
author_dict['host'] = "{}/api/".... | 48,441 |
def add_transformer_enc_hyperparams_args(parser):
"""Only applicable when args.model_name is 'transformer_enc'"""
parser.add_argument('--hid_dim', type=int, default=128)
parser.add_argument('--num_enc_layers', type=int, default=3)
parser.add_argument('--num_enc_heads', type=int, default=8)
parser.ad... | 48,442 |
def make_length(value):
""" Make a kicad length measurement from an openjson measurement """
return int(round(float(value) * MULT)) | 48,443 |
def get_data_path():
"""
Return the path to the project's data folder
:return: The path to the data folder
"""
project_folder = os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(__file__))))
return os.path.join(project_folder, "data") | 48,444 |
def with_metaclass(meta, *bases):
"""copied from https://github.com/Byron/bcore/blob/master/src/python/butility/future.py#L15"""
class metaclass(meta):
__call__ = type.__call__
__init__ = type.__init__
def __new__(cls, name, nbases, d):
if nbases is None:
ret... | 48,445 |
def timeout_iter(duration):
"""sets a timer for `duration` seconds, yields time elapsed as long as timeout has not been reached"""
t0 = time.perf_counter()
elapsed = 0
while elapsed < duration:
yield elapsed
elapsed = time.perf_counter() - t0 | 48,446 |
def calc_mupen_res(N,region_w,region_h):
"""find res to fit N mupen instances in region"""
results = []
for row_length in range(1,N+1):
col_length = math.ceil(N/float(row_length))
instance_width = int(math.floor( min(640, region_w/float(row_length) )))
instance_height = int(math.floor(instance_width... | 48,447 |
def pos_tag_wordnet(text: List) -> List:
"""Create pos_tag with wordnet format
:rtype: object
:param (List) text: string to be nltk_pos_tagged for syntactic similar synonyms
:return (List[List[str, 'pos_tag']]) tagged_text: str values with according nltk_pos_tag
"""
pos_tagged_text... | 48,448 |
def create_app():
"""
Create an app with config file
:return: Flask App
"""
# init a flask app
app = Flask(__name__)
# 从yaml文件中加载配置,此加载方式有效加载
# 初始化APP
_config_app(app)
# 允许跨域请求
if app.config.get('CORS_ENABLE'):
CORS(app)
# 配置蓝图
configure_blueprints(app)
... | 48,449 |
def img_to_json(img, decimals=2, swap=False, save=None):
""" Convert an image volume to web-ready JSON format suitable for import into
the Neurosynth viewer.
Args:
img: An image filename.
round: Optional integer giving number of decimals to round values to.
swap: A temporary kludge to dea... | 48,450 |
def encode_float(
encoder_state: ctypes.Structure,
pcm_data: bytes,
frame_size: int,
max_data_bytes: int
) -> typing.Union[bytes, typing.Any]:
"""Encodes an Opus frame from floating point input"""
pcm_pointer = ctypes.cast(pcm_data, opuslib.api.c_float_pointer)
opus_data = (c... | 48,451 |
def _login(use_cookie):
"""User login helper function.
The request data should contain at least 'email' and 'password'.
The cookie expiration duration is defined in flask app config.
If user is not authenticated, it raises Unauthorized exception.
"""
data = _get_request_data()
if 'email' no... | 48,452 |
def get_days_to_complete(course_id, date_for):
"""Return a dict with a list of days to complete and errors
NOTE: This is a work in progress, as it has issues to resolve:
* It returns the delta in days, so working in ints
* This means if a learner starts at midnight and finished just before
midnig... | 48,453 |
def test_seccomp_ls(bin_seccomp_paths):
"""Assert that the seccomp filter denies an unallowed syscall."""
# pylint: disable=redefined-outer-name
# pylint: disable=subprocess-run-check
# The fixture pattern causes a pylint false positive for that rule.
# Path to the `ls` binary, which attempts to ex... | 48,454 |
def get_course_data(level="graduate", department_code="CS"):
# Get appropriate regex for the provided data.
"""
Retrieves the information as tuple of the form (course numbers, titles, pre-requisites, description)
for a given program and department.
:type level: string (Must be one of "undergraduate... | 48,455 |
def get_highlightjs_setting(setting, default=None):
"""
Read a setting
"""
return HIGHLIGHTJS.get(setting, default) | 48,456 |
def make_walks(T,
walklen=10,
epochs=3,
return_weight=1.,
neighbor_weight=1.,
threads=0):
"""
Create random walks from the transition matrix of a graph
in CSR sparse format
NOTE: scales linearly with threads but hyperthread... | 48,457 |
def package_dir_path(path):
"""Return package path to package install directory"""
return path + '/.pkg' | 48,458 |
def sort_cluster_data(cluster_data, cluster_accuracy):
"""
sort cluster data based on GDT_mean values of cluster_accuracy.
-> cluster 0 will have highest GDT_mean
-> cluster <max> will have lowest GDT_mean
.. Note :: if cluster_data has noise_label assigned, will move this label to the end of t... | 48,459 |
def reprintClean(pack):
"""
Helper function specifically for reprint packs.
:param pack: List, contains the 12 cards in a pack
:return: temppack, the pack with the higher rarity cards implanted in
"""
temppack = pack
rarity = random.randint(0, 12)
if rarity == 0:
card = ... | 48,460 |
def load_data(db, brand_mappings: dict = None, item_stream=None, commit_size=1000):
"""
:param db:
:param brand_mappings:
:param item_stream:
:param commit_size:
:return:
"""
brand_mappings = brand_mappings or BRANCH_NAMES_TO_IDS
load_brand_name_mappings(db, brand_mappings)
ite... | 48,461 |
def logout():
"""Logs the current user out"""
del session['user_id']
return redirect('/') | 48,462 |
def main() -> int:
"""
Main function. Executed if script is called standalone.
"""
args = _parse_cmd_args()
try:
return _search_symantec(args.keyword, args.limit)
except KeyboardInterrupt:
_warn("Keyboard interrupt detected\n", True)
return 1 | 48,463 |
def _check_imgs_array(imgs):
"""Check input image if it is an array
Parameters
----------
imgs : array of str, shape=[n_subjects, n_sessions]
Element i, j of the array is a path to the data of subject i
collected during session j.
Data are loaded with numpy.load and ... | 48,464 |
def smoothline(xs, ys=None, interpol=3, window=1, verbose=3):
"""Smoothing 1D vector.
Description
-----------
Smoothing a 1d vector can be challanging if the number of data is low sampled.
This smoothing function therefore contains two steps. First interpolation of the
input line followed ... | 48,465 |
def setAttribute(values, value):
"""
Takes the values of an attribute value list and attempts to append
attributes of the proper type, inferred from their Python type.
"""
if isinstance(value, int):
values.add().int32_value = value
elif isinstance(value, float):
values.add().doub... | 48,466 |
def _delete_layer_versions(layers: Dict[str, List[int]], event: Any):
"""Delete the provided layer versions for each lambda layer."""
# There is no batch deletion for lambda layer versions; delete them one by one
for layer_name in layers:
for layer_version in layers[layer_name]:
try:
... | 48,467 |
def prune_model(keras_model, prun_factor_dense=10, prun_factor_conv=10, metric='L1', comp=None, num_classes=None, label_one_hot=None):
"""
A given keras model get pruned. The factor for dense and conv says how many percent
of the dense and conv layers should be deleted.
Args:
keras_model: ... | 48,468 |
def unpublish_exploration(committer, exploration_id):
"""Unpublishes the given exploration.
Args:
committer: UserActionsInfo. UserActionsInfo object for the committer.
exploration_id: str. ID of the exploration.
Raises:
Exception. This could potentially throw an exception from
... | 48,469 |
def scale_values(tbl, columns):
"""Scale values in a dataframe using MinMax scaling.
:param tbl: Table
:param columns: iterable with names of columns to be scaled
:returns: Table with scaled columns
"""
new_tbl = tbl.copy()
for col in columns:
name = new_tbl.labels[col]
x_sc... | 48,470 |
def do_share_network_list(cs, args):
"""Get a list of network info."""
all_tenants = int(os.environ.get("ALL_TENANTS", args.all_tenants))
search_opts = {
'all_tenants': all_tenants,
'project_id': args.project_id,
'name': args.name,
'created_since': args.created_since,
... | 48,471 |
def setup_args(args):
""" Setup the args based on the argparser obj
Args:
args(ArgParser): Parsed arguments
Notes:
If there is no core_root, or test location passed, create a default
location using the build type and the arch.
"""
host_os = None
arch = args.arch
bu... | 48,472 |
def discover_devices(timeout : int = 30, debug : bool = False) -> Dict[Optional[str], str]:
"""
Discovers Nanoleaf devices on the network using SSDP
:param timeout: The timeout on the search in seconds (default 30)
:param debug: Prints each device string for the SSDP discovery
:returns: Dictionary ... | 48,473 |
def get_params_out_of_range(
params: list, lower_params: list, upper_params: list
) -> list:
"""
Check if any parameter specified by the user is out of the range that was defined
:param params: List of parameters read from the .inp file
:param lower_params: List of lower bounds provided by the user... | 48,474 |
def _filter_work_values(
works: np.ndarray,
max_value: float = 1e4,
max_n_devs: float = 100,
min_sample_size: int = 10,
) -> np.ndarray:
"""Remove pairs of works when either is determined to be an outlier.
Parameters
----------
works : ndarray
Array of records containing fields ... | 48,475 |
def pf_from_ssig(ssig, ncounts):
"""Estimate pulsed fraction for a sinusoid from a given Z or PDS power.
See `a_from_ssig` and `pf_from_a` for more details
Examples
--------
>>> round(a_from_pf(pf_from_ssig(150, 30000)), 1)
0.1
"""
a = a_from_ssig(ssig, ncounts)
return pf_from_a(a) | 48,476 |
def get_aic(mse: float, n: int, p: int):
"""
Calcuate AIC score.
Parameters
----------
mse: float
Mean-squared error.
n: int
Number of observations.
p: int
Number of parameters
Returns
-------
float
AIC value.
"""
return n * log(mse) + 2 ... | 48,477 |
def triangle(a, b):
""" Return triangle function:
^ .
| / \
|____/___\____
a b
"""
return partial(primitives.tri, a, b) | 48,478 |
def get_max_trans_date() -> date:
"""Return the date of the last transaction in the database"""
return pickle.load(open(conf("etl_accts"), "rb"))[1] | 48,479 |
def build_argparser():
"""
Parse command line arguments.
:return: command line arguments
"""
parser = ArgumentParser()
parser.add_argument("-m", "--model", required=True, type=str,
help="Path to an xml file with a trained model.")
parser.add_argument("-i", "--input",... | 48,480 |
def test_train(pipeline_dict, training_dataset, trainer_config, tmp_path):
"""Testing the correct working of prediction, vocab creating and training"""
pipeline = Pipeline.from_config(pipeline_dict)
pipeline.predict(text="my name is juan")
trainer = Trainer(
pipeline=pipeline,
train_da... | 48,481 |
def read_file(in_file: str):
"""Read input file."""
file_path = Path(in_file)
data = []
count = 0
with open(file_path) as fp:
for line in fp:
data.append(line)
count = count + 1
return ''.join(data), count | 48,482 |
def web_authorize():
"""OAuth 登录跳转"""
# TODO: (演示使用, 自动登录), 请删除并配置自己的认证方式, OAuth2或账密系统
set_user_login({
'job_number': 7777,
'realname': 'Fufu'
})
return redirect(url_for('web.web_index'))
# OAuth 认证
redirect_uri = url_for('web.web_authorized', _external=True)
return oau... | 48,483 |
def insert_exchange_rates(
session: Session, keyspace: str, table: str, exchange_rates: pd.DataFrame
) -> None:
"""Insert exchange rates into Cassandra table."""
colnames = ",".join(exchange_rates.columns)
values = ",".join(["?" for i in range(len(exchange_rates.columns))])
query = f"""INSERT INTO ... | 48,484 |
def limit(value, limits):
"""
:param <float> value: value to limit
:param <list>/<tuple> limits: (min, max) limits to which restrict the value
:return <float>: value from within limits, if input value readily fits into the limits its left unchanged. If value exceeds limit on either boundary its set to t... | 48,485 |
def _cdp_no_split_worker(work_queue, counts_by_ref, seq_1, seq_2, nt):
"""
Worker process - get refseq from work queue, aligns reads from seq_1 and seq_2,
and adds as (x,y) coords to counts_by_ref if there are alignments.
:param work_queue: joinable queue with refseq header and seq tuples (JoinableQueue... | 48,486 |
def createIQSatelliteChannel(satellite_id):
"""Factory
This method creates a satellite channel object that exchanges IQ data in between both ends.
"""
return SatelliteChannel(satellite_id, stellarstation_pb2.Framing.Value('IQ')) | 48,487 |
def scaled_herding_forward_pass(weights, scales, input_data, n_steps):
"""
Do a forward pass with scaled units.
:param weights: A length:L list of weight matrices
:param scales: A length:L+1 list of scale vectors
:param input_data: An (n_samples, n_dims) array of input data
:param n_steps: Numbe... | 48,488 |
def open_remote_factory(mocker):
"""Fixture providing open_remote function for ReferenceLoader construction."""
return mocker.Mock(return_value=StringIO(REMOTE_CONTENT)) | 48,489 |
def get_displacement_bcs(domain, macro_strain):
"""Get the shift and fixed BCs.
The shift BC has the the right top and bottom points in x, y and z
fixed or displaced.
The fixed BC has the left top and bottom points in x, y and z
fixed.
Args:
domain: an Sfepy domain
macro_strain: t... | 48,490 |
def update(fatal=False):
"""Update local yum cache."""
cmd = ['yum', '--assumeyes', 'update']
log("Update with fatal: {}".format(fatal))
_run_yum_command(cmd, fatal) | 48,491 |
def print_logs():
"""
Print the location of the root local logs directory we expect as well as
the most recent local logs directory. Then tail -f all the log files
and ignore if tail not installed.
:return: None
"""
root_log = fileoperations.get_logs_location(HOST_LOGS_DIRNAME)
last_loc... | 48,492 |
def public_rest_url(path_url: str = "",
domain: str = CONSTANTS.DEFAULT_DOMAIN,
only_hostname: bool = False,
domain_api_version: str = None,
endpoint_api_version: str = None) -> str:
"""
Creates a full URL for provided public REST e... | 48,493 |
def main():
"""
This time I did not come with an algorithm to read and solve the puzzle.
Instead I read the puzzle input and solved it manually, reaching the generalization below.
"""
magic_number = 15 * 170 # Number of iterations in the first loop of the puzzle input
answer = 0
while True:... | 48,494 |
def get_dir_cos(dist_vec):
""" Calculates directional cosines from distance vectors.
Calculate directional cosines with respect to the standard cartesian
axes and avoid division by zero
Args:
dist_vec: distance vector between particles
Returns: dir_cos, array of directional cosines of distan... | 48,495 |
def lambda_handler(event, context):
"""
Entry point for the Get All Lambda function.
"""
handler_request.log_event(event)
# Get gk_user_id from requestContext
player_id = handler_request.get_player_id(event)
if player_id is None:
return handler_response.return_response(401, 'Unautho... | 48,496 |
def test_alarm_already_set():
"""Test various scenarios and return values for test_alarm_already_set."""
alarms = [
{"title": "Date: 02/12/2025 Time: 02:14",
"content": "Test alarm",
"url_request": "2025-12-02T02:14",
"alarm_identifier": "Test alarm"}
]
set_alarm = "2025-12-02T02:14"... | 48,497 |
def pynealScanner_Siemens(scannerSettings, scannerDirs):
""" Launch Pyneal Scanner for real-time scan in a Siemens environment
"""
from utils.Siemens_utils import Siemens_launch_rtfMRI
# launch a real-time session
Siemens_launch_rtfMRI(scannerSettings, scannerDirs) | 48,498 |
def reverse_complement_dna(seq):
"""
Reverse complement of a DNA sequence
Parameters
----------
seq : str
Returns str
"""
return complement_dna(seq)[::-1] | 48,499 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.