content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def get_git_hash():
""" Return the current git hash """
repo = git.Repo(search_parent_directories=True)
return repo.head.object.hexsha | 5,299,500 |
def _eval_once(session_creator, ops_dict, summary_writer, merged_summary,
global_step, num_examples, input_data, labels, unique_groups, fair_margin_over_epochs, FLAGS, config):
"""Runs evaluation on the full data and saves results.
Args:
session_creator: session creator.
ops_dict: dictionary... | 5,299,501 |
def test_binding_residue_annotation_extractor(
get_extractor: Callable[[], BindEmbed21HBIAnnotationExtractor],
expected_accuracy: float,
):
"""Check that BasicAnnotationExtractor passes (without checking correctness)"""
extractor = get_extractor()
hit = read_csv('test-data/bindEmbed21HBI/Q9RN60_hit... | 5,299,502 |
def test_type_bcd_present():
"""
ASCII message type is required by spec and provided
"""
spec["h"]["data_enc"] = "ascii"
spec["h"]["len_type"] = 0
spec["h"]["max_len"] = 6
spec["t"]["data_enc"] = "b"
spec["p"]["data_enc"] = "ascii"
s = b"header\x02\x100000000000000000"
doc_dec, ... | 5,299,503 |
def project_ABA(A, B):
"""
Project matrix of K vectors, a_k, onto Hermitian matrix B
Projects each of K vectors, a_k, in matrix, A, of dimension K x M
onto a Hermitian matrix, B, of dimension M x M producing a
vector of scalars, c, of length K
Parameters
----------
... | 5,299,504 |
def plcc_loss(x, y):
"""Loss version of `plcc_tf`"""
return (1. - plcc(x, y)) / 2. | 5,299,505 |
def replicas_to_qps(num_replicas, processing_time, max_qp_replica=1, target_utilization=0.7):
"""Provide a rough estimate of the queries per second supported by a number of replicas
Args:
num_replicas (int): number of replicas
processing_time (float): the estimated amount of time (in ... | 5,299,506 |
async def retrieve_address_by_id(
address_id: int, db: MSSQLConnection = Depends(get_db)
) -> AddressResponse:
"""
**Retrieves an address with the id from the `address_id` path parameter.**
"""
address = await AddressService(db).get(address_id)
if address is None:
raise HTTPException(sta... | 5,299,507 |
def sqrt(x: VariableLike, *, out: Optional[VariableLike] = None) -> VariableLike:
"""Element-wise square-root.
:param x: Input data.
:param out: Optional output buffer.
:raises: If the dtype has no square-root, e.g., if it is a string.
:return: The square-root values of the input.
"""
retur... | 5,299,508 |
def filter_tree(tree: pd.DataFrame, filterids: list or str or None = None,
root: str = "1", ignoreinvalid: bool = True, sep: str = None, indx: int = 0) -> pd.DataFrame:
"""
Filters an existing pandas DataFrame based on a List of TaxIDs.
:param tree: pandas DataFrame
:param filterids: li... | 5,299,509 |
def check_if_tests_can_run():
"""Verify that the currently loaded profile is a test profile, otherwise raise `TestsNotAllowedError`."""
profile = configuration.PROFILE
if not profile.is_test_profile:
raise TestsNotAllowedError(f'currently loaded profile {profile.name} is not a valid test profile') | 5,299,510 |
def multinomial_coeffs_of_power_of_nd_linear_monomial(num_vars, degree):
""" Compute the multinomial coefficients of the individual terms
obtained when taking the power of a linear polynomial
(without constant term).
Given a linear multivariate polynomial e.g.
e.g. (x1+x2+x3)**2 = x1**2+2*x1*x2+2*... | 5,299,511 |
def main(args):
"""This program will use the GPIO capabilities of the raspberry pi to toggle LED lights based on a schedule
"""
driver = None
try:
logger = logging.getLogger(__name__)
driver = AlarmDriver(int(args.light1),int(args.light2))
driver.build_schedule(args.onTime,args.... | 5,299,512 |
def _get_split_rows(input_array, num_of_sections):
""" Split array by the number of valid cells (not NaNs) on each rows
input_array : an array with some NaNs
num_of_sections : (int) number of sections that the array to be splited
return split_rows : a list of row subscripts to split the array
Split ... | 5,299,513 |
def update_with_change_set(ctx, environment, stack, verbose):
"""
Updates the stack via change set.
Updates ENVIRONMENT/STACK with prompt via change set and
description.
"""
env = get_env(ctx.obj["sceptre_dir"], environment, ctx.obj["options"])
change_set_name = "-".join(["change-set", uuid... | 5,299,514 |
def probability(df, features):
"""
Calculates the occurence probability of all the categories for every feature.
Parameters
----------
df : panda dataframe
the dataset of the population
features : dictionary
a dictionary of features with keys as feature na... | 5,299,515 |
def clip_to_timecodes(src_clip: vs.VideoNode) -> Deque[float]:
"""
Cached function to return a list of timecodes for vfr clips.
The first call to this function can be `very` expensive depending on the `src_clip`
length and the source filter used.
Subsequent calls on the same clip will return the p... | 5,299,516 |
def numeric_map(lookup, numeric_stops, default=0.0):
"""Return a number value interpolated from given numeric_stops
"""
# if no numeric_stops, use default
if len(numeric_stops) == 0:
return default
# dictionary to lookup value from match-type numeric_stops
match_map = dict((x, y) fo... | 5,299,517 |
def test_corrupted_file_error_message(fetch_kddcup99_fxt, tmp_path):
"""Check that a nice error message is raised when cache is corrupted."""
kddcup99_dir = tmp_path / "kddcup99_10-py3"
kddcup99_dir.mkdir()
samples_path = kddcup99_dir / "samples"
with samples_path.open("wb") as f:
f.write(b... | 5,299,518 |
def index():
"""
code and variables for when the page refreshes
"""
logging.info("Loading updated Website")
#calls the function which calls the functions which are needed to perform the tasks which the user specifies
manage_url()
#runs the scheduler
s.run(blocking... | 5,299,519 |
def greedy_remove(text_before, guesses_before, n_keep):
"""Remove words from the question while trying to keep the original
predictions
Args:
text_before: the text before removal
guesses_before: a dictionary of scores of guesses as the starting point
n_keep: number of words to ke... | 5,299,520 |
def cli(env, sortby, datacenter, identifier, subnet_type, network_space, ipv4, ipv6):
"""List subnets."""
mgr = SoftLayer.NetworkManager(env.client)
table = formatting.Table([
'id', 'identifier', 'type', 'network_space', 'datacenter', 'vlan_id',
'IPs', 'hardware', 'vs',
])
table.so... | 5,299,521 |
def get_all_logins():
"""Get the login details from the encrypted text store."""
cipher_suite = Fernet(FERNET_KEY)
if os.path.exists("src/bga_keys"):
with open("src/bga_keys", "rb") as f:
encrypted_text = f.read()
text = cipher_suite.decrypt(encrypted_text).decode("utf-8")
... | 5,299,522 |
def get_msa_site(pro_id, seq, site, res, verbose=True):
"""TODO: Please check the surrounding residues
"""
cnt = -1
msa_site = -1
for i in range(len(seq)):
if seq[i] != "-": # and seq[i] != "?" # and seq[i] != "X"
cnt += 1
if cnt == site:
msa_site = i
... | 5,299,523 |
def call_join(cfg, clargs, cmds, **kwargs):
"""
IMPURE
Calls ffmpeg for joining the audio mixdown and the video.
Parameters
----------
cfg: dict
Configuration dictionary.
clargs: Namespace
Command line arguments (normalized).
cmds: iter(tuple)
Iterator of commands to be pass... | 5,299,524 |
def freq_id_to_stream_id(f_id):
""" Convert a frequency ID to a stream ID. """
pre_encode = (0, (f_id % 16), (f_id // 16), (f_id // 256))
stream_id = (
(pre_encode[0] & 0xF)
+ ((pre_encode[1] & 0xF) << 4)
+ ((pre_encode[2] & 0xF) << 8)
+ ((pre_encode[3] & 0xF) << 12)
)
... | 5,299,525 |
def paypal_cancel(request):
""" Render paypal_cancel.html template when the user click cancel during a purchase process in PayPal."""
args = {'post': request.POST, 'get': request.GET}
return render(request, 'paypal/paypal_cancel.html', args) | 5,299,526 |
def enrichments(ctx, depth):
"""Generate database enrichment stats."""
for dataset in ctx.obj['datasets']:
certs_file = dataset.full_path(DatasetState.COLLECTED, 'certs', True)
hosts_file = dataset.full_path(DatasetState.COLLECTED, 'hosts', True)
if certs_file and hosts_file:
... | 5,299,527 |
def contourf(x, y, z, xlabel='x', ylabel='y', xlim=None, ylim=None,
legend=None, **kwargs):
"""Plots a filled countour plot of z vs. x and y in a single frame."""
fig, ax = plt.subplots()
lvls = np.linspace(np.min(z), np.max(z), 150)
l1 = ax.contourf(x, y, z, levels=lvls, zorder=-9, **kwarg... | 5,299,528 |
def convolve2d(imagee, kernell):
"""
This function which takes an image and a kernel and returns the convolution of them.
:param image: a numpy array of size [image_height, image_width].
:param kernel: a numpy array of size [kernel_height, kernel_width].
:return: a numpy array of size [image_heigh... | 5,299,529 |
def test_login_page_with_true_user_and_correct_password_status_code_on_dashboard_is_200(client, db):
"""Tests a view that requires authentication"""
from flask_login import current_user
# client is a pytest fixture
with client as c:
form = LoginForm()
form.username.data = 'mylyto'
... | 5,299,530 |
def text_format(text: str, text_size: int, text_color: tuple, text_font_location: str = font):
"""Template for creating text in pygame. Reformation of the size and color
Parameters:
text (str): The input text to be formatted
text_size (int): The text size of the formatted text
text_colo... | 5,299,531 |
def _weight_fn(x, weight=None, inverse=False):
"""
Implement the polynomial weight function described in the paper.
Y = X^weight and
Y = X^(1 / weight) as the inverse.
>>> _weight_fn(2)
2.2973967099940698
>>> _weight_fn(2, weight=2)
4.0
>>> _weight_fn(2, weight=2, inverse=True)
... | 5,299,532 |
def test_rename_model():
"""Test that we can rename models"""
with AnkiSimple() as a:
assert 'MyTest' in a.model_names
a.rename_model('MyTest', 'NewModelName')
assert 'NewModelName' in a.model_names
assert 'MyTest' not in a.model_names | 5,299,533 |
def id_to_name(transcription, mapping={}, composed=False):
"""Takes transcription annotated with entities and updates/outputs a dict mapping
entity identifier and counted proper names
"""
for i, token in enumerate(transcription):
# keep only proper names
if proper_entity(token):
... | 5,299,534 |
def get_all_folders(path):
"""
:param path:
:return:
"""
return [path + '/' + i for i in os.listdir(path)] | 5,299,535 |
def cgtransformation_to_rgtransform(cgT):
# type: (compas.geometry.Transformation) -> Rhino.Geometry.Transform
"""Convert :class:`compas.geometry.Transformation` to :class:`Rhino.Geometry.Transform`.""" # noqa: E501
_ensure_rhino()
M = cgT.matrix
return matrix_to_rgtransform(M) | 5,299,536 |
def fadein(clip, duration, initial_color=None):
"""
Makes the clip progressively appear from some color (black by default),
over ``duration`` seconds at the beginning of the clip. Can be used for
masks too, where the initial color must be a number between 0 and 1.
For cross-fading (progressive appea... | 5,299,537 |
def run_test_on_article(case):
"""Run the test for one article test case."""
section('Running article test for', case.article_doi())
with open(case.xml_path()) as f:
create = requests.post(SERVER_HOST + '/articles', files={'xml': f})
report('Create article', create)
url_args = {'host': SER... | 5,299,538 |
def test_register_instance():
"""is the register_instance working?"""
from app.register import ObjectRegister, make_register_instance
Register = ObjectRegister()
register_instance = make_register_instance(Register)
@register_instance
class SomeObject:
"""Our test object"""
def... | 5,299,539 |
def evaluate(weight_file_path, data_dir, output_dir, prob_thresh=0.5, nms_thresh=0.1, lw=3, display=False):
"""Detect faces in images.
Args:
prob_thresh:
The threshold of detection confidence.
nms_thresh:
The overlap threshold of non maximum suppression
weight_file_path:
A pretra... | 5,299,540 |
def test_value_tracker_bool():
"""Test ValueTracker.__bool__()"""
tracker = ValueTracker(0.0)
assert not tracker
tracker.increment_value(1.0)
assert tracker | 5,299,541 |
def count_occupied_fields(window, player):
"""" Count number of occupied fields by 'player' in 'window'. """
count = np.count_nonzero(window == player)
return 0 if count is None else count | 5,299,542 |
def covariance(x):
"""Compute array covariance matrix.
:param x: narrowband complex timeseries data for multiple sensors (row per sensor)
"""
cov_mtx = _np.zeros((x.shape[0], x.shape[0]), dtype=_np.complex)
for j in range(x.shape[1]):
cov_mtx += _np.outer(x[:,j], x[:,j].conj())
cov_mtx ... | 5,299,543 |
def fix_trimap(trimap, lower_threshold=0.1, upper_threshold=0.9):
"""Fixes broken trimap :math:`T` by thresholding the values
.. math::
T^{\\text{fixed}}_{ij}=
\\begin{cases}
0,&\\text{if } T_{ij}<\\text{lower_threshold}\\\\
1,&\\text{if }T_{ij}>\\text{upper_threshold}\\... | 5,299,544 |
def chop(sequence: Sequence[T], size: int) -> Iterator[Sequence[T]]:
"""Iterate through a given sequence in chunks of the given size."""
for idx in range(0, len(sequence), size):
yield sequence[idx:idx + size] | 5,299,545 |
def flower(ctx, tornado_argv):
"""Web based tool for monitoring and administrating Celery clusters."""
warn_about_celery_args_used_in_flower_command(ctx, tornado_argv)
apply_env_options()
apply_options(sys.argv[0], tornado_argv)
extract_settings()
setup_logging()
app = ctx.obj.app
flow... | 5,299,546 |
def get_hash_tags(sentence, be_class_verb, subj_obj_list, seed=0, max_outputs=1, nlp=None):
"""method for appending hashtags to sentence"""
verb, hashtag_list = extract_hashtags(sentence, nlp, be_class_verb, subj_obj_list)
transformation_list = []
for _ in range(max_outputs):
random.seed(0)
... | 5,299,547 |
def get_tune(tune):
"""
Convert a tune value to a frequency.
"""
if isinstance(tune,str):
try:
tune = _TUNE_A * 2.**(_NOTES[tune]/12.)
except KeyError as e:
raise ValueError("If `tune` is provided as a string, it has to be any of "+str(list(_NOTES.keys())))
... | 5,299,548 |
def delete_docs_index():
"""
Delete index `docs`.
This is usually done in preparation for restoring indexes from a snapshot backup.
"""
es = utils.get_elasticsearch_connection()
try:
logger.info("Delete index 'docs'")
es.indices.delete('docs')
except elasticsearch.exceptions... | 5,299,549 |
def aspheric_surface_equation(r, d, k, radius_of_curvature):
"""
Representation of the aspheric surface function.
"""
l = np.sqrt((radius_of_curvature * radius_of_curvature) - ((1 + k) * np.multiply(r, r)))
num = np.multiply(r, r)
den = radius_of_curvature + l
z = num / den + d
return ... | 5,299,550 |
def get_topic_rule_output(rule_name: Optional[pulumi.Input[str]] = None,
opts: Optional[pulumi.InvokeOptions] = None) -> pulumi.Output[GetTopicRuleResult]:
"""
Resource Type definition for AWS::IoT::TopicRule
"""
... | 5,299,551 |
def test():
"""Run doctests."""
import doctest
from crds.core import utils
return doctest.testmod(utils) | 5,299,552 |
def setup_config(
config_directories=None,
config_file=None,
default_filename="icap-server-opentc.yml"
):
"""Setup configuration
"""
config_found = False
config_file_path = None
if config_file:
config_file_path = config_file
if os.path.isfile(config_file_path... | 5,299,553 |
def get_matcher(obj):
"""Return an object suitable for comparing against other objects
using the "==" operator.
If special comparison handling is implemented, a MatcherObject or
MatcherTuple will be returned. If the object is already suitable
for this purpose, the original object will be returned u... | 5,299,554 |
def install_extensions(ext_root):
"""Install the c-extensions and PyObjC site dir within the plotdevice module"""
# Make sure the destination folder exists.
if not isdir(ext_root):
os.makedirs(ext_root)
# Copy all build results to plotdevice/lib dir
for extension in glob("%s/*/build/lib*"%D... | 5,299,555 |
def _ns(tag, namespace=NAMESPACES['phy']):
"""Format an XML tag with the given namespace (PRIVATE)."""
return '{%s}%s' % (namespace, tag) | 5,299,556 |
def Compose(X, Y):
"""Compose two type constructors X and Y into a single type constructor
Kind:
.. code-block::
Compose :: (* -> *) -> (* -> *) -> * -> *
That is, it takes two type constructors and one concrete type to create a
concrete type. Another way to see it is that it takes two o... | 5,299,557 |
def calculate_fitness(sequence, seq_to_fitness, key, program):
"""Calculates the fitness value of this sequence."""
seq_to_fitness[key] = polly_stats.get_regions_without_scops(sequence,
program) | 5,299,558 |
def calculate_bounds(model, rays):
"""
:param model:
:param rays: dictionary {boundary_index: reflected rays}
:return:
"""
# делаем развертку по всем границам для каждого луча для каждой границы
bound_types = []
angles = []
ray_indexes = []
# индексы границ
bound_indexes = ... | 5,299,559 |
def get(key: str, locale: str = config.get('locale')) -> Union[dict, list, str]:
"""Get the translation corresponding to that key and language"""
return container[locale][key] | 5,299,560 |
def get_entry_end_date(e):
"""Returns end date for entry"""
import dateutil.parser
return dateutil.parser.parse(e['time_end']) | 5,299,561 |
def remove_stripe_based_sorting(sinogram, size, dim=1):
"""
Algorithm 3 in the paper. Remove stripes using the sorting technique.
Work particularly well for removing partial stripes.
Angular direction is along the axis 0.
Parameters
----------
sinogram : float
2D array
... | 5,299,562 |
def index(request):
"""Chat index page."""
return HttpResponse("Testing") | 5,299,563 |
def read():
"""Read information from coulometer."""
ina = INA219(SHUNT_OHMS)
ina.configure()
print("Voltage: %.2f V" % ina.voltage())
try:
print("Current: %.2f mA" % ina.current())
"""print("Power: %.2f mW" % ina.power())"""
ina.sleep()
time.sleep(10)
ina... | 5,299,564 |
def compress_report(input_path, output_path):
"""
Description: Compress the final report file
Args:
input_path: File path to be compressed
output_path: Compressed file storage path
Returns:
"""
timestamp = time.strftime("%Y%m%d%H%M%S", time.localtime())
with tarfile.open(f"... | 5,299,565 |
def compress_counts(
counts: Dict[StateTuple, float], tol: float = 1e-6, round_to_int: bool = False
) -> CountsDict:
"""Filter counts to remove states that have a count value (which can be a
floating-point number) below a tolerance, and optionally round to an
integer.
:param counts: Input counts
... | 5,299,566 |
def allreduce_nonblocking(tensor: torch.Tensor, average: bool = True,
is_hierarchical_local=False, name: Optional[str] = None) -> int:
"""
A function that performs nonblocking averaging or summation of the input tensor
over all the Bluefog processes. The input tensor is not modifie... | 5,299,567 |
def _streaming_false_negatives(predictions, labels, weights=None,
metrics_collections=None,
updates_collections=None,
name=None):
"""Computes the total number of false positives.
If `weights` is `None`, weights default to ... | 5,299,568 |
def test_linear3d(par):
"""Create small dataset with an horizontal event and check output
contains event at correct time and correct amplitude
"""
# Data creation
v = 1
t0 = 50
theta = 0.
phi = 0.
amp = 0.6
# Create axes
t, _, x, y = makeaxis(par)
# Create data
d, d... | 5,299,569 |
def get_file_path(instance, file):
"""
Get the file path where will be stored in
:param instance: database object of this db record
:param file: file object.
:return: path of file system which will store the file.
"""
file_ext = file.split(".")[-1]
filename = "%s.%s" % (hash_file(instanc... | 5,299,570 |
def getOneFilter(psi, count, scale, mode):
""" Methdod used to visualize one filter
parameters:
psi -- dictionnary that contains all the wavelet filters
count -- key to identify one wavelet filter in the psi dictionnary
scale -- scattering scale
mode -- mode between fouri... | 5,299,571 |
def traverse_node(root, pattern):
"""
Find matches at current node, then move on to child nodes
"""
if root.text is not None:
matches = pattern.findall(root.text)
if matches:
print("Full text:")
print(root.text)
print("Matches:")
counter ... | 5,299,572 |
def hourly_sync(**kwargs):
"""
Schedule a sync every set number of hours
:param hours: how many hours to wait between syncs
:param sync: which sync function to perform
:param filename: file to sync to
"""
hours = kwargs.get('hours', 4)
filename = kwargs.get('filename', 'EloquaDB.db')
... | 5,299,573 |
def get_launch_agents_dir() -> Path:
"""Returns user LaunchAgents directory."""
launch_agents_dir = Path.home() / "Library" / "LaunchAgents"
assert launch_agents_dir.is_dir()
return launch_agents_dir | 5,299,574 |
def sample_categorical_crossentropy(y_true,
y_pred,
class_weights=None,
axis=None,
from_logits=False):
"""Categorical crossentropy between an output tensor and a target ten... | 5,299,575 |
def print_curve(q,t,r,k,D):
"""
Description:
Prints the curve (q,t,r,k,D)
Input:
q - size of prime field
t - trace of Frobenius
r - size of prime order subgroup
k - embedding degree
D - (negative) fundamental discriminant
Output:
... | 5,299,576 |
def ope(actual_series: TimeSeries,
pred_series: TimeSeries,
intersect: bool = True,
reduction: Callable[[np.ndarray], float] = np.mean) -> float:
""" Overall Percentage Error (OPE).
Given a time series of actual values :math:`y_t` and a time series of predicted values :math:`\\hat{y}_t`... | 5,299,577 |
def main():
"""Read input and print output"""
while True:
try:
number = int(input())
difference = sum(distinct_factors(number)) - (number << 1)
if difference:
if difference in range(-2, 3):
print(number, 'almost perfect')
... | 5,299,578 |
def build_constraint_matrix(cons, d):
"""
Build constraint matrix.
The constraint matrix is a matrix P that is the vertical stack
of all the preserved marginals.
Parameters
----------
cons : iter of iter
List of variable indices to preserve.
d : dit.Distribution
Distrib... | 5,299,579 |
def randomStrategy(G, k, l, randomSeed=None):
"""
title::
randomStrategy
description::
Generate random initial strategy. See compare_heuristic_script.py
for example use.
attributes::
G
Graph object (networkx)
k
Number of human patrollers... | 5,299,580 |
def eddy_loss(i, t=0.31*1e-6, w=4.29*1e-6, f=50, I_c=115):
"""
:param t: thickness of the conductor
:param w: width of the conductor
:param f: Hz
:param Ic: A
:return:
"""
return 4*mu_0**2./pi*t*w*f**2/C_RHO*I_c**2 | 5,299,581 |
def get_hashtag() -> str:
"""
Create string with special and random hashtags
"""
hash_tags = ""
for item in SPECIALHASHTAGS:
hash_tags += " " + item
hash_tags += " " + random.choice(HASHTAGS)
return hash_tags | 5,299,582 |
def count_pos_BAM(rw, path_bam_tumoral, path_bam_normal):
"""
Adds read counts of dinucleotide positions calling another function that runs samtools
:param rw: row with the variant info
:param path_bam_tumoral: path to the tumoral BAM
:param path_bam_normal: path to the normal BAM
:return: row ... | 5,299,583 |
def make_snapshot(cluster_name, path, data=None):
"""生成快照,包括快照树结构信息(zd_snapshot_tree)和快照数据(zd_snapshot)
"""
if data is None:
data = ZookeeperService.get(cluster_name, path)
# 验证节点路径是否已经存在,不存在才创建相应树结构节点
if not _is_tree_node_exists(cluster_name, path):
if path.strip() == "/":
... | 5,299,584 |
def find_centers_of_ordered_list(ls):
"""
to find label positions for plotting.
ls must be ordered!
"""
import pandas
uniqs = pandas.unique(ls)
positions = []
for u in uniqs:
idxs = [] # list of indices of corresponding values
for index, elements in enumerate(ls):
... | 5,299,585 |
def linx_upload(ctx: Context, randomize: str, expiry_days: int,
delete_key: str, access_key: str, file_path: str, filename: str):
"""
Upload the provided file.
"""
working_dir = ctx.obj['working_dir']
config: LinxConfig = ctx.obj["config"]
no_confirm_flag: bool = ctx.obj["yes"]
... | 5,299,586 |
async def get_url(bot, urls, headers={}, read_response=True, get_bytes=False):
"""Uses aiohttp to asynchronously get a url response, or multiple."""
async def fetch(url, read_method='text'):
if not url: # Why
return (None, None)
async with session.get(str(url)) as response:
... | 5,299,587 |
def translate_fun_Number(x):
"""Converts Number(string) to
__extrafunc_Number(string)
Args:
x (str): JavaScript code to translate.
Returns:
str: Translated JavaScript code.
Examples:
>>> from ee_extra import translate_fun_parseFloat
>>> translate_fun_parseFloat(x =... | 5,299,588 |
def pad_2d_array(arr, n_column, value=-1):
"""Pad 2D array with columns composed of -1.
Argument:
arr: A 2D array denoting the stimulus set.
n_column: The total number of columns that the array should
have.
value (optional): The value to use to pad the array.
Returns:
... | 5,299,589 |
def mtsdecomp_parser():
"""Command-line interface to decompress a file."""
parser = argparse.ArgumentParser(description='Decompress a raw binary file.')
parser.add_argument(
'cdata', type=str,
help='path to the input compressed binary file (.cbin)')
parser.add_argument(
'cmeta'... | 5,299,590 |
def yddot_d_z(mu, state, r_15_inv, r_25_inv):
""" Partial of x acceleration with respect to z
Args:
mu (float): three body constant
state (np.array): 6 dimensional state vector of
(x, y, z, dx, dy, dz)
r_15_inv (float): 1 / norm(r_1)^(5) where r_1 is the vector from the
... | 5,299,591 |
def decypher(text):
"""
Decypher file name into descriptive label for legend
"""
# name shortcuts
help_dict = {"h": "Target/Hunt AI", "p": "Probabilistic AI", "r": "Random AI"}
final = ""
t_split = text.split("-")
final += help_dict[t_split[0]]
# hunt/target AI branch
if t_spli... | 5,299,592 |
def get_chattering_species(atom_followed="C"):
"""
return chattering species
the chatteing reaction infomation is just for reference, will not use it
as long as the paired chattering species is provided, should be fine
better make them in the same order
"""
fast_transitions = [
# {}
... | 5,299,593 |
def kill(arg1, arg2):
"""Stops a proces that contains arg1 and is filtered by arg2
"""
from subprocess import Popen, PIPE
# Wait until ready
t0 = time.time()
# Wait no more than these many seconds
time_out = 30
running = True
while running and time.time() - t0 < time_out:
i... | 5,299,594 |
def run(ctx, problem,
hparam_set: str = None,
progress: bool = False,
cuda: bool = False,
device: str = None,
log_dir: str = None,
checkpoint_prefix: str = 'checkpoint',
**kwargs):
"""Run Experiments.
This initializes the Problem class with
a given Hyperpar... | 5,299,595 |
def describe_tags(ResourceId=None):
"""
Describes tags for a WorkSpace.
See also: AWS API Documentation
:example: response = client.describe_tags(
ResourceId='string'
)
:type ResourceId: string
:param ResourceId: [REQUIRED]
The resource ID of the reque... | 5,299,596 |
def processHostname(hostname):
"""
Check if the received hostname is a bot, based on our list
"""
if regexp_hostname.search(hostname.lower()):
return True
return False | 5,299,597 |
def format_beneficial_tags(
all_sorted_selection: List[MetadataPrioritySet]
) -> List[str]:
"""Formats the operators so that only combinations of tags that
have 'beneficial' results (ie. operators with only rarity 4, 5, 6)
are formatted into the returned list of messages."""
messages = ["Only be... | 5,299,598 |
def append_bibtex(bibtex: str, path: str = OUTPUT_PATH):
"""Append bibtex to file.
Args:
path (str): Path to bibtex file.
bibtex (str): Bibtex entry.
"""
with open(path, 'a') as fon:
fon.write(bibtex)
fon.write('\n\n') | 5,299,599 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.