content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def get_lif_list(path):
"""
Returns a list of files ending in *.lif in provided folder
:param: path
:return: list -- filenames
"""
path += '/*.lif'
return glob.glob(path) | 25,100 |
def parse_args():
"""
Parse input arguments
"""
parser = argparse.ArgumentParser(description='Single image depth estimation')
parser.add_argument('--dataset', dest='dataset',
help='training dataset',
default='custom', type=str)
parser.add_argument('--e... | 25,101 |
def plot_rhodelta_rho(rho, delta):
"""
Plot scatter diagram for rho*delta_rho points
Args:
rho : rho list
delta : delta list
"""
logger.info("PLOT: rho*delta_rho plot")
y = rho * delta
r_index = np.argsort(-y)
x = np.zeros(y.shape[0])
idx = 0
for r in r_index:
... | 25,102 |
def test_arguments_in_init(mocker):
"""Test whether arguments are set up correctly while initializing a HermesApp object."""
app = HermesApp(
"Test arguments in init",
mqtt_client=mocker.MagicMock(),
host="rhasspy.home",
port=8883,
tls=True,
username="rhasspy-herm... | 25,103 |
def speaker_data_to_csvs(corpus_context, data):
"""
Convert speaker data into a CSV file
Parameters
----------
corpus_context: :class:`~polyglotdb.corpus.CorpusContext`
the corpus object
data : :class:`~polyglotdb.io.helper.DiscourseData`
Data to load into a graph
"""
di... | 25,104 |
def compute_distance_matrix(users, basestations):
"""Distances between all users and basestations is calculated.
Args:
users: (obj) list of users!
basestations: (obj) list of basestations!
Returns:
(list of) numpy arrays containing the distance between a user and all base... | 25,105 |
def __getattr__(name):
"""Lazy load the global resolver to avoid circular dependencies with plugins."""
if name in _SPECIAL_ATTRS:
from .core import resolver
res = resolver.Resolver()
res.load_plugins_from_environment()
_set_default_resolver(res)
return globals()[name]... | 25,106 |
def img_newt(N, xran=(-3, 3), yran=(-3, 3), tol=1e-5, niter=100):
"""
Add colors to a matrix according to the fixed point
of the given equation.
"""
sol = [-(np.sqrt(3.0)*1j - 1.0)/2.0,
(np.sqrt(3.0)*1j + 1.0)/2.0,
-1.0]
col_newt = np.zeros((N, N, 3))
Y, X = np... | 25,107 |
def _ensure_no_unsupported_suppressions(
schema_ast: DocumentNode, renamings: RenamingMapping
) -> None:
"""Confirm renamings contains no enums, interfaces, or interface implementation suppressions."""
visitor = SuppressionNotImplementedVisitor(renamings)
visit(schema_ast, visitor)
if (
not ... | 25,108 |
def pack_block_header(hdr: block.BlockHeader,
abbrev: bool = False,
pretty: bool = False,
) -> str:
"""Pack blockchain to JSON string with b64 for bytes."""
f = get_b2s(abbrev)
hdr_ = {'timestamp': f(hdr['timestamp']),
'previous_h... | 25,109 |
def get_datasets(recipe):
"""Get dataset instances from the recipe.
Parameters
----------
recipe : dict of dict
The specifications of the core datasets.
Returns
-------
datasets : dict of datasets
A dictionary of dataset instances, compatible with torch's
DataLoader... | 25,110 |
def is_sedol(value):
"""Checks whether a string is a valid SEDOL identifier.
Regex from here: https://en.wikipedia.org/wiki/SEDOL
:param value: A string to evaluate.
:returns: True if string is in the form of a valid SEDOL identifier."""
return re.match(r'^[0-9BCDFGHJKLMNPQRSTVWXYZ]{6}\d$', value) | 25,111 |
def p_listof_literal_terms(t):
"""
listof-terms : LPAREN literal-term-list RPAREN
| LPAREN RPAREN
"""
if len(t) == 4:
t[0] = t[2]
else:
t[0] = [] | 25,112 |
def create_substrate(dim):
"""
The function to create two-sheets substrate configuration with specified
dimensions of each sheet.
Arguments:
dim: The dimensions accross X, Y axis of the sheet
"""
# Building sheet configurations of inputs and outputs
inputs = create_sheet_space(-1,... | 25,113 |
def EventObjectGenerator(plaso_storage, quiet=False):
"""Yields EventObject objects.
Yields event_objects out of a StorageFile object. If the 'quiet' argument
is not present, it also outputs 50 '.'s indicating progress.
Args:
plaso_storage: a storage.StorageFile object.
quiet: boolean value indicating... | 25,114 |
def main():
"""Place holder function for running this module as cmd line program."""
print("null tpn processing.") | 25,115 |
def remove_artefacts(signal: np.array, low_limit: int = 40, high_limit: int = 210) -> np.array:
"""
Replace artefacts [ultra-low and ultra-high values] with zero
Args:
signal: (np.array) 1D signal
low_limit: (int) filter values below it
high_limit: (int) filter valu... | 25,116 |
def normalizedBGR(im, display=True):
""" Generate Opponent color space. O3 is just the intensity """
im = img.norm(im)
B, G, R = np.dsplit(im, 3)
b = (B - np.mean(B)) / np.std(B)
g = (G - np.mean(G)) / np.std(G)
r = (R - np.mean(R)) / np.std(R)
out = cv2.merge((np.uint8(img.normUnity(b) * 25... | 25,117 |
def generate_training_pages():
""" Responsible for generating the markdown pages of the training pages """
data = {}
# Side navigation for training
data['menu'] = resources_config.training_navigation
# Training Overview
training_md = resources_config.training_md + json.dumps(data)
# ... | 25,118 |
def feeds(url):
"""
Tries to find feeds
for a given URL.
"""
url = _full_url(url)
data = _get(url)
# Check if the url is a feed.
if _is_feed(url):
return [url]
# Try to get feed links from markup.
try:
feed_links = [link for link in _get_feed_links(data, url) i... | 25,119 |
def getlog(name):
"""Create logger object with predefined stream handler & formatting
Parameters
----------
name : str
module __name__
Returns
-------
logging.logger
Examples
--------
>>> from smseventlog import getlog
>>> log = getlog(__name__)
"""
name = ... | 25,120 |
def hard_prune(args, ADMM, model):
"""
hard_pruning, or direct masking
Args:
model: contains weight tensors in cuda
"""
print ("hard pruning")
for (name, W) in model.named_parameters():
if name not in ADMM.prune_ratios: # ignore layers that do not have rho
continue
_, cuda... | 25,121 |
def read_new_probe_design(path: str, reference_type: str = 'genome') -> pd.DataFrame:
"""
Read amplimap probes.csv file and return pandas dataframe.
"""
try:
design = pd.read_csv(path)
log.info('Read probe design table from %s -- found %d probes', path, len(design))
if list(desi... | 25,122 |
def replace_nan(x):
"""
Replaces NaNs in 1D array with nearest finite value.
Usage: y = replace_nan(x)
Returns filled array y without altering input array x.
Assumes input is numpy array.
3/2015 BWB
"""
import numpy as np
#
x2 = np.zeros(len(x))
np.... | 25,123 |
def import_worksheet_data(model_type):
"""A function called from Excel to import data by ID
from Firestore into the Excel workbook.
Args:
model_type (str): The data model at hand.
"""
# Initialize the workbook.
book = xlwings.Book.caller()
worksheet = book.sheets.active
config_s... | 25,124 |
def handson_table(request, query_sets, fields):
"""function to render the scoresheets as part of the template"""
return excel.make_response_from_query_sets(query_sets, fields, 'handsontable.html')
# content = excel.pe.save_as(source=query_sets,
# dest_file_type='handsontable.... | 25,125 |
def is_periodic(G):
"""
https://stackoverflow.com/questions/54030163/periodic-and-aperiodic-directed-graphs
Own function to test, whether a given Graph is aperiodic:
"""
if not nx.is_strongly_connected(G):
print("G is not strongly connected, periodicity not defined.")
return False
... | 25,126 |
def Sphere(individual):
"""Sphere test objective function.
F(x) = sum_{i=1}^d xi^2
d=1,2,3,...
Range: [-100,100]
Minima: 0
"""
#print(individual)
return sum(x**2 for x in individual) | 25,127 |
def find_names_for_google(df_birth_names):
"""
:param df_birth_names: 所有的birth data from the data given by Lu
:return 1: df_country_found,
返回一个dataframe 里面有国家了
先通过country list过滤,有些国家可能有问题(如有好几个名字的(e.g. 荷兰),有些含有特殊符号,如刚果布,刚果金,朝鲜,南朝鲜北朝鲜是三个“国家”,
再比如说南奥塞梯,一些太平洋岛国归属有问题,还就是香港台湾这样的。。。。暂时算是国家)
... | 25,128 |
def check_type(
value: Any,
expected_type: Any,
*,
argname: str = "value",
memo: Optional[TypeCheckMemo] = None,
) -> None:
"""
Ensure that ``value`` matches ``expected_type``.
The types from the :mod:`typing` module do not support :func:`isinstance` or :func:`issubclass`
so a numbe... | 25,129 |
def make_address_mask(universe, sub=0, net=0, is_simplified=True):
"""Returns the address bytes for a given universe, subnet and net.
Args:
universe - Universe to listen
sub - Subnet to listen
net - Net to listen
is_simplified - Whether to use nets and subnet or universe only,
see User Guid... | 25,130 |
def get_offline_target(featureset, start_time=None, name=None):
"""return an optimal offline feature set target"""
# todo: take status, start_time and lookup order into account
for target in featureset.status.targets:
driver = kind_to_driver[target.kind]
if driver.is_offline and (not name or... | 25,131 |
def yaml2json(input, output, mini, binary, sort):
"""
-i YAML -o JSON [-m] (minify) [-b] (keep binary)
"""
writer.json(
reader.yaml(
input, sort=sort
),
output,
mini=mini,
binary=binary
) | 25,132 |
def create_dir_struct(course_name="abc_course", force=False, working_dir=None):
"""
Create a directory structure that can be used to start an abc-classroom
course. This includes a main directory, two sub directories for templates
and cloned files, and a start to a configuration file.
This is the im... | 25,133 |
def get_img_size(src_size, dest_size):
"""
Возвращает размеры изображения в пропорции с оригиналом исходя из того,
как направлено изображение (вертикально или горизонтально)
:param src_size: размер оригинала
:type src_size: list / tuple
:param dest_size: конечные размеры
:type dest_size: lis... | 25,134 |
def test_get_query_result():
"""
测试获取查询结果集
"""
hp.enable()
hp.reset()
mock_query_result()
res = client.get("/v3/datalab/queries/1/result/")
assert res.is_success()
assert res.data["totalRecords"] == 1 | 25,135 |
def laxnodeset(v):
"""\
Return a nodeset with elements from the argument. If the argument is
already a nodeset, it self will be returned. Otherwise it will be
converted to a nodeset, that can be mutable or immutable depending on
what happens to be most effectively implemented."""
if not isinstance(v, Node... | 25,136 |
def load_config():
"""
Loads the configuration file.
Returns:
- (json) : The configuration file.
"""
return load_json_file('config.json') | 25,137 |
def test_singleton_get_instance_without_configure_fails():
""" Calling get_instance() without first calling configure_instance() should fail """
with pytest.raises(Exception):
c = Controller.get_instance() | 25,138 |
def dtm_generate_footprint(tile_id):
"""
Generates a footprint file using gdal.
:param tile_id: tile id in the format "rrrr_ccc" where rrrr is the row number and ccc is the column number
:return execution status
"""
# Initiate return value and log output
return_value = ''
log_file = ope... | 25,139 |
def save_fitresult(output_dir, fit_result, log_lines=None):
"""
Save a fit result object to the specified directory with associated metadata
Output directory contents:
deltaG.csv/.txt: Fit output result (deltaG, covariance, k_obs, pfact)
losses.csv/.txt: Losses per epoch
log.txt: Log file with ... | 25,140 |
def favicon(request):
"""
best by tezar tantular from the Noun Project
"""
if settings.DEBUG:
image_data = open("static/favicon-dev.ico", "rb").read()
else:
image_data = open("static/favicon.ico", "rb").read()
# TODO add cache headers
return HttpResponse(image_data, content_t... | 25,141 |
def text_from_html(body):
"""
Gets all raw text from html, removing all tags.
:param body: html
:return: str
"""
soup = BeautifulSoup(body, "html.parser")
texts = soup.findAll(text=True)
visible_texts = filter(tag_visible, texts)
return " ".join(t.strip() for t in visible_texts) | 25,142 |
def alert_history():
"""
Alert History: RESTful CRUD controller
"""
return s3_rest_controller(rheader = s3db.cap_history_rheader) | 25,143 |
def chat():
"""
Chat room. The user's name and room must be stored in
the session.
"""
if 'avatar' not in session:
session['avatar'] = avatars.get_avatar()
data = {
'user_name': session.get('user_name', ''),
'avatar': session.get('avatar'),
'room_key': session.get... | 25,144 |
def _get_split_idx(N, blocksize, pad=0):
"""
Returns a list of indexes dividing an array into blocks of size blocksize
with optional padding. Padding takes into account that the resultant block
must fit within the original array.
Parameters
----------
N : Nonnegative integer
Total ... | 25,145 |
def buydown_loan(amount, nrate, grace=0, dispoints=0, orgpoints=0, prepmt=None):
"""
In this loan, the periodic payments are recalculated when there are changes
in the value of the interest rate.
Args:
amount (float): Loan amount.
nrate (float, pandas.Series): nominal interest rate per ... | 25,146 |
def ffill(array: np.ndarray, value: Optional[int] = 0) -> np.ndarray:
"""Forward fills an array.
Args:
array: 1-D or 2-D array.
value: Value to be filled. Default is 0.
Returns:
ndarray: Forward-filled array.
Examples:
>>> x = np.array([0, 5, 0, 0, 2, 0])
>>> f... | 25,147 |
def test_dpp_proto_pkex_cr_req_no_i_auth_tag(dev, apdev):
"""DPP protocol testing - no I-Auth Tag in PKEX Commit-Reveal Request"""
run_dpp_proto_pkex_req_missing(dev, 39, "No valid u (I-Auth tag) found") | 25,148 |
def svn_stringbuf_from_file(*args):
"""svn_stringbuf_from_file(char const * filename, apr_pool_t pool) -> svn_error_t"""
return _core.svn_stringbuf_from_file(*args) | 25,149 |
def test_multiple_substitutions(tmp_path):
"""Render a template with multiple context variables."""
template_path = tmp_path / "template.txt"
template_path.write_text(textwrap.dedent(u"""\
TO: {{email}}
FROM: from@test.com
Hi, {{name}},
Your number is {{number}}.
"""))
... | 25,150 |
def poly4(x, b, b0):
"""
Defines a function with polynom 4 to fit the curve
Parameters
----------
x: numpy.ndarray:
x of f(x)
b: float
Parameter to fit
b0 : int
y-intercept of the curve
Returns
-------
f : numpy.ndarray
Result of f(x)
"""
... | 25,151 |
def chkiapws06table6(printresult=True,chktol=_CHKTOL):
"""Check accuracy against IAPWS 2006 table 6.
Evaluate the functions in this module and compare to reference
values of thermodynamic properties (e.g. heat capacity, lapse rate)
in IAPWS 2006, table 6.
:arg bool printresult: If True (de... | 25,152 |
def flat(arr):
"""
Finds flat things (could be zeros)
___________________________
"""
arr = np.array(arr)
if arr.size == 0:
return False
mean = np.repeat(np.mean(arr), arr.size)
nonzero_residuals = np.nonzero(arr - mean)[0]
return nonzero_residuals.size < arr.size/100 | 25,153 |
def sensitive_fields(*paths, **typed_paths):
"""
paths must be a path like "password" or "vmInfo.password"
"""
def ret(old_init):
def __init__(self, *args, **kwargs):
if paths:
ps = ["obj['" + p.replace(".", "']['") + "']" for p in paths]
setattr(s... | 25,154 |
def test_base_url(host, scheme):
"""Test the base URL setting on init."""
url = f"{scheme}://{utils.random_lower_string()}"
dri_postal = DriPostal(url)
assert isinstance(dri_postal.service_url, AnyHttpUrl)
assert str(dri_postal.service_url) == url | 25,155 |
def get_timestamp_diff(diff):
"""获取前后diff天对应的时间戳(毫秒)"""
tmp_str = (datetime.today() + timedelta(diff)).strftime("%Y-%m-%d %H:%M:%S")
tmp_array = time.strptime(tmp_str, "%Y-%m-%d %H:%M:%S")
return int(time.mktime(tmp_array)) * 1000 | 25,156 |
def can_delete(account, bike):
""" Check if an account can delete a bike.
Account must be a team member and bike not borrowed in the future.
"""
return (team_control.is_member(account, bike.team)
and not has_future_borrows(bike)) | 25,157 |
def run_dev(
root: Optional[Path] = typer.Option(None),
host: str = typer.Option("127.0.0.1"),
rpc_port: int = typer.Option(3477),
http_port: int = typer.Option(8000),
):
""" Hot reloading local HTTP and RPC servers """
# set environment variables
# commit to os.environ for HTTP/RPC process... | 25,158 |
def config_file():
"""
Returns the config file ($HOME/.config/python-pulseaudio-profiles-trayicon/config.json).
:return: the directory for the configurations
:rtype: str
"""
return os.path.join(config_dir(), "config.json") | 25,159 |
def setup_directories(base_dir, fqdn, mode, uid, gid):
"""Setup directory structure needed for cert updating operations."""
expected_dirs = []
settings = {'base': base_dir, 'fqdn': fqdn}
dir_tree = DIR_TREE[:]
dir_tree.insert(0, base_dir)
for directory in dir_tree:
expected_dirs.append((... | 25,160 |
def get_node_types(nodes, return_shape_type = True):
"""
Get the maya node types for the nodes supplied.
Returns:
dict: dict[node_type_name] node dict of matching nodes
"""
found_type = {}
for node in nodes:
node_type = cmds.nodeType(node)
... | 25,161 |
def updateDistances(fileName):
"""
Calculate and update the distance on the given CSV file.
Parameters
----------
fileName: str
Path and name of the CSV file to process.
Returns
-------
ret: bool
Response indicating if the update was successful or not.
"""
# Re... | 25,162 |
def hr(*args, **kwargs):
"""
The HTML <hr> element represents a thematic break between
paragraph-level elements (for example, a change of scene in a
story, or a shift of topic with a section). In previous versions
of HTML, it represented a horizontal rule. It may still be
displayed as a horizont... | 25,163 |
def as_linker_option(p):
"""Return as an ld library path argument"""
if p:
return '-Wl,' + p
return '' | 25,164 |
def split_backbone(options):
"""
Split backbone fasta file into chunks.
Returns dictionary of backbone -> id.
"""
backbone_to_id = {}
id_counter = 0
# Write all backbone files to their own fasta file.
pf = ParseFasta(options.backbone_filename)
tuple = pf.getRecord()
while tup... | 25,165 |
def test_hash(CmpC):
"""
__hash__ returns different hashes for different values.
"""
assert hash(CmpC(1, 2)) != hash(CmpC(1, 1)) | 25,166 |
def _get_highest_tag(tags):
"""Find the highest tag from a list.
Pass in a list of tag strings and this will return the highest
(latest) as sorted by the pkg_resources version parser.
"""
return max(tags, key=pkg_resources.parse_version) | 25,167 |
def test_ipm3():
"""
Test ipm on unique distribution.
"""
d = bivariates['cat']
red = i_pm(d, ((0,), (1,)), (2,))
assert red == pytest.approx(1) | 25,168 |
def papply( f, seq, pool_size=cores, callback=None ):
"""
Apply the given function to each element of the given sequence, optionally invoking the given
callback with the result of each application. Do so in parallel, using a thread pool no
larger than the given size.
:param callable f: the function... | 25,169 |
def rename_kwargs(func_name: str, kwargs: Dict, aliases: Dict):
"""
Used to update deprecated argument names with new names. Throws a
`TypeError` if both arguments are provided, and warns if old alias
is used. Nothing is returned as the passed `kwargs` are modified
directly. Implementation is inspir... | 25,170 |
def add_comment(request, pk):
"""
Adds comment to the image - POST.
Checks the user and assigns it to the comment.posted_by
"""
form = PhotoCommentForm(request.POST)
if form.is_valid():
comment = form.save(commit=False)
comment.user = request.user
comment.save()
else:... | 25,171 |
def predict():
"""
runs the three models and displays results view
"""
filename = request.form['filename']
file_root = os.path.splitext(filename)[0]
full_filename = os.path.join(app.config['STATIC_MATRIX_PATH'],
filename)
# run YOLOv5 model
os.system(... | 25,172 |
def disable_plugin(
ctx: typer.Context,
plugin: str = typer.Argument(None, help="the plugin key"),
web: bool = typer.Option(False, help="open upm in web browser after disabling plugin"),
):
""" Disables the specified plugin """
if plugin is None:
try:
plugin = pathutil.get_plugin... | 25,173 |
def disable_warnings_temporarily(func):
"""Helper to disable warnings for specific functions (used mainly during testing of old functions)."""
def inner(*args, **kwargs):
import warnings
warnings.filterwarnings("ignore")
func(*args, **kwargs)
warnings.f... | 25,174 |
def progress_bar(progress):
"""
Generates a light bar matrix to display volume / brightness level.
:param progress: value between 0..1
"""
dots = list(" " * 81)
num_dots = ceil(round(progress, 3) * 9)
while num_dots > 0:
dots[81 - ((num_dots - 1) * 9 + 5)] = "*"
num_dots -= ... | 25,175 |
def read(ctx, folder):
"""
Get folder details EVE-NG host
\b
Examples:
eve-ng folder read /path/to/folder
"""
client = get_client(ctx)
resp = client.api.get_folder(folder)
cli_print_output("json", resp) | 25,176 |
def get_context_command_parameter_converters(func):
"""
Parses the given `func`'s parameters.
Parameters
----------
func : `async-callable`
The function used by a ``SlasherApplicationCommand``.
Returns
-------
func : `async-callable`
The converted function.
... | 25,177 |
def norm(x):
"""Normalize 1D tensor to unit norm"""
mu = x.mean()
std = x.std()
y = (x - mu)/std
return y | 25,178 |
def honest_propose(validator, known_items):
"""
Returns an honest `SignedBeaconBlock` as soon as the slot where
the validator is supposed to propose starts.
Checks whether a block was proposed for the same slot to avoid slashing.
Args:
validator: Validator
known_items (Dict): Kn... | 25,179 |
def concat_pic_pdf(src, dest=None, line_max=2, recursive=False, alpha=1, vertical=False, row_max=None):
"""将src文件夹下图片合成到dest(pdf文件),每行line_max个,扩大系数为alpha,vertical代表为竖直状态"""
num = 0
dest = create_dest(dest, '.pdf')
concat_tmp = os.path.join(src, 'concat')
import shutil
shutil.rmtree(concat_tmp, ... | 25,180 |
def formatKwargsKey(key):
"""
'fooBar_baz' -> 'foo-bar-baz'
"""
key = re.sub(r'_', '-', key)
return key | 25,181 |
def mktimestamp(dt):
"""
Prepares a datetime for sending to HipChat.
"""
if dt.tzinfo is None:
dt = dt.replace(tzinfo=dateutil.tz.tzutc())
return dt.isoformat(), dt.tzinfo.tzname(dt) | 25,182 |
def helicsFederateEnterExecutingModeIterativeAsync(fed: HelicsFederate, iterate: HelicsIterationRequest):
"""
Request an iterative entry to the execution mode.
This call allows for finer grain control of the iterative process than `helics.helicsFederateRequestTime`. It takes a time and iteration request, an... | 25,183 |
def test_actor_nisscan(monkeypatch, pkgs_installed, fill_conf_file, fill_ypserv_dir):
"""
Parametrized helper function for test_actor_* functions.
Run the actor feeded with our mocked functions and assert
produced messages according to set arguments.
Parameters:
pkgs_installed (touple): i... | 25,184 |
def test_hashing():
"""" check that hashes are correctly computed """
cam1 = CameraGeometry.from_name("LSTCam")
cam2 = CameraGeometry.from_name("LSTCam")
cam3 = CameraGeometry.from_name("ASTRICam")
assert len(set([cam1, cam2, cam3])) == 2 | 25,185 |
def load_and_assign_npz_dict(name='model.npz', sess=None):
"""Restore the parameters saved by ``tl.files.save_npz_dict()``.
Parameters
----------
name : a string
The name of the .npz file.
sess : Session
"""
assert sess is not None
if not os.path.exists(name):
print("[!]... | 25,186 |
def MakeProto(python_out):
"""Make sure our protos have been compiled to python libraries."""
# Start running from one directory above the grr directory which is found by
# this scripts's location as __file__.
cwd = os.path.dirname(os.path.abspath(__file__))
# Find all the .proto files.
protos_to_compile =... | 25,187 |
def check_dataset(dataset):
"""Check dataset name."""
if not isinstance(dataset, str):
raise TypeError("Provide 'dataset' name as a string")
if (dataset not in get_available_datasets()):
raise ValueError("Provide valid dataset. get_available_datasets()") | 25,188 |
def build_accuracy(logits, labels, name_scope='accuracy'):
"""
Builds a graph node to compute accuracy given 'logits' a probability distribution over the output and 'labels' a
one-hot vector.
"""
with tf.name_scope(name_scope):
correct_prediction = tf.equal(tf.argmax(logits, 1), tf.argmax(la... | 25,189 |
def generate_markdown_files(domain, mitigations, side_nav_data, side_nav_mobile_data, notes):
"""Responsible for generating shared data between all mitigation pages
and begins mitigation markdown generation
"""
data = {}
if mitigations:
data['domain'] = domain.split("-")[0]
dat... | 25,190 |
def compute_mp_av(mp, index, m, df, k):
"""
Given a matrix profile, a matrix profile index, the window size and the DataFrame that contains the timeseries.
Create a matrix profile object and add the corrected matrix profile after applying the complexity av.
Uses an extended version of the apply_av funct... | 25,191 |
def read_burris(fh):
"""
Read Burris formatted file, from given open file handle.
Accepts comma or tab-separated files.
Parameters
----------
fh : TextIOWrapper
open file handle
Returns
-------
ChannelList
"""
all_survey_data = ChannelList()
for i, orig_line ... | 25,192 |
def _remove_invalid_characters(file_name):
"""Removes invalid characters from the given file name."""
return re.sub(r'[/\x00-\x1f]', '', file_name) | 25,193 |
def get_ops():
""" Builds an opcode name <-> value dictionary """
li = ["EOF","ADD","SUB","MUL","DIV","POW","BITAND","BITOR","CMP","GET", \
"SET","NUMBER","STRING","GGET","GSET","MOVE","DEF","PASS", \
"JUMP","CALL","RETURN","IF","DEBUG","EQ","LE","LT","DICT", \
"LIST","NONE","LEN... | 25,194 |
def load_actions(
file_pointer, file_metadata, target_adim, action_mismatch, impute_autograsp_action
):
"""Load states from a file given metadata and hyperparameters
Inputs:
file_pointer : file object
file_metadata : file metadata row (Pandas)
target_adim ... | 25,195 |
def send_message(hookurl: str, text: str) -> int:
"""
Send a message on the channel of the Teams.
The HTTP status is returned.
parameters
----------
hookurl : str
URL for the hook to the Teams' channel.
text : str
text to send.
returns
-------
int
HTTP... | 25,196 |
def np_fft_irfftn(a, *args, **kwargs):
"""Numpy fft.irfftn wrapper for Quantity objects.
Drop dimension, compute result and add it back."""
res = np.fft.irfftn(a.value, *args, **kwargs)
return Quantity(res, a.dimension) | 25,197 |
def get_codec_options() -> CodecOptions:
"""
Register all flag type registry and get the :class:`CodecOptions` to be used on ``pymongo``.
:return: `CodecOptions` to be used from `pymongo`
"""
return CodecOptions(type_registry=TypeRegistry(type_registry)) | 25,198 |
def get_frame_lims(x_eye, y_eye, x_nose, y_nose, view, vertical_align='eye'):
"""Automatically compute the crop parameters of a view using the eye and nose and reference.
Note that horizontal/vertical proportions are currently hard-coded.
Parameters
----------
x_eye : float
x position of t... | 25,199 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.