content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def dunder_partition(key):
"""Splits a dunderkey into 2 parts
The first part is everything before the final double underscore
The second part is after the final double underscore
>>> dunder_partition('a__b__c')
>>> ('a__b', 'c')
"""
parts = key.rsplit('__', 1)
return tuple(parts)... | afd33d6e03de982bb7b71b0e7817fc5f1ae7207f | 667,993 |
import random
def random_marker():
""" A random marker used to identify a pytest run.
Some tests will spawn a private chain, the private chain will be one or
more ethereum nodes on a new subprocesss. These nodes may fail to start on
concurrent test runs, mostly because of port number conflicts, but e... | 37f0f7d44a27f4aecb06acdb8685b2103aa05ea1 | 667,994 |
def is_payload_valid(payload, rules):
"""
Checks if a payload is valid based on some predefined rules
args: payload, rules
ret: is_valid
"""
if type(payload) != dict:
return False
for rule in rules:
if type(rule) == list:
count = 0
for nested_rule i... | ba86d8e68a7f594fc2d650554a593dcf002d352f | 667,995 |
def fallback_handler(handler_input):
"""
Purpose:
Handler for cancelling or stopping the skill
Note: AMAZON.FallbackIntent is only available in en-US locale.
This handler will not be triggered except in that locale,
so it is safe to deploy on any locale.
Args:
handle... | 54af8815d59059e8c34139ded0ab99235688b532 | 667,996 |
from typing import List
from typing import Dict
from typing import Any
def patterns() -> List[Dict[str, Any]]:
"""Patterns for testing. Semi-duplicates purposeful."""
patterns = [
{"label": "DRUG", "pattern": "Zithromax", "type": "fuzzy", "id": "Antibiotic"},
{"label": "GPE", "pattern": "Mahwa... | 4787042d57c06356cd0cf1c3e700b04f28e9fe00 | 667,997 |
def strip_prefix(key):
"""Remove "arg" or "aux" prefix for all the keys in the params file.
The prefix are kept in the params for compatibility reason. To use the saved
model in mxnet, see https://gist.github.com/pierric/b4da8783755de763bff13aea5f5e900d
Arguments:
key {str} -- a key in the... | f3852a6a4504d9ddab1482d8c1144bc187b17ae6 | 667,998 |
import argparse
def parseCommandLineArguments():
"""
Parses the arguments provided through command line.
Launch python transfer_genomic_nucl_counts_to_transcriptome.py --help for more details
"""
parser = argparse.ArgumentParser(prog="transfer_genomic_nucl_counts_to_transcriptome.py",description="... | abae683c6216a92d0849f776ec2543d309501956 | 667,999 |
from typing import List
from typing import Tuple
import collections
def shortest_path_grid(grid: List[List[int]], start:Tuple[int, int], end:Tuple[int, int]):
"""
Finds shortest path in a grid of mxn using BFS and returns it's path length including start and end.
Uses direction vetors and each cell treats... | 249fb474764a4d19abad33fb887e649138f30301 | 668,000 |
def intercalate_sigma_into_peak_params(reduced_peak_params, sigmas):
"""
Insert the sigmas back into reduced_peak_params to form peak_params.
To describe N peaks,
Input
-----
reduced_peak_params : A vector of length = 2*N.
Every odd element describe an amplitude,
... | 388f277e3c0f258a0b18a42efb225a8657319531 | 668,001 |
from functools import reduce
def union_axis(*dfs, axis='index'):
"""DataFrames中某个轴的并集"""
if isinstance(dfs[0], list):
dfs = dfs[0]
if axis == 'index':
axis_list = [df.index for df in dfs]
else:
axis_list = [df.columns for df in dfs]
new_axis = reduce(lambda x, y: x.union(y)... | 10a9366f2a2b93a5677bd9df88950775888bdd55 | 668,002 |
from datetime import datetime
def parse_iso_date(txt: str) -> datetime:
"""Parse a datetime in ISO format."""
return datetime.strptime(txt[:19], "%Y-%m-%d %H:%M:%S") | 840fb5865ec3b86bdb1811ae117c8db9de8ec9fb | 668,003 |
def toggle_enable_template(form, args, blueprint_template):
"""Logic for activating and deactivating a blueprint template"""
if form.is_enabled.raw_data:
blueprint_template.is_enabled = form.is_enabled.raw_data[0] # WTForms Issue#451
else:
blueprint_template.is_enabled = False
if ar... | ff5a0eab16fbbd8ed363c5595a514a410bc578aa | 668,004 |
import uuid
def id_from_name(name):
"""Generate a UUID using a name as the namespace
:type name: str
:rtype: str
"""
return str(uuid.uuid3(uuid.NAMESPACE_DNS, name)).upper() | b91f2449ae1d13c612d4e653fc07de3c08cf4dd5 | 668,005 |
import subprocess
import sys
import os
def subprocess_run_helper(func, *args, timeout, **extra_env):
"""
Run a function in a sub-process
Parameters
----------
func : function
The function to be run. It must be in a module that is importable.
*args : str
Any additional comman... | 71a8ca86b25c2b10a1a2e1393881b8330a179e79 | 668,007 |
def createTemplate(prevKeypoint, currKeypoint, frame, scale=1.2/9*20):
"""
This function creates a template around the location of a keypoint in the
current frame, based on the size of a keypoint in the previous frame.
The (seemingly random) size is taken from the paper.
"""
# Create function that limits... | 02e6cb3fe5c829effc2155b273cf792c7dadb0ff | 668,008 |
def position_dictionary(graph):
"""
can be used by nx.draw to position nodes with matplotlib. This is not used in the general functioning of
the spacing app but is useful for visual testing. If you have a networkx graph G, then you can use it like:
nx.draw(G,pos=position_dictionary(G)) To see the res... | 0d476b74ee69096a5cbb3ed6aedf446682e26356 | 668,009 |
from datetime import datetime
def formatted_birth_date(date, formatted):
"""
This function formats the given date to the selected format.
"""
if formatted == "DD/MM/YYYY": # Input Date: "YYYY-MM-DD"
date = datetime.strptime(date, "%Y-%m-%d")
date = [str(date.day), str(date.month), str... | 0efff411d7abc408df3e9f6376d9201b628134e4 | 668,010 |
def profit_filler(df, max_length):
"""Takes a dataframe and ensures all the profit rows are the same length for
adding together profits over the number of games, shorter rows will be
filled with their final value.
example: row 0 = [1,2,3,4], row 1 = [1,2,3] -> row 0 = [1,2,3,4],
row 1 = [1,2,3,3]
... | 0cc6e787f46fffdbc9890da408ead248d49e1ac6 | 668,011 |
def progress_bar(val, val_max, val_min=0, prefix="", suffix="", bar_len=20):
"""
Displays a progress bar in the simulation tree.
:param val: current value
:param val_max: maximum value
:param val_min: minimum value
:param prefix: marker for the completed part
:param suffix: marker for the in... | 141fe08ad0b6aa4222d739e0399b60078297acde | 668,012 |
def iteratively_query_dict(path: list, d: dict):
"""
Query a multidimensional dict with a list as the key.
:param path:
:param d:
:return:
"""
tmp = d
for key in path:
tmp = tmp[key]
return tmp | d006e88642eb3413e7e8ee69c269e51e13977de5 | 668,013 |
def jobparams_postfiltering(value, exclusions={}):
"""
Perform post-filtering of raw job parameters.
Any items in the optional exclusion list will be added (space separated) at the end of the job parameters.
:param value: job parameters (string).
:param optional exclusion: exclusion dictionary from... | 190570ba177b606719e897e959b2508d17164163 | 668,014 |
def _get_id2line(team_stats):
"""
team_stats: {
'headers':[],
'data': [[],[]] # two teams, don't know which is home/away
}
"""
headers = team_stats['headers']
id_loc = headers.index('TEAM_ID')
data0 = team_stats['data'][0]
data1 = team_stats['data'][1]
... | 43835bc420b46bf23034e245cdfe0301d4ebe42b | 668,016 |
def gridsize(nf):
"""
Fuzzy logic to determine optimal gridsize from full screen proportion
"""
col_row = [ [2,2], [2,3], [3,2], [3,3], [3,4], [4,3], [4,4],
[4,5], [5,4], [5,5], [5,6], [6,5], [6,6], [7,6], [6,7], [7,7], [8,7], [7,8], [8,8], [9,8], [8,9], [9,9] ]
c=9
r=9
for cr, rr in co... | c465a025c448491adb820f407c2793cb265ded73 | 668,017 |
def doble_mas_comun(matriz_dobles: list) -> tuple:
"""
Función 6 – Doble programa más popular.
Indica cuál es el doble programa más popular entre los estudiantes.
Es equivalente estar inscrito en el Programa1 y tener un doble programa con el programa2,
que estar inscrito en el Programa2 y hacer dobl... | 5b9ef2e1bdbc1fed055e4410434c557f82106d53 | 668,018 |
from textwrap import dedent
def indent(text, spaces=4, strip=False):
"""Return the ``text`` indented by the given number of ``spaces``."""
if not hasattr(text, 'splitlines'):
text = '\n'.join(text)
if strip:
text = dedent(text)
prefix = ' ' * spaces
output = '\n'.join(prefix + lin... | 3e715643eb367061cb13cdf9162e11004a732346 | 668,019 |
def fseq_sign_changes(f, arr, i):
"""
Checks whether a sequence's i'th image through a function f has different
sign from the i+1'th element
"""
return f(arr[i]) * f(arr[i+1]) < 0 | 61df4cda92281fe44364036a90db41ab3f2a8f5d | 668,020 |
def createDataSet():
"""
获取测试数据集
:return:
"""
dataSet = [[1, 1, 1, 1, 'yes'],
[1, 0, 1, 1, 'no'],
[2, 2, 1, 1, 'yes'],
[2, 2, 0, 1, 'no'],
[2, 2, 0, 1, 'no'],
[0, 1, 1, 1, 'noaksjdh'],
[0, 1, 1, 0, 'yes'],
... | 3a6c9492a9c19c9442276ced91f6ebbf892703f9 | 668,021 |
import re
def parseTargetUrl(url):
"""
Parse target URL
"""
retVal = url
if not re.search("^http[s]*://", retVal, re.I) and not re.search("^ws[s]*://", retVal, re.I):
if re.search(":443[/]*$", retVal):
retVal = "https://" + retVal
else:
retVal = "http://" +... | 9538bb30f4d46d9282385c79cddb6e7e6bca7d61 | 668,022 |
def _get_word_ids(tokens, model_type="bert"):
"""Given the BPE split results, mark each token with its original word ids.
Args:
tokens: a list of BPE units
For example, if original sentnece is `iran and afghanistan speak the same language .`, then the roberta
tokens will be:
['ir', 'an', '... | c261ad5f760e57aaf5e5eac9ed88a4f9544f2537 | 668,023 |
def _FilterForImageType(artifacts, image_type):
"""Return only images for given |image_type|."""
return [i for i in artifacts if i.image_type == image_type] | 0193ca72067a76c8bbb9d56d966687f2466b9fd3 | 668,024 |
def get_sentiments_from_results(results):
""" Filter sentiments from results and replace labels - 1 for Good (positive), 2 for Bad (negative) """
sentiments = map(lambda x: 1 if x == 'Good' else 0, [result[0]['label'] for result in results])
return sentiments | e3df5a6e5de05dcc5d0977d9f6096e7d1435f935 | 668,025 |
import json
def createJSONPackage(data):
"""
Returns a JSON package.
Args:
data (dict) : A dictionary consisting of the data to JSONify.
"""
return json.dumps(data) | eb0e2be865932b8ba32f48b2b59bbb6252d12382 | 668,027 |
def objective(model):
"""
The objective function of the model.
Parameters
----------
model : pyomo model object
The pyomo model that the optimization shall be run on.
Returns
-------
dev : float
The summed squared deviation between the resulting charging load
(... | 66e29fd8e6cf184049f0f31d8efde6b406f8878a | 668,028 |
def parse_decoder_output(data):
"""
This function takes the output of a neurosynth decoder querry
It parses the output and returns a key-value pairing where the keys are the neurosynth terms, and values are correlations
"""
termas = data.split('values')[1]
termn = ''.join(termas).split('\n')
... | 7e6a94cb90074fb8719398712ccbaa27256f6d08 | 668,029 |
def calc_more_stuff(result):
"""Do some more calculations"""
if type(result) is list:
result += [{"more": "stuff"}]
elif type(result) is dict:
result["more"] = "stuff"
return result | 6df9ef7d3b4344e70d46f74031d38cb94279c4a9 | 668,030 |
def isRGB(color):
""" Check if the provided strings match the required rgb format
Positional arguments:
color -- a single color string
"""
try:
if color[0:4] != 'rgb(':
return False
if color[-1:] != ')':
return False
if len(color[4:-1].split(',')) != ... | ee235abe05740c73112024e76c56a10073b69e3b | 668,032 |
def get_property_annotations(self, all=False):
"""Returns a dict with non-empty property annotations.
If `all` is true, also annotations with no value are included."""
onto = self.namespace.ontology
d = {a.label.first(): a._get_values_for_class(self)
for a in onto.annotation_properties()}
... | 2a86cc27d091a6cb8ecfd1cb567c8c0b9d6c3e04 | 668,033 |
import re
def makeREstring(strings, default=None, strings_are_regex=False):
"""Turn a list of strings into a regexp string matching exactly those strings."""
if strings or default is None:
if not strings_are_regex:
strings = (re.escape(s) for s in strings)
return '^(' + '|'.join(st... | 58a9f3b2ad95ac918610b04ea175c0fe5e7d858f | 668,034 |
def get_max_cols(wrkbk, sheet_name = 'Sheet1') -> int:
"""
Count the maximum number of occupied columns
Arguments:
excel_filename: excel workbook
sheet_name: exchel sheet name to check.If sheet name not set, default is Sheet1
Returns:
int: Return max number occupi... | a402c8aa90fc5cccd8927e8f4effd1a1262a51a3 | 668,035 |
def recurse_access_key(current_val, keys):
""" Given a list of keys and a dictionary, recursively access the dicionary
using the keys until we find the key its looking for
If a key is an integer, it will convert it and use it as a list index
Example:
>>> recurse_access_key({'a': 'b'}, ['a'])
... | d63f3da3a44f062a70985da031d91c4fbb961d4e | 668,036 |
def comment_command(mwdb, file_or_hash, comment):
"""
Add comment to object
"""
obj = mwdb.query(file_or_hash)
obj.add_comment(comment)
return dict(message="Added comment {object_id}", object_id=obj.id) | 13ddf5729cc5cbe71f896e3b13bfcc8bb6d64a3d | 668,037 |
from typing import Tuple
def _get_brackets(range_: str) -> Tuple[bool, bool]:
"""Extract the bracket types from the provided range."""
if range_[0] not in {"[", "("}:
raise ValueError(f"Invalid range bracket {range_[0]}" f", should be [ or (.")
if range_[-1] not in {"]", ")"}:
raise ValueE... | be92e74a875c83700508c81e58f40c8a3d5c5989 | 668,038 |
def conductivity_to_imaginary_permittivity(freq: float,
conductivity: float) -> float:
"""Converts between conductivity and imaginary permittivity
This is a simple and straightforward conversion between the value
of conductivity, in S/m, and the imaginary part of ... | 7e156a2f0bbad8235cb40978303d34d5b44899dd | 668,040 |
import click
import functools
def common_args(func):
"""
Decorator to contain CLI args that will be common to both CLI and GUI: title and engine args.
"""
@click.option("--title", "-t", help="Title to display (if omitted will use file name).")
@click.option(
"--layout",
"-l",
... | 3eb652645ff929952aa14af108732af17eee39d6 | 668,041 |
import itertools
def _split_doctest(code):
"""Split a single doctest string into multiple code block strings"""
def is_code(x):
return x.startswith(">>>") or x.startswith("...")
groups = itertools.groupby(code.splitlines(), is_code)
raw_code_blocks = (lines for is_code, lines in groups if is... | 22811d2b0598ac53d7a17c0e3fb496549ed32989 | 668,042 |
def default_query_factory(controller):
"""
The default factory just returns Model.query(), sorted by created if it's available.
"""
Model = controller.meta.Model
query = Model.query()
if 'created' in Model._properties and Model._properties['created']._indexed:
query = query.order(-Model.... | d64c201dc1949c79a98286065e28347d065042da | 668,043 |
def add_cp(results, nodes, probabilities):
"""
Add the F-N cumulative frequency.
See equation (1) from Oughton et al. 2019.
Parameters
----------
results : list of dicts
All iterations generated in the simulation function.
nodes : int
Number of substations for the scenario.... | b189d07baf7ad3fe1d19afff39cfd0bf9d7a0c6c | 668,044 |
import pickle
def load_detectron_predictions(detectron_root):
"""Load detectron predictions from root directort.
Args:
detectron_root (Path): Points to a directory which contains a
subdirectory for each sequence, which in turn contains a .pickle
file for each frame in the sequ... | bc9c999aeab998bdb8de49343e770b5b7a7b99ed | 668,046 |
import re
def process_history(post_hist : list) -> dict:
"""Parses history metadata for title, date, student uid, and creation date.
:param post_hist: post history
:returns: dictionary with relevant history data pulled.
"""
hist_result = {}
init_post = post_hist[-1]
hist_result["student u... | 40098f0b62e81e74f7d82d431115c08cd2064597 | 668,047 |
def pub(subpub, address):
"""The reply socket."""
sub, pub = subpub
pub.bind(address)
return pub | df1a432bbee2d683e17561435585e451ac33dd70 | 668,048 |
def bool_2_uint8(bool_arr):
"""
Converts a boolean array to a black-and-white
uint8 array (0 and 255).
PARAMETERS:
im : (M x N) numpy array of bools
boolean array to convert
RETURNS:
(result) : (M x N) numpy array of uint8s
uint8 array of 0s (False) and 255s (... | 78e03b5e830486602d0f78d2250777c80a0a476d | 668,049 |
def input_new(s=""):
"""
Wrapper for the data entry function.
:param s: Description of the input value(Default value = "")
"""
return input(s) | 989a17a9e0a34d11eeddad3c5f826b3b47feb5e7 | 668,050 |
def step_learning_rate(base_lr, epoch, step_epoch, multiplier=0.1):
"""Sets the learning rate to the base LR decayed by 10 every step epochs"""
lr = base_lr * (multiplier ** (epoch // step_epoch))
return lr | 27c012e53421c91838f63e6319f8d4f03d0ff76c | 668,051 |
def get_multi_async(keys, **ctx_options):
"""Fetches a sequence of keys.
Args:
keys: A sequence of keys.
**ctx_options: Context options.
Returns:
A list of futures.
"""
return [key.get_async(**ctx_options) for key in keys] | 55e2c47c884d5d3b6aac41a64b9a938dadec222f | 668,052 |
def derivative(xdata, ydata):
"""
performs d(ydata)/d(xdata) with nearest-neighbor slopes
must be well-ordered, returns new arrays [xdata, dydx_data]
neighbors:
"""
D_ydata = []
D_xdata = []
for n in range(1, len(xdata)-1):
D_xdata.append(xdata[n])
D_ydata.append((ydata[... | 6e346554606e49b545499335a649fa6da8c119c4 | 668,053 |
def remove_device_model(device, session):
"""
:param session:
:param device:
:return:
"""
device.device_model = None
session.commit()
return device | 0c73ae77118bbb9a83924c533a11587eaf2c3543 | 668,054 |
def parse_alignment(reg_file):
""" Create a rinfo dictionary from a rinfo file."""
reg_dic = {}
with open(reg_file, "r") as infile:
for line in infile:
if line.startswith("REGION"):
newline = line.strip().split("\t")
key1 = newline[1].split(":")[0]
... | 4ecca36b914bf1f5e0655ef2273505d8ef30456a | 668,055 |
def get_permission_names(perm_int):
"""Takes an integer representing a set of permissions and returns a list
of corresponding permission names."""
pms = {'God': 16, 'Admin': 8, 'Builder': 2, 'Player': 1, 'DM': 4}
perm_list = []
for key, value in pms.items():
if perm_int & value:
... | d9175a1fffe1599ae470519611f6e80adbb4f3fe | 668,056 |
import logging
def get_arts(service, spreadsheetId):
"""Gets arts from gSheet."""
range_name = 'arts!A:AZ'
results = service.spreadsheets().values().get(
spreadsheetId=spreadsheetId, range=range_name).execute()
values = results.get('values', [])
if not values:
logging.error('No art found in gSheet... | 51f96421b3f1e017174dcc20b4b1599b9ef25db1 | 668,057 |
def edgelist_from_synapse_df(syn_df,
pre_column='pre_pt_root_id',
post_column='post_pt_root_id',
weight_column='size',
agg='count'):
"""Compute a list of pre to post edges from a synapse-query-style d... | ff2301ea1beeb799bf5887e2e140dc8a31be406b | 668,058 |
def eval_rpn(tokens) -> int:
"""Takes the postfix expression and returns the result.
Approach is simple. Add digits to the stack. Once we hit an
operator we execute the operation with the last two digits added.
The result gets added to the stack again
At the end there is one value in the stack whi... | 71e0ee47be67bd884218690c61bb85cad2bed07b | 668,059 |
def reusable_contextmanager(context_manager):
"""
Allows the generator-based context manager to be used more than once
"""
if not hasattr(context_manager, '_recreate_cm'):
return context_manager # context manager is already reusable (was not created usin yield funcion
class ReusableCtx:
... | cf3e051fd36216bf381b83e4775280df1a330a9f | 668,060 |
def extract_task(spark):
"""Load data from parquet file format.
#param spark: Spark session object.
#return: Spark Dataframe.
"""
spark.sql('use itv000513_reddit_db')
red = spark.sql('select id_name as author,id as author_id,"user" as author_type,created_date from dim_redditor')
sub = spark.... | b04c1fa049088fd645c35cb7eedc1a815cbc07df | 668,061 |
def task_serve_docs():
"""Show the documentation and coverage watching for changes."""
return {
"basename": "serve-docs",
"task_dep": ["install"],
"actions": ["poetry run mkdocs serve"],
} | e8a9649b542294211d55007aa01b1896ce39ae76 | 668,062 |
from typing import Dict
def remove_margin_lines(obj: Dict) -> bool:
"""Remove the lines that are inside the margins
Useful for 106 D and E/F - mostly for split pages
:param obj: PDF character
:return: True or False
"""
if obj["width"] < 10:
return False
if 70 < obj["x0"] < 75:
... | 1dbe69af10a4a3e0cc87041187b67ae8277f5ade | 668,064 |
from typing import Dict
from typing import Optional
from typing import Tuple
from typing import Any
def get_best_attribute(item: Dict[str, Optional[str]], keys: Tuple, fallback: Any = None) -> Optional[str]:
"""
Due to the weird nature of data exported from Last.fm, we need to check multiple keys to find the ... | 94fdc893ec7239c698d99d72c797a8ad67bb093c | 668,066 |
def calc_accu(a, b):
"""
Returns the accuracy (in %) between arrays <a> and <b>. The two arrays must
be column/row vectors.
"""
a = a.flatten()
b = b.flatten()
accu = 100.0 * (a == b).sum() / len(a)
return accu | 3f91e0805b3fc950da0ae02b34c8c0fb383e78c6 | 668,067 |
import hashlib
def message_to_hash(message_string):
"""Generate a hash deterministically from an arbitrary string."""
message = hashlib.sha256()
message.update(message_string.encode()) # Encode as UTF-8.
return int(message.digest().hex(), 16) >> 5 | 11b4d37488860cb3dae3525ced90f0d5072ffa0b | 668,068 |
def threepl_parameters(trace):
"""Returns the parameters from an MCMC run.
Args:
trace: result from the mcmc run
Return:
return_dictionary: dictionary of found parameters
"""
return {'Discrimination': trace['Discrimination'].mean(0),
'Difficulty': trace['Difficulty'].me... | 4b81a0c6cc7196dc15a4fc8145cd20671e51c91e | 668,070 |
def frequencies(colorings):
"""
Procedure for computing the frequency of each colour in a given coloring.
:param colorings: The given coloring.
:return: An array of colour frequencies.
"""
maxvalue = -1
frequency = [0] * (len(colorings))
for i in colorings:
maxvalue = max(maxvalu... | f9509e4c6ff253656a5e3d734e3b913c4428ec1c | 668,071 |
import torch
def pairwise_l2_sq(
x1,
x2,
):
"""Compute pairwise squared Euclidean distances."""
return torch.cdist(x1, x2).pow(2) | 12b147cba24fcd5a668ba614020a521225def3ae | 668,072 |
def is_valid_bdf_interval(interval):
"""check if the min_tx_interva,min-rx-interval is valid"""
if interval < 50 or interval > 1000:
return False
return True | 3d363a3efe1aff4351ee981e11663d89f97463f8 | 668,074 |
def update_function(func, invars, energized):
"""Return the output of the a Function's update method."""
return func.update(*invars, energized=energized) | 2e60daa5f99bda175d8308218b404c7d592920a9 | 668,075 |
import torch
def boxes3d_to_bev_torch_lidar(boxes3d):
"""
:param boxes3d: (N, 7) [x, y, z, w, l, h, ry] in LiDAR coords
:return:
boxes_bev: (N, 5) [x1, y1, x2, y2, ry]
"""
boxes_bev = boxes3d.new(torch.Size((boxes3d.shape[0], 5)))
cu, cv = boxes3d[:, 0], boxes3d[:, 1]
half_l, half... | 80c906865ab5b6465cc9189dda137a3010987115 | 668,076 |
def filter_date(date):
"""Return x-axis labels based on dates list."""
if date[-2:] != "01":
return ""
return date[:7] | 3e908eddf2d3825dad19092df269f5747fc4d8f7 | 668,077 |
import argparse
def get_args():
"""Return arguments passed to the script"""
parser = argparse.ArgumentParser(prog='hemlis.py')
parser.add_argument('message', type=str, help='message to encode, could be a file')
parser.add_argument('--version', action='version', version='%(prog)s 1.0')
parser.add_a... | 54977e86c075c270eb63da3043dcd37ba4e412ed | 668,078 |
import argparse
def parse_args() -> argparse.Namespace:
"""Parse command line arguments."""
parser = argparse.ArgumentParser(description="Print a sweet sweet sequence")
parser.add_argument(
"sequence",
type=str,
help="Define the sequence to run (e.g.: A181391)",
nargs="?",
... | e5c3b8043cf4bfab6fc18dda0ac779a8ea3bf8c6 | 668,079 |
import os
def _findfile(f, possible_folders):
"""
Returns one of the `possible_folders` where `f` is present,
or None
"""
for folder in possible_folders:
if os.path.exists(os.path.join(folder, f)):
return folder
return None | 862419aa88245acc1c62ac8183c643369c3a1911 | 668,080 |
def unpack(value):
"""Return a three tuple of data, code, and headers"""
if not isinstance(value, tuple):
return value, 200, {}
value_len = len(value)
if value_len == 2:
return value[0], value[1], {}
elif value_len == 3:
return value[0], value[1], value[2]
else:
r... | cc7f500534866b0f080d6e237ce89b90635c2782 | 668,081 |
def is_condition_key_match(document_key, some_str):
""" Given a documented condition key and one from a policy, determine if they match
Examples:
- s3:prefix and s3:prefix obviously match
- s3:ExistingObjectTag/<key> and s3:ExistingObjectTag/backup match
"""
# Normalize both
document_key = ... | e79c7b0e5fc8732d5b333893edf6eaf3cd234164 | 668,082 |
def read_best_fit(path):
"""
Return a 2-tuple consisting of the name and the best-fit objective function value,
given the path to sorted_params.txt
"""
with open(path) as f:
f.readline() # header
line = f.readline() # first pset (best)
parts = line.split()
n... | 3804f0d58fff62ccb78ccbad6a77ccdd9f827aa5 | 668,083 |
import torch
def ssm_vr_loss(energy_model, x, n_slices=1):
"""SSM-VR (variance reduction) loss from
Sliced Score Matching: A Scalable Approach to Density and Score Estimation
The loss is computed as
s = -dE(x)/dx
loss = vT*(ds/dx)*v + 1/2*||s||^2
Args:
x (torch.Tensor): input samples... | 914f74b661244fd2c098d2e01c4124359bb78111 | 668,084 |
def get_z_sample(xbar, mu, SE):
"""
Return the z-score of a sample, from a sampling distribution.
Parameters
----------
* xbar: mean of the current sample.
* mu: mean of the population from where the sample is drawn.
* SE: standard error of the sampling distribution (population SD / root(po... | be1b19d6c0ff6a9f47425e3b12813b6da68938f1 | 668,085 |
def get_gnames_to_save_in_nested_folder(gnames_list):
"""
On case-insensitive systems the SVG files cannot be all saved to the
same folder otherwise a.svg and A.svg would be written over each other,
for example. So, pre-process the list of glyph names to find which ones
step on each other, and save ... | 112680a2db5e4a6cb86dce57a0e55b740e8a4018 | 668,086 |
def get_notes_from_line(line):
"""
Takes a line as a string, and gives back an array of note symbols (string, with name + figure).
We didn't just split at each spaces, because we wanted the "p" to be part of
the note it succeeds, to increase directly the duration of the note.
Hence, we split the st... | 83350acc71448cf451e2682dc47943cdfc43abf1 | 668,087 |
def round_filters(channels, global_params, skip=False):
"""
Calculate and round number of channels based on depth multiplier.
Args:
channels (int): base number of channels.
global_params (EasyDict): global args, see: class: `EfficientNet`.
skip (bool): if True, do nothing and return... | c30ddaaacf73812efa3cbc3032498204785c7c6b | 668,088 |
import pickle
def deliver(conn, localobj):
"""delivers (recreates) a local object on the other party. the object is
``pickled`` locally and ``unpickled`` on the remote side, thus moved
**by value**. changes made to the remote object will not reflect locally.
:param conn: the RPyC connection
:para... | 83c18503758de9c8be08d6c9f61647c3ab547181 | 668,089 |
def ConstructNameFilterExpression(requested_name_regexes):
"""Construct a name filter expression.
Args:
requested_name_regexes: A list of name regular expressions that can
be used to filter the resources by name on the server side.
Returns:
A string expression suitable for the requested names, or ... | dc9fc587abab52e400866b6675102a48533431a1 | 668,090 |
def for_text_write(fpath):
""" For Python3 we often should open as a text file (like for json, csv.reader, etc) """
return open(fpath, "w") | 6cc53a98b6f869550271d21210173cf84e5b2c67 | 668,091 |
def split_heads(x, num_heads):
""" Split heads
:param x: A tensor with shape [batch, length, channels]
:param num_heads: An integer
:returns: A tensor with shape [batch, heads, length, channels / heads]
"""
assert x.shape[-1] % num_heads == 0, str(x.shape)
return x.reshape(x.shape[:-1] + (... | be77a96a531f89ae32098394028dd317073dba67 | 668,092 |
def get_illust_url(illust_id: int) -> str:
"""Get illust URL from ``illust_id``.
:param illust_id: Pixiv illust_id
:type illust_id: :class:`int`
:return: Pixiv Illust URL
:rtype: :class:`str`
"""
return (
'https://www.pixiv.net/member_illust.php'
'?mode=medium&illust_id={}'... | a6878b01e6ced3ce8d65a3acaa0459ac4f3c8a9c | 668,093 |
import os
def get_files_from_unpack_folder(folder):
"""Return the source image file paths from the given unpack folder.
Returns [] if the files were not found.
"""
# All of the image files are located in the measurement folier
measurement_folder = os.path.join(folder, 'measurement')
if not... | 0acaeadd67804c17d7509b44d2c4c0676e8bde08 | 668,094 |
def _get_entity_type_sg_name_field(entity_type):
"""
Return the Shotgun name field to use for the specified entity type. This
is needed as not all entity types are consistent!
:param entity_type: The entity type to get the name field for
:returns: The name field for the specified... | 8cc96d8f0d926f5c28ac83017eb3ded46168ad6f | 668,095 |
def addword(bot, input):
"""Add word to bad words list"""
if not input.admin:
return False
if not input.group(2):
return
word = input.group(2).lower()
if word not in bot.config.badwords:
bot.config.set_add('badwords', word)
bot.reply("Added word to list")
else:
bot.reply("Word already in list") | 476b4853f145ff15281ffc930ad36063d9838877 | 668,096 |
def right_child(node, new_node=None):
""" Set right child: right_child(node, new_right_child); Get right node: right_child(node). """
if new_node is not None:
node[2] = new_node
return node[2] | 545bc3a187f669bdf56bf88390a0dac3ff5fc80e | 668,098 |
def square(number: int):
"""Calculate square of a given number."""
return number ** 2 | c028a462b49cb743299820c4c0768543333f402b | 668,099 |
def findHumanOpponentExists(player):
""" Checks if an opponent team exists """
opponent_teamname = input("Choose your opponent team by name: ")
try:
if player == opponent_teamname:
raise Exception("Playing against yourself is strictly prohibited.")
teamfilename = "teams/team" + ... | c20431cbe232ffb13fdbb31fc439aae6c6a13c78 | 668,100 |
def _normalized_scale(scale):
"""
Generate the scaling factor for each dimension based on voxel size and array
dimension.
"""
den = min(scale)
return tuple(s / den for s in scale) | 4677d7a0545913a0c15e38d03575ef1ddf26e035 | 668,101 |
import os
def outputs_handler(params):
"""
It handles the output paths.
Parameters
----------
params : condifparser object
Configuration parameters to run the encoding.
"""
global preprocessing_output, encodings_output, clustering_output, \
analysis_output
... | 6755928e58cc863761e133b89ee186bfe13122d0 | 668,102 |
def calculatePostIapAggregateInterference(q_p, num_sas, iap_interfs):
"""Computes post IAP allowed aggregate interference.
Routine to calculate aggregate interference from all the CBSDs managed by the
SAS at protected entity.
Args:
q_p: Pre IAP threshold value for protection type (mW)
num_sas: Number ... | 269aa10ff5a4a22193525698248ab56e59759fb6 | 668,103 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.