content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def deps():
"""Define dependencies for `rules_rust` docs"""
rust_repositories()
stardoc_repositories() | 68,400 |
def logsumexp(matrix, dim=None):
"""
Compute log(sum(exp(matrix), dim)) in a numerically stable way.
:param matrix: input ndarray
:type matrix: ndarray
:param dim: integer indicating which dimension to sum along
:type dim: int
:return: numerically stable equivalent of np.log(np.sum(np.e... | 68,401 |
def import_book(book_path):
"""
Read book at (book_path)
"""
book = dict(name=os.path.basename(os.path.splitext(book_path)[0]))
with open(book_path, 'r') as f:
book['content'] = f.read()
region_file = to_region_file(book_path)
if os.path.exists(region_file):
with open(regio... | 68,402 |
def _run_adb(adbcommand):
"""Run the adb binary."""
cmd = [ADB]
cmd.extend(adbcommand.split())
return process.check_output(cmd) | 68,403 |
def get_hooks(additional_dirs=None):
""" Helper function to find and load all hooks. """
log.debug("get_hooks()")
if additional_dirs is None:
additional_dirs = []
hooks = annex.Annex(BaseHermesHook, [
os.path.join(BUILTIN_PLUGIN_DIR, "hooks"),
"/etc/hermes/plugins/hooks",
... | 68,404 |
def info(msg, html=False, also_console=False):
"""Writes the message to the log file using the ``INFO`` level.
If ``also_console`` argument is set to ``True``, the message is
written both to the log file and to the console.
"""
write(msg, 'INFO', html)
if also_console:
console(msg) | 68,405 |
def _label_constraint(key, value):
"""
Returns a label constraint for host limit 1
:param key: The key fo the label
:param value: The value of the label
"""
return task_pb2.Constraint(
type=1,
labelConstraint=task_pb2.LabelConstraint(
kind=1,
condition=2,
... | 68,406 |
def trim(infile, outfile):
"""Trim video with ffmpeg. Returns tuple of filename and dict of trim times"""
if not pyask.yes_no("Does the video need to be trimmed?", default="yes"):
return (infile, {"start": 0, "end": None})
start, end = get_trim_times()
run(
[
"ffmpeg",
... | 68,407 |
def u3u2(u3):
"""
feet&inch to inch
"""
f = u3[0]
if f == '': f = 0
else: f = int(f)
i = u3[1]
if i == '': i = 0
else: i = round(convert_to_float(u3[1]), 2)
u2 = f*12 + i
return str(u2) | 68,408 |
def is_csv(path):
"""Is a file a CSV file extension?"""
(filename, ext) = os.path.splitext(path)
return ext.lower() in ['.csv', '.CSV'] | 68,409 |
def QA_SU_save_etf_day(engine, client=DATABASE):
"""save etf_day
Arguments:
engine {[type]} -- [description]
Keyword Arguments:
client {[type]} -- [description] (default: {DATABASE})
"""
engine = select_save_engine(engine)
engine.QA_SU_save_etf_day(client=client) | 68,410 |
def create(policy_backbone: ModelFactory, value_backbone: ModelFactory):
""" Vel creation function """
return DeterministicPolicyModelFactory(
policy_backbone=policy_backbone, value_backbone=value_backbone
) | 68,411 |
def main(args: Namespace) -> bool:
"""
The Function to process the data at the given path using the given transformation rules
and store them at given destination path. if any file fails at transformation level,
it will be stored in error path
Args:
args (Namespace): Argument Namespace con... | 68,412 |
def test_read_flash_hex(mock_read_flash):
"""Test read_flash_hex() with default arguments."""
data_bytes = bytes([x for x in range(256)] * 4)
intel_hex = IntelHex()
intel_hex.frombytes(data_bytes)
ihex_str = ihex_to_str(intel_hex)
mock_read_flash.return_value = (0, data_bytes)
result = cmds... | 68,413 |
def rising_edge(signal):
"""
FUNCTION: rising_edge(a str)
a: signal name
Rising edge wait function.
"""
global sim_time_queue
if (sim_time > 0):
signal_cur_value = 0
signal_prev_value = 0
... | 68,414 |
def alt(*args: Pat) -> Pat:
"""Matches one of the given choices.
>>> alt() # will never match
alt()
>>> alt('a')
'a'
>>> alt(alt('b', 'c'), 'd')
alt('b', 'c', 'd')
"""
choices = []
for a in args:
if isinstance(a, Alt):
choices.extend(a.choices)
else... | 68,415 |
def batch_get_value(ops):
"""Returns the value of more than one tensor variable.
# Arguments
ops: list of ops to run.
# Returns
A list of Numpy arrays.
"""
if ops:
return get_session().run(ops)
else:
return [] | 68,416 |
def calculate_interest_years(starting_amount, requested_amount, interest_rate, stipend_rate):
"""
If I want X in the bank, how long will it take?
:param starting_amount: The amount of money the bank has to start with.
:type starting_amount: double
:param requested_amount: The amount requested in the... | 68,417 |
def list_collections(config: Config, verbose):
"""Return the list of available collections in the service provider."""
if verbose:
click.secho(f'Server: {config.url}', bold=True, fg='black')
click.secho('\tRetrieving the list of available coverages... ',
bold=False, fg='black... | 68,418 |
def short_information(title, index=0):
"""
Takes in track information and returns everything as a short formatted String.
Args:
title (str): track title string
index (str): optional track number string
Returns:
A short formatted string of all track information.
"""
if ... | 68,419 |
def _reduction_a_cell_do(ip, p, filters, net_type, cell_num, total_num_cells, total_training_steps, do_p=0.3, block_id=None):
"""Adds a Reduction cell for NASNet-A (Fig. 4 in the paper).
Args:
ip: Input tensor `x`
p: Input tensor `p`
filters: Number of output filters
block_id: S... | 68,420 |
def post_processor(provider: str = None, parser: str = None,
provider_parser_list: List[Dict] = None) -> Callable:
"""
Decorator that register function for post processing. You can insert provider and parser or
list of dict that contain more providers. Dict must have two keys provider and... | 68,421 |
def validate_ecs_cli_version(ecs_cli_path: str):
"""
Validate the version of ecs-cli
"""
ecs_cli_version_str = subprocess.check_output([ecs_cli_path, "--version"],
text=True)
# Sample output:
# ecs-cli version 1.20.0 (7547c45)
if f" {ECS_CL... | 68,422 |
def _main():
"""
Run functions in this file in a subprocess and prints to stdout the results.
"""
data = {}
message = ""
if len(sys.argv) == 2:
func_name = sys.argv[-1]
func = globals().get(func_name, None)
if func:
try:
data, message = func()... | 68,423 |
def AddAttachedCertificatesFlagsToParser(parser):
"""Adds flags describing certificate update without resource args."""
is_clear_certificates = base.Argument(
'--clear-certificates',
help='Removes all certificates from the entry',
action='store_true')
group = base.ArgumentGroup(
help='Arg... | 68,424 |
def plot_inplane_vs_bias(
inplane_field: np.ndarray,
bias: np.ndarray,
dV_dI: np.ndarray,
savgol_windowl: Optional[int] = None,
savgol_polyorder: Optional[int] = None,
cvmax: Optional[float] = None,
cvmin: Optional[float] = None,
bias_limits: Optional[np.ndarray] = None,
in_field_lim... | 68,425 |
def vmaddrelu(x, y, z):
"""
calculate relu(x * z + y), only support float16, float32.
Args:
x (tvm.tensor.Tensor): input.
y (tvm.tensor.Tensor): input.
z (tvm.tensor.Tensor): input.
Returns:
tvm.tensor.Tensor, relu(X * Z + Y).
"""
return multiple_elewise_op(x,... | 68,426 |
def setup(hass, config):
"""Set up the keyboard_remote."""
config = config.get(DOMAIN)
keyboard_remote = KeyboardRemote(hass, config)
def _start_keyboard_remote(_event):
keyboard_remote.run()
def _stop_keyboard_remote(_event):
keyboard_remote.stop()
hass.bus.listen_once(EVENT... | 68,427 |
def _write_metadata(output_fp, metadata, metadata_args):
""" Write the metadata to a file pointer.
Parameters
----------
output_fp : file like
the file pointer to write to
metadata : dict
the metadata to write
metadata_args : MetadataArgs
the metadata args
Returns
... | 68,428 |
def _compute_taylor(data_input):
"""Algorithm: atanh(x) = x + x^3/3 + x^5/5 + x^7/7"""
taylor_para = [0, 1.0, 0, 1/3.0, 0, 1.0/5, 0, 1.0/7]
# x^2
data_mul_2 = topi.multiply(data_input, data_input)
# 1/5 + x^2/7
data_mul_2_7 = topi.multiply(data_mul_2, tvm.const(taylor_para[7], "float32"))
... | 68,429 |
def infer_feature_types(data, feature_types=None):
"""Create a Woodwork structure from the given list, pandas, or numpy input, with specified types for columns.
If a column's type is not specified, it will be inferred by Woodwork.
Arguments:
data (pd.DataFrame): Input data to convert to a Woodw... | 68,430 |
def apply_token_replay(log, net, initial_marking, final_marking, parameters=None):
"""
Calculates all metrics based on token-based replay and returns a unified dictionary
Parameters
-----------
log
Trace log
net
Petri net
initial_marking
Initial marking
final_mar... | 68,431 |
def add_css_file_extension(name):
"""
Appends the CSS file extension to a string.
:return: name with '.css' append at the end append at the end
:rType: string
"""
return '%s.css' % name | 68,432 |
def get_data_hlsp_everest(obsid):
"""
Given a EVEREST observation ID, returns the lightcurve data.
:param obsid: The EVEREST observation ID to retrieve the data from.
:type obsid: str
:returns: JSON -- The lightcurve data for this observation ID.
Error codes:
From parse_obsid_hlsp_everes... | 68,433 |
def update_subscription_instances_chunk(subscription_ids: List[int]):
"""
分片更新订阅状态
"""
subscriptions = models.Subscription.objects.filter(id__in=subscription_ids, enable=True, is_deleted=False)
for subscription in subscriptions:
try:
if subscription.is_running():
... | 68,434 |
def try_protection(var, target, attacker, attacker_role, reason):
"""Attempt to protect the player, and return a list of messages or None."""
prots = []
for protector, entries in PROTECTIONS.get(target, {}).items():
for scope, protector_role in entries:
if attacker_role in scope:
... | 68,435 |
def _get_position(a, n):
""" returns position of substring :n: as "start", "end" or "middle" """
position = a.index(n)
if position == 0:
return ("start", position)
elif position+len(n) == len(a):
return ("end", position)
else:
return ("middle", position) | 68,436 |
def data_factory(value, encoding='UTF-8'):
"""Wrap a Python type in the equivalent C AMQP type.
If the Python type has already been wrapped in a ~uamqp.types.AMQPType
object - then this will be used to select the appropriate C type.
- bool => c_uamqp.BoolValue
- int => c_uamqp.IntValue, LongValue, D... | 68,437 |
def write_feeds(server: Server, s_collection: Collection = None):
"""Writes a server's rss feeds to database
Parameters
----------
server: Server
the server instance
s_collection: Collection
(optional) the server collection to write to
"""
if not s_collection:
s_col... | 68,438 |
def AllTokens():
"""Retrieves all descendants of pygments.token.Token."""
def Traverse(token):
for tok in token.subtypes:
yield tok
for sub_token in Traverse(tok):
yield sub_token
return sorted(Traverse(pygments.token.Token)) | 68,439 |
def init_qt_logger(logger: Logger, name: str, update_signal: pyqtBoundSignal):
"""
Redirects the logger to QT widget.
Needs to be called when GUI objects are available.
update_signal needs str as argument.
"""
qt_handler = QtLogHandler(update_signal)
qt_handler.set_name(name)
log... | 68,440 |
def previous(values, elements, scope=None, strict=True):
"""Return closest previous (index, elem) of values withing scope.
Assumption:
values and elements are sorted
"""
# Init iterator on elements
elem_indexes = enumerate(elements)
index, elem = next(elem_indexes)
try:
nin... | 68,441 |
def space_normalize(root, text=None, standoffs=None):
"""
Eliminates multiple consequtive spaces and normalizes newlines
(and other space) into regular space.
"""
if text is None or standoffs is None:
text, standoffs = text_and_standoffs(root)
# TODO: this is crude and destructive; imp... | 68,442 |
def _load_prefs() -> Dict[str, Any]:
"""Load user preferences from TOML and return as a dict
:return: dict containing user preferences
"""
try:
return dict(toml.load(PREFERENCES))
except (IOError, toml.TomlDecodeError):
log.info(f"{PREFERENCES} could not be opened or decoded for pr... | 68,443 |
def slice(from_index, to_index, list_or_string):
"""Returns the elements of the given list or string (or object with a slice
method) from fromIndex (inclusive) to toIndex (exclusive).
Dispatches to the slice method of the third argument, if present"""
return list_or_string[from_index:to_index] | 68,444 |
def wr_saved():
"""Output the last sequence of characters saved from the input string"""
dot_out(saved) | 68,445 |
def make_app():
"""Create page handlers and create a Tornado app."""
handlers = create_route_handlers(config.pages)
settings = {
"static_path": config.static_path,
"template_path": config.template_path,
"debug": True
}
return tornado.web.Application(handlers, **settings) | 68,446 |
def accuracy(output, target):
"""Computes the precision@k for the specified values of k"""
# batch_size = target.size(0) * target.size(1) * target.size(2)
_, pred = output.max(1)
pred = pred.view(1, -1)
target = target.view(1, -1)
correct = pred.eq(target)
# correct = correct[target != 255]
... | 68,447 |
def parse_identification_method(tag, type):
"""
parses id_marc_tag tag attrib for proper handling in pymarc obj
args:
tag str (marc tag)
type str (standard, control field)
return:
(tag, subfield) tuple
"""
if type == 'standard':
tag_to_check = tag[:3]
subf... | 68,448 |
def backup(user, dest):
"""Performs a backup of all the repos in user's GitHub account on dest
"""
gh = pygithub3.Github()
repos = gh.repos.list(user=user, type='all')
for repo in repos.all():
repo_path = os.path.join(dest, repo.name)
LOG.info("Backing up repository {}".format(repo.n... | 68,449 |
def entropy_from_indexes(indexes: List[int], lang: str) -> Entropy:
"""Return the entropy from a list of word-list indexes.
Return the entropy from a list of integer indexes into
a given language word-list.
"""
n = _wordlists.language_length(lang)
entropy = 0
for i in indexes:
... | 68,450 |
def decompress_G2(p: G2Compressed) -> G2Uncompressed:
"""
Recovers x and y coordinates from the compressed point (z1, z2).
"""
z1, z2 = p
c_flag1, b_flag1, a_flag1 = get_flags(z1)
# c_flag == 1 indicates the compressed form
# MSB should be 1
if not c_flag1:
raise ValueError("c_f... | 68,451 |
def lnprob(lnparams, *args):
""" The ln-probability function.
Calculates the logarithmic posterior probability (likelihood times prior)
of the model given the data.
Args:
lnparams (array): The parameter array containing Equivalent
Evolutionary Point (EEP), age in log10(yrs), metall... | 68,452 |
def VerifyCbiEepromWpStatus(dut, cbi_eeprom_wp_status,
ec_bypass_cbi_eeprom_wp_check):
"""Verify CBI EEPROM status.
If cbi_eeprom_wp_status is Absent, CBI EEPROM must be absent. If
cbi_eeprom_wp_status is Locked, write protection must be on. Otherwise, write
protection must be off.
... | 68,453 |
def coding_strand_to_rna(strand):
"""returns the coding strand to the rna strand (T --> U)"""
strand = strand.upper().replace("T","U")
return strand | 68,454 |
def make_2d(
x_seq, y_seq, alphabet, file_name, out_dir, labels, matplot, pil, array_flag
):
"""
fun plots 2D metrics of watson-crick binding
rules of sequence x and y as heatmap
parameters
x_seq=sequecne on x axis
y_seq=sequence on y axis
alphabet=2D matrix
file_name=image file nam... | 68,455 |
def _process(proc_data):
"""
Final processing to conform to the schema.
Parameters:
proc_data: (Dictionary of Lists) raw structured data to process
Returns:
List of Dictionaries. Structured data to conform to the schema.
"""
for entry in proc_data:
# add timestamps
... | 68,456 |
def load_rsa_key(filename):
"""
Function to get an RSA key from the specified file for Paramiko.
"""
return paramiko.RSAKey.from_private_key_file(prepend_home_dir(filename)) | 68,457 |
def merge_grid(proj_path):
"""This function concatinates the shapefiles which contains the keyword '33kV' and '66kV'
:param proj_path:
:return:
"""
current = os.getcwd()
os.chdir(proj_path)
files = os.listdir(proj_path)
shapefiles = []
for file in files:
if file.endswith('.sh... | 68,458 |
def F_score(xs, ys, beta=0.01):
"""
Returns the F score described here: http://en.wikipedia.org/wiki/F1_score
for list `xs` against to the list `ys`.
Make beta smaller to give more weight to the precision.
"""
p = precision(xs, ys)
r = recall(xs, ys)
if (p + r) == 0:
return 0, 0... | 68,459 |
def get_db_len(session_id):
"""
Args:
session_id (int): id of a user's session
Returns:
int: how many songs the user has rated in a specific session
"""
cursor, connection = open_db_connection()
try:
cursor.execute(
f"""select count(*)
fro... | 68,460 |
def create_addr_record(addr_file: Path) -> clusterlib.AddressRecord:
"""Return a `clusterlib.AddressRecord`."""
f_name = addr_file.name.replace(".addr", "")
basedir = addr_file.parent
vkey_file = basedir / f"{f_name}.vkey"
skey_file = basedir / f"{f_name}.skey"
if not (vkey_file.exists() and sk... | 68,461 |
def graph_to_entities_json(g):
"""
Converts the given graph to entities JSON.
:param g: a graph
:return: an array of JSON
"""
entities = []
for u, v in g.edges():
entity = {
"Device": "",
"IP": "",
"Identity": "",
"Location": "",
... | 68,462 |
def create_annotation_ce_target(creator: str, field: str = None, fragment: str = None):
"""Return a mutation for making an AnnotationCETarget.
An AnnotationCETarget is a node that can be used for a
web Annotation (https://www.w3.org/TR/annotation-model)
as the target field, when the target refers to a n... | 68,463 |
def sg_put(gid, chid, value):
"""perform a `put` within a synchronous group.
This `put` cannot wait for completion or for a a callback to complete.
"""
if not isinstance(chid, dbr.chid_t):
raise ChannelAccessException("not a valid chid!")
ftype = field_type(chid)
count = element_count(... | 68,464 |
def do0(*items):
"""Like do, but return the value of the first item.
Examples::
y = do0(17,
assign(x=42),
lambda e: print(e.x),
print("hello from 'do0'"))
assert y == 17
y = do0(assign(x=17), # the first item can be an assignment, too
... | 68,465 |
def TransformScope(r, *args):
"""Gets the /args/ suffix from a URI.
Args:
r: A URI.
*args: Optional URI segment names. If not specified then 'regions', 'zones'
is assumed.
Returns:
The URI segment after the first /*args/ in r, the last /-separated
component in r if none found.
Example... | 68,466 |
def variational_mfvi_sample(n_sample, qf_mean, qf_sdev,
mfvi_mixture=False, mixture_par_list=None,
**kwargs):
"""Generates f samples from GPR mean-field variational family.
Args:
n_sample: (int) number of samples to draw
qf_mean: (tf.Tenso... | 68,467 |
def recode_mark(mark, mark_shouldbe, no_mark="XX"):
"""A little helper function to remap clips to standard values that can
then be parsed.
Replaces BP with LPRP so ADBP becomes ADLPRP.
Arguments:
- `mark`: A mark string returned by the glfc database.
- `mark_shouldbe`: a dictionary mapping va... | 68,468 |
def parse_rxn_class_file(job_path):
""" Read the class dictionary
"""
if os.path.exists(os.path.join(job_path, CLA_INP)):
print(' class.dat found. Reading contents...')
cla_str = ptt.read_inp_str(job_path, CLA_INP, remove_comments='#')
cla_dct = _build_cla_dct(cla_str)
else:
... | 68,469 |
def select_copy_number(query, query_id):
"""
Execute copy-number query and return results
"""
cur = connection.cursor()
cur.execute(query, (query_id,))
rows = cur.fetchall()
values = []
for row in rows:
value = CopyNumberValue(entrez_gene_id=row[0], depmap_id=row[1], value=r... | 68,470 |
def remove_extension_from_filename(filename: str) -> str:
"""
Return a filename without its extension
"""
return os.path.splitext(filename)[0] | 68,471 |
def read_single_camera_description(filename, camera_name):
"""
Read a specific camera description from a DL1 file
Parameters
----------
filename: str
camera_name: str
Returns
-------
`ctapipe.instrument.camera.description.CameraDescription`
"""
geom = read_single_camera_geo... | 68,472 |
def mostrarPantallaJuegoTerminado(supPant, j1nombre, j1puntaje, j2nombre, j2puntaje):
"""Dibuja la pantalla de juego terminado sobre supPant, mostrando los nombres y puntajes de los jugadores. Esta pantalla también
tiene estrellas rojas rotantes, y permanece hasta que el usuario pulse una tecla."""
j1pun... | 68,473 |
def _get_remains(courses):
""":param courses: list of (id, num) pair"""
return map(int, [i[u'课余量'] for i in val]) | 68,474 |
def _update_doc(doc):
"""Add a list of plugins to the module docstring, formatted as
a ReStructuredText table.
"""
from textwrap import wrap
info = [(p, plugin_info(p)) for p in plugins() if not p == 'test']
col_1_len = max([len(n) for (n, _) in info])
wrap_len = 73
col_2_len = wrap_l... | 68,475 |
def preprocess(infile, outfile=sys.stdout, defines=None,
force=0, keepLines=0, includePath=None, substitute=0,
contentType=None, contentTypesRegistry=None,
__preprocessedFiles=None):
"""Preprocess the given file.
"infile" is the input path.
"outfile" is the outp... | 68,476 |
def test_compile_regex_with_escaped_backslash():
"""Raises exception when trying to compile regex with escaped backslash."""
regex = "N\\OW"
with pytest.raises(SystemExit):
compile_regex(regex) | 68,477 |
def IDO(
directed = False, preprocess = "auto", load_nodes = True, load_node_types = True,
load_edge_weights = True, auto_enable_tradeoffs = True,
sort_tmp_dir = None, verbose = 2, cache = True, cache_path = None,
cache_sys_var = "GRAPH_CACHE_DIR", version = "2017-11-03", **kwargs
) -> Graph:
"""Ret... | 68,478 |
def printCopyrightSourceComments(fp):
"""Print Khronos CC-BY copyright notice on open file fp.
Writes an asciidoc comment block, which copyrights the source
file."""
print('// Copyright (c) 2014-2019 Khronos Group. This work is licensed under a', file=fp)
print('// Creative Commons Attribution 4.0 ... | 68,479 |
def scrape_detail(url):
"""
scrape detail page and return its html
:param page: page of detail page
:return: html of detail page
"""
return scrape_page(url) | 68,480 |
def parse_command_line():
"""Parse the command-line options."""
formatter_class = argparse.ArgumentDefaultsHelpFormatter
description = 'Clang-format: Allow CHKERRQ to be on same line.'
parser = argparse.ArgumentParser(description=description,
formatter_class=formatte... | 68,481 |
def test_torchscript_properties(modelclass):
"""Test that scripted LightningModule has unnecessary methods removed."""
model = modelclass()
script = model.to_torchscript()
assert not hasattr(model, "batch_size") or hasattr(script, "batch_size")
assert not hasattr(model, "learning_rate") or hasattr(s... | 68,482 |
def build_phone_encoder(features, speaker_labels, feature_length, params, endpoints, reuse_variables, is_training=False):
"""Build encoder for phone latent variable.
Use the tdnn and share the same structure in the lower layers.
Args:
features: the input features.
speaker_labels: the speake... | 68,483 |
def from_probit(func):
"""
Evaluate a function that samples points in probit space and return these points after transforming them to natural space
"""
def f_transf(ref, *args, **kwargs):
y = func(ref, *args)
return transform_from_probit(y, ref.bounds)
return f_transf | 68,484 |
def token_is_valid(token):
"""Validate a checkout token."""
if token is None:
return False
if isinstance(token, UUID):
return True
try:
UUID(token)
except ValueError:
return False
return True | 68,485 |
def shortest_path(map, dest, default_value = 0, block_value = 1):
""" Find shortest-path field
:param map: the proposed map (2-d)
:param dest: the goal, a point
:param default_value: the identifier for default cell
:param block_value: the identifier for block cell
:return: floor field and a dis... | 68,486 |
def _ast_eval(node):
"""
Performs an algebraic syntax tree evaluation of a unit.
"""
operators = {ast.Add: op.add, ast.Sub: op.sub, ast.Mult: op.mul,
ast.Div: op.truediv, ast.Pow: op.pow, ast.BitXor: op.xor,
ast.USub: op.neg}
if isinstance(node, ast.Num): # <number>
return ... | 68,487 |
def getWriteOutColour(
colour: Iterable[Any], convertType: type = int, multiplier: int = 255
) -> list[Any]:
"""getWriteOutColour"""
return [convertType(col * multiplier) for col in colour] | 68,488 |
def cache(
backend: "redis_helper.RedisHelper",
expire: Optional[int] = None,
namespace: str = NAMESPACE,
alias: Optional[str] = None,
json_response: Type[JSONResponse] = JSONResponse,
get_key_func: Optional[Callable[[Request], Awaitable[str]]] = None,
after_cache_response_list: Optional[Lis... | 68,489 |
def create_tsmp_placeholders(
name: str,
model_start_time: pd.Timestamp,
end_time: pd.Timestamp,
run_dir: str,
tsmp_config: Dict[str, Any],
cycle_config: Dict[str, Any]
) -> Dict[str, Any]:
"""
This function creates a dictionary of placeholders which are inserted
... | 68,490 |
def predict_model(video_fn, model,
start_frame=0, end_frame=30,
plot_every_x_frames=5):
"""
Given a video and model, starting frame and end frame.
Predict on all frames.
"""
fn = video_fn.split('.')[0]
label = metadata.loc[video_fn]['label']
original = me... | 68,491 |
def display_sidebar(all_devices, state):
"""
Display sidebar information.
"""
st.sidebar.subheader("Device selection")
state.selected_device = st.sidebar.selectbox(
"Selected device",
all_devices,
index=all_devices.index(state.selected_device if state.selected_device else Non... | 68,492 |
async def launch_as_tasks():
"""
The naive version is basically the equivalent of blocking after each put
or get. With this version we launch put_object/get_object as asyncio Tasks
by appending to a list then doing asyncio.gather to run them concurrently:
https://docs.python.org/3/library/asyncio-ta... | 68,493 |
def getIdsOfCities(session, all=False):
"""Gets the user's cities
Parameters
----------
session : ikabot.web.session.Session
Session object
all : bool
boolean indicating whether all cities should be returned, or only those that belong to the current user
Returns
-------
... | 68,494 |
def print_2d(exp_name, num_winners=0, mask=False,
angle=0, reverse=False, update=False, values="default", coloring="purple",
num_elections=800, winners_order="positionwise_approx_cc", main_order="", metric="positionwise",
saveas="map_2d"):
""" Print the two-dimensional embeddi... | 68,495 |
def tx_collector():
"""A helper to deduplicate transactions"""
def snowflake():
txids = set()
txs = []
while True:
tx = yield txs
if tx:
if tx.id not in txids:
txids.add(tx.id)
txs.append(tx)
... | 68,496 |
def initialize_model_from_run(run_id):
"""
Initialized a model based on a run_id (i.e., using the exact
same parameter settings)
Parameters
----------
run_id : int
The Openml run_id
Returns
-------
model : sklearn model
the scikitlearn mo... | 68,497 |
def make_cost_function(file_name='cubic.dat', minimizers=None,
max_runtime=None):
"""
Helper function that returns a simple fitting problem
"""
options = Options()
if minimizers:
options.minimizers = minimizers
if max_runtime:
options.max_runtime = max_runt... | 68,498 |
def display_chunk():
""" Print the chunk from filename at position DiskFixer style """
display_offsets()
display_hexadecimal_content()
display_textual_content() | 68,499 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.