content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def feature_norm_ldc(df):
"""
Process the features to obtain the standard metrics in LDC mode.
"""
df['HNAP'] = df['HNAC']/df['ICC_abs']*100
df['TCC'] = (df['ICC_abs']+df['DCC_abs'])/df['VOL']
df['ICC'] = df['ICC_abs']/df['VOL']
df['DCC'] = df['DCC_abs']/df['VOL']
return df | 60e3ef31c0be07179854de3191c2c75f4ec2cb4d | 18,252 |
def dice_jaccard(y_true, y_pred, y_scores, shape, smooth=1, thr=None):
"""
Computes Dice and Jaccard coefficients.
Args:
y_true (ndarray): (N,4)-shaped array of groundtruth bounding boxes coordinates in xyxy format
y_pred (ndarray): (N,4)-shaped array of predicted bounding boxes coordinates... | ed3a043b53d843e05ff3e32954eb9dbc2939b6ca | 18,253 |
def forward_pass(output_node, sorted_nodes):
"""
Performs a forward pass through a list of sorted nodes.
Arguments:
`output_node`: A node in the graph, should be the output node (have no outgoing edges).
`sorted_nodes`: A topologically sorted list of nodes.
Returns the output Node's v... | a91c5b7ebef98815a47b26d58a680b36098969d5 | 18,254 |
def qr_decomposition(q, r, iter, n):
"""
Return Q and R matrices for iter number of iterations.
"""
v = column_convertor(r[iter:, iter])
Hbar = hh_reflection(v)
H = np.identity(n)
H[iter:, iter:] = Hbar
r = np.matmul(H, r)
q = np.matmul(q, H)
return q, r | 94aa433e31e93dc36f67f579cb03f67930cfabc4 | 18,255 |
import logging
import torch
import operator
def build_detection_train_loader(cfg, mapper=None):
"""
A data loader is created by the following steps:
1. Use the dataset names in config to query :class:`DatasetCatalog`, and obtain a list of dicts.
2. Coordinate a random shuffle order shared among all p... | 007b09ce00814264b3264798d4a0afd05c23d6eb | 18,257 |
def discRect(radius,w,l,pos,gap,layerRect,layerCircle,layer):
"""
This function creates a disc that is recessed inside of a rectangle. The
amount that the disc is recessed is determined by a gap that surrounds the
perimeter of the disc. This much hangs out past the rectangle to couple to
a bus waveguide.Calls sub... | 1cb5f505fb868f31771fe6e48faa6399d8b051ad | 18,258 |
def sub_factory():
"""Subscript text: <pre>H[sub]2[/sub]O</pre><br />
Example:<br />
H[sub]2[/sub]O
"""
return make_simple_formatter("sub", "<sub>%(value)s</sub>"), {} | 4f721d0713c1a2be496a45c1bf7abe8766572135 | 18,259 |
from typing import Tuple
def train_test_split(
structures: list, targets: list, train_frac: float = 0.8
) -> Tuple[Tuple[list, list], Tuple[list, list]]:
"""Split structures and targets into training and testing subsets."""
num_train = floor(len(structures) * train_frac)
return (
(structures[:... | 279fbe353bf07aa9b9654f4be4c21cf248f2c8bb | 18,260 |
def reset_password(token):
"""
Handles the reset password process.
"""
if not current_user.is_anonymous():
return redirect(url_for("forum.index"))
form = ResetPasswordForm()
if form.validate_on_submit():
user = User.query.filter_by(email=form.email.data).first()
expired... | c34d090b09a236eecfe101d66ec0daaf3c08eb87 | 18,261 |
def delete(vol_path):
"""
Delete a kv store object for this volume identified by vol_path.
Return true if successful, false otherwise
"""
return kvESX.delete(vol_path) | 5d120b6a509119587df5f2dc9f1436115b01a257 | 18,262 |
import uuid
def get_tablespace_data(tablespace_path, db_owner):
"""This function returns the tablespace data"""
data = {
"name": "test_%s" % str(uuid.uuid4())[1:8],
"seclabels": [],
"spcacl": [
{
"grantee": db_owner,
"grantor": db_owner,
... | 3272e9b941d6bfb426ed754eed7f956c4c0933f4 | 18,263 |
def join_chunks(chunks):
"""empty all chunks out of their sub-lists to be split apart again by split_chunks(). this is because chunks now
looks like this [[t,t,t],[t,t],[f,f,f,][t]]"""
return [item for sublist in chunks for item in sublist] | a5daf41ba3fa6e7dafc4f05b29cc5aeaa397d5a5 | 18,264 |
def urls_equal(url1, url2):
"""
Compare two URLObjects, without regard to the order of their query strings.
"""
return (
url1.without_query() == url2.without_query()
and url1.query_dict == url2.query_dict
) | f2cbcf111cd5d02fa053fbd373d24b2dab047dfc | 18,265 |
def bytes_to_ints(bs):
"""
Convert a list of bytes to a list of integers.
>>> bytes_to_ints([1, 0, 2, 1])
[256, 513]
>>> bytes_to_ints([1, 0, 1])
Traceback (most recent call last):
...
ValueError: Odd number of bytes.
>>> bytes_to_ints([])
[]
"""
if len(bs) % 2 != 0:... | e8ac9ec973ff58973703e3e109da5b45d3f9d802 | 18,266 |
import site
def canRun(page):
""" Returns True if the given check page is still set to "Run";
otherwise, returns false. Accepts one required argument, "page."
"""
print("Checking checkpage.")
page = site.Pages[page]
text = page.text()
if text == "Run":
print("We're good!")
retur... | 3cb1276d82ffeadb1a730bb2eb1c1f3427905e94 | 18,268 |
def _bgp_predict_wrapper(model, *args, **kwargs):
"""
Just to ensure that the outgoing shapes are right (i.e. 2D).
"""
mean, cov = model.predict_y(*args, **kwargs)
if len(mean.shape) == 1:
mean = mean[:, None]
if len(cov.shape) == 1:
cov = cov[:, None]
return mean, cov | 23bb62927e767057df94ef8b95b57874fc078d7f | 18,270 |
import numpy
def max_pool(images, imgshp, maxpoolshp):
"""
Implements a max pooling layer
Takes as input a 2D tensor of shape batch_size x img_size and performs max pooling.
Max pooling downsamples by taking the max value in a given area, here defined by
maxpoolshp. Outputs a 2D tensor of shape b... | acbbfb686f77dc6e05f385b2addc8f49e7f344d3 | 18,272 |
def rmean(A):
""" Removes time-mean of llc_4320 3d fields; axis=2 is time"""
ix,jx,kx = A.shape
Am = np.repeat(A.mean(axis=2),kx)
Am = Am.reshape(ix,jx,kx)
return A-Am | 39edcdca0cc4d411c579991086bf555d65686020 | 18,273 |
def build_request_url(base_url, sub_url, query_type, api_key, value):
"""
Function that creates the url and parameters
:param base_url: The base URL from the app.config
:param sub_url: The sub URL from the app.config file. If not defined it will be: "v1/pay-as-you-go/"
:param query_type: The query ... | ecf3ef0a3d7d5591b1f6aa9787f4f2984688f9f2 | 18,275 |
import re
def snake_to_camel(action_str):
"""
for all actions and all objects unsnake case and camel case.
re-add numbers
"""
if action_str == "toggle object on":
return "ToggleObjectOn"
elif action_str == "toggle object off":
return "ToggleObjectOff"
def camel(match):
... | c71745c02fc712e2b463e7bcb022bfca41c2efd4 | 18,276 |
from datetime import datetime
def todayDate() -> datetime.date:
"""
:return: ex: datetime.date(2020, 6, 28)
"""
return datetime.date.today() | dc9dae8bbeaabf5c8d7d9e3509d1e331e2c609ff | 18,277 |
def lookup_facade(name, version):
"""
Given a facade name and version, attempt to pull that facade out
of the correct client<version>.py file.
"""
for _version in range(int(version), 0, -1):
try:
facade = getattr(CLIENTS[str(_version)], name)
return facade
ex... | eb76df1f7f3a9991c3e283643a52784c9d65f4f1 | 18,278 |
import time
def create_service(netUrl, gwUrl, attributes, token):
"""
Create NFN Service in MOP Environment.
:param netUrl: REST Url endpoint for network
:param gwUrl: REST Url endpoint for gateway
:param serviceAttributes: service paramaters, e.g. service type or name, etc
:param token: see... | 848f8375273ec4583a6c5d361c8a319ff43ba2a8 | 18,279 |
def _drawBlandAltman(mean, diff, md, sd, percentage, limitOfAgreement, confidenceIntervals, detrend, title, ax, figureSize, dpi, savePath, figureFormat, meanColour, loaColour, pointColour):
"""
Sub function to draw the plot.
"""
if ax is None:
fig, ax = plt.subplots(1,1, figsize=figureSize, dpi=dpi)
plt.rcParam... | 43bf53cd4594c1ed58860a6127f40f6345bea6ba | 18,280 |
def rename_columns(df):
"""This function renames certain columns of the DataFrame
:param df: DataFrame
:type df: pandas DataFrame
:return: DataFrame
:rtype: pandas DataFrame
"""
renamed_cols = {"Man1": "Manufacturer (PE)",
"Pro1": "Model (PE)",
"Man2"... | 9c22747d7c6da20cab1593388db5575a38aa313f | 18,281 |
import requests
import json
def get_github_emoji(): # pragma: no cover
"""Get Github's usable emoji."""
try:
resp = requests.get(
'https://api.github.com/emojis',
timeout=30
)
except Exception:
return None
return json.loads(resp.text) | 533a56e2e59b039cbc45ab5acb7ab4e8487e4ad9 | 18,282 |
def transport_stable(p, q, C, lambda1, lambda2, epsilon, scaling_iter, g):
"""
Compute the optimal transport with stabilized numerics.
Args:
p: uniform distribution on input cells
q: uniform distribution on output cells
C: cost matrix to transport cell i to cell j
lambda1: re... | 584607e57b4d216633ef0a03c2cb06726b0f423f | 18,283 |
def add(A: Coord, B: Coord, s: float = 1.0, t: float = 1.0) -> Coord:
"""Return the point sA + tB."""
return (s * A[0] + t * B[0], s * A[1] + t * B[1]) | 53c2f750199d785140154881fdc0ace31b9e2472 | 18,284 |
def from_binary(bin_data: str, delimiter: str = " ") -> bytes:
"""Converts binary string into bytes object"""
if delimiter == "":
data = [bin_data[i:i+8] for i in range(0, len(bin_data), 8)]
else:
data = bin_data.split(delimiter)
data = [int(byte, 2) for byte in data]
return bytes(da... | f16706da2d5b9ae5984a35a13ebd02ae94581153 | 18,285 |
def one_on_f_weight(f, normalize=True):
""" Literally 1/f weight. Useful for fitting linspace data in logspace.
Parameters
----------
f: array
Frequency
normalize: boolean, optional
Normalized the weight to [0, 1].
Defaults to True.
Returns
-------
weight: array... | 54301aa7480e6f3520cbfcccfa463a2a02d34b9c | 18,287 |
def load_randomdata(dataset_str, iter):
"""Load data."""
names = ['x', 'y', 'tx', 'ty', 'allx', 'ally', 'graph']
objects = []
for i in range(len(names)):
with open("data/ind.{}.{}".format(dataset_str, names[i]), 'rb') as f:
if sys.version_info > (3, 0):
objects.append... | 476a54078680bb711a77fc9e3900192a1ef3b811 | 18,289 |
def plot(figsize=None, formats=None, limit=100, titlelen=10, **kwargs):
"""Display an image [in a Jupyter Notebook] from a Quilt fragment path.
Intended for use with `%matplotlib inline`.
Convenience method that loops over supblots that call
`plt.imshow(image.imread(FRAG_PATH))`.
Keyword arguments... | f1b72c952d1c517ba4f09e03af8463a73d2c8759 | 18,290 |
def tresize(tombfile, keyfile, passphrase, newsize):
"""
Resize a tomb.
Keyfile, passphrase and new size are needed.
"""
cmd = ['tomb',
'resize',
tombfile,
'-k',
keyfile,
'--unsafe',
'--tomb-pwd',
sanitize_passphrase(passphrase),
'-s',
... | 334a722b79aec80bc4a95c67a0b155653e29eb10 | 18,291 |
def auto_z_levels(fid, x, y, variable, t_idx, n_cont, n_dec):
"""
list(float) = auto_z_levels(fid, variable, t_idx, n_cont, n_dec)
... # contour lines
... # post .
"""
fig, ax = plt.subplo... | f80020c01a661412fb79d23f6081bdb94a471102 | 18,292 |
def _DefaultValueConstructorForField(field):
"""Returns a function which returns a default value for a field.
Args:
field: FieldDescriptor object for this field.
The returned function has one argument:
message: Message instance containing this field, or a weakref proxy
of same.
That function in... | 3a468e2850aaf9707ee1229eeb009ef5c013f1b6 | 18,294 |
def clean_text(dirty_text):
"""
Given a string, this function tokenizes the words of that string.
:param dirty_text: string
:return: list
input = "American artist accomplishments american"
output = ['accomplishments', 'american', 'artist']
"""
lower_dirty_text = dirt... | 1df63ea0c9be5a518d2fd1f931772080962f878f | 18,295 |
def GetCurrentUserController(AuthJSONController):
""" Return the CurrentUserController in the proper scope """
class CurrentUserController(AuthJSONController):
""" Controller to return the currently signed in user """
def __init__(self, toJson):
""" Initialize with the Json ... | ee710cd4d65982cf01d17fba130b7bb83dffd617 | 18,296 |
import numpy
def fft_in_range(audiomatrix, startindex, endindex, channel):
"""
Do an FFT in the specified range of indices
The audiomatrix should have the first index as its time domain and
second index as the channel number. The startindex and endinex
select the time range to use, and the cha... | 30ce104795d0809f054439ba32f47d33528ecbff | 18,297 |
def drop_arrays_by_name(gt_names, used_classes):
"""Drop irrelevant ground truths by name.
Args:
gt_names (list[str]): Names of ground truths.
used_classes (list[str]): Classes of interest.
Returns:
np.ndarray: Indices of ground truths that will be dropped.
"""
inds = [i fo... | 67d711ae61f3c833fa9e8b33d4bf4bf6d99a34ad | 18,298 |
def get_data_table_metas(data_table_name, data_table_namespace):
"""
Gets metas from meta table associated with table named `data_table_name` and namespaced `data_table_namespace`.
Parameters
---------
data_table_name : string
table name of this data table
data_table_namespace : string
... | 8b4ee249112d399c429a33fed82d9cb01404d441 | 18,299 |
def get_at_content(sequence):
"""Return content of AT in sequence, as float between 0 and 1, inclusive. """
sequence = sequence.upper()
a_content = sequence.count('A')
t_content = sequence.count('T')
return round((a_content+t_content)/len(sequence), 2) | 6316d29cdb9d7129f225f2f79a50485fb6919e32 | 18,300 |
def page_not_found(e):
"""Handle nonexistin pages."""
_next = get_next_url()
if _next:
flash("Page Not Found", "danger")
return redirect(_next)
return render_template("404.html"), 404 | 9267c65fb842309cf1e877239be4d7fff7b1b634 | 18,301 |
def test_query(p: int = 1) -> int:
"""
Example 2 for a unit test
:param p: example of description
:return: return data
"""
return p | 69c01914db1d7a5cebf1c4e78f7c5dc7f778b4b4 | 18,302 |
def mirror_1d(d, xmin=None, xmax=None):
"""If necessary apply reflecting boundary conditions."""
if xmin is not None and xmax is not None:
xmed = (xmin+xmax)/2
return np.concatenate((2*xmin-d[d < xmed], d, 2*xmax-d[d >= xmed]))
elif xmin is not None:
return np.concatenate((2*xmin-d, ... | 0b538222dd227171ac4a3cf1ac2d8a30361eccf1 | 18,303 |
def calc_vertical_avg(fld,msk):
"""Compute vertical average, ignoring continental or iceshelf points """
# Make mask of nans, assume input msk is 3D of same size as fld 3 spatial dims
nanmsk = np.where(msk==1,1,np.NAN)
v_avg = fld.copy()
v_avg.values = v_avg.values*msk.values
if 'Z' in... | 7cd512cf2642864e9974e18ef582f541f65b3e96 | 18,304 |
def replace(data, match, repl):
"""Replace values for all key in match on repl value.
Recursively apply a function to values in a dict or list until the input
data is neither a dict nor a list.
"""
if isinstance(data, dict):
return {
key: repl if key in match else replace(value,... | 1b3dc8ac7521ec199cf74ebc8f4d8777827ab9fc | 18,306 |
import time
def get_current_date() ->str:
"""Forms a string to represent the current date using the time module"""
if len(str(time.gmtime()[2])) == 1:
current_date = str(time.gmtime()[0]) + '-' + str(time.gmtime()[1]) + '-0' + str(time.gmtime()[2])
else:
current_date = str(time.gmtime()[0]... | 480d44fc0153407960eacb875474fc02cb17c6c3 | 18,307 |
def to_jsobj(obj):
"""Convert a Jsonable object to a JSON object, and return it."""
if isinstance(obj, LIST_TYPES):
return [to_jsobj(o) for o in obj]
if obj.__class__.__module__ == "builtins":
return obj
return obj.to_jsobj() | ffd43b2d49f6dd0d3b6608a601e3bccc1be1a289 | 18,308 |
def EVAL_find_counter_exemplars(latent_representation_original, Z, idxs, counter_exemplar_idxs):
"""
Compute the values of the goal function.
"""
# prepare the data to apply the diversity optimization
data = np.zeros((len(idxs), np.shape(Z)[1]))
for i in range(len(idxs)):
data[i] = Z[i... | 985d260c74e78ffa6a47a52d6d5d30043b0b5495 | 18,309 |
from re import M
def min_energy(bond):
"""Calculate minimum energy.
Args:
bond: an instance of Bond or array[L1*L2][3].
"""
N_unit = L1*L2
coupling = bond.bond if isinstance(bond, Bond) else bond
# Create matrix A
a = np.zeros((N_unit, N_unit), dtype=float)
for i in range(N_u... | e86adbde2cbb5135962360fd67c45704c935c123 | 18,310 |
from typing import Tuple
def find_result_node(flat_graph: dict) -> Tuple[str, dict]:
"""
Find result node in flat graph
:return: tuple with node id (str) and node dictionary of the result node.
"""
result_nodes = [(key, node) for (key, node) in flat_graph.items() if node.get("result")]
if le... | d0aa0e7ba71c4eb9412393a3bea40965db1525fe | 18,311 |
import string
import random
def password_generator(size=25, chars=string.ascii_uppercase + string.ascii_lowercase + string.digits):
"""Returns a random 25 character password"""
return ''.join(random.choice(chars) for _ in range(size)) | 66cedb858d7ddef9b93b4f9ed8ffd854a722c14b | 18,312 |
def create_cleaned_df(df, class_label_str):
"""Transform the wide-from Dataframe (df) from main.xlsx into one with
unique row names, values 0-1001 as the column names and a label column
containing the class label as an int.
Parameters
----------
df : pandas DataFrame
A DataFrame read in... | ac40ce5af2221db6e984537dfd3a8dcb5f25a4a7 | 18,313 |
def uni_to_int(dxu, x, lambda_val):
"""
Translates from single integrator to unicycle dynamics.
Parameters
----------
dxu :
Single integrator control input.
x :
Unicycle states (3 x N)
lambda_val :
Returns
-------
dx :
"""
n = dxu.shape[1]
dx = np... | bfd9f0f0e62fbedb9611f762267644ecb2b3de30 | 18,314 |
import struct
def pack_binary_command(cmd_type, cmd_args, is_response=False):
"""Packs the given command using the parameter ordering specified in GEARMAN_PARAMS_FOR_COMMAND.
*NOTE* Expects that all arguments in cmd_args are already str's.
"""
expected_cmd_params = GEARMAN_PARAMS_FOR_COMMAND.get(cmd_t... | bbe87233d338344ef2ed21b9555fcd4c22c959dc | 18,315 |
import cupy as cp
import cupyx.scipy.sparse.linalg as cp_linalg
def get_adjacency_spectrum(graph, k=np.inf, eigvals_only=False, which='LA', use_gpu=False):
"""
Gets the top k eigenpairs of the adjacency matrix
:param graph: undirected NetworkX graph
:param k: number of top k eigenpairs to obtain
... | aef39f929c949edb13604c0e83b01b4d6025f06d | 18,316 |
def make_system(*args, **kwargs):
"""
Factory function for contact systems. Checks the compatibility between the
substrate, interaction method and surface and returns an object of the
appropriate type to handle it. The returned object is always of a subtype
of SystemBase.
Parameters:
------... | 06d0fbd8eb8ec6e39ec6aabb2192ab8f3455846e | 18,317 |
def place_owner_list(user_id):
"""
It retrieves the list of places for which the user is the owner.
Parameters:
- user_id: id of the user, which is owner and wants to get its own places.
Returns a tuple:
- list of Places owned by the user (empty if the user is not an owner)
- status messag... | ea2c0df7f4e72bd0b7ace5ca9c341a71fd651b32 | 18,319 |
def job_met_heu(prob_label, tr, te, r, ni, n):
"""MeanEmbeddingTest with test_locs randomized.
tr unused."""
# MeanEmbeddingTest random locations
with util.ContextTimer() as t:
met_heu = tst.MeanEmbeddingTest.create_fit_gauss_heuristic(te, J, alpha, seed=180)
met_heu_test = met_heu.perf... | 6aabf3c2628ecdb98b1ae939040a823be307c6f5 | 18,320 |
def download():
"""Unchanged from web2py.
```
allows downloading of uploaded files
http://..../[app]/default/download/[filename]
```
"""
return response.download(request, db) | 65e0e27b96b6701f2e04c98be702819908647956 | 18,321 |
def action_id2arr(ids):
""" Converts action from id to array format (as understood by the environment) """
return actions[ids] | 4d3f54078e99c73e0509b36ee39806c721690551 | 18,324 |
from promgen import models
def breadcrumb(instance=None, label=None):
"""
Create HTML Breadcrumb from instance
Starting with the instance, walk up the tree building a bootstrap3
compatiable breadcrumb
"""
def site(obj):
yield reverse("site-detail"), obj.domain
def shard(obj):
... | 5fec6c8b6d1bfdadec9405b3a4b73b119d7357f9 | 18,327 |
from typing import Optional
def get_domain(arn: Optional[str] = None,
opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetDomainResult:
"""
The resource schema to create a CodeArtifact domain.
:param str arn: The ARN of the domain.
"""
__args__ = dict()
__args__['arn']... | bed4130d5ec77f859cfa7e200794990792b0d2e8 | 18,330 |
def collect_properties(service_instance, view_ref, obj_type, path_set=None, include_mors=False):
"""
Collect properties for managed objects from a view ref
Check the vSphere API documentation for example on retrieving
object properties:
- http://goo.gl/erbFDz
Original Source: https://git... | 98cc1f6baa38f6c82452a0c3c5efb13a86a17b9e | 18,331 |
import signal
def _timeout(seconds):
"""Decorator for preventing a function from running for too long.
Inputs:
seconds (int): The number of seconds allowed.
Notes:
This decorator uses signal.SIGALRM, which is only available on Unix.
"""
assert isinstance(seconds, int), "@timeout(... | dec9909e662c3943d2bba56e116d6c212201aa42 | 18,332 |
def marginal_entropy(problem: dict, train_ixs: np.ndarray, obs_labels: np.ndarray, unlabeled_ixs: np.ndarray,
batch_size: int, **kwargs) -> np.ndarray:
"""
Score is -p(x)log[p(x)] i.e. marginal entropy of the point.
:param problem: dictionary that defines the problem, containing keys:
... | 78751d2cae853f9595579578c38bf2974cea4316 | 18,333 |
def prepareNNImages(bact_img, ftsz_img, model, bacteria=False):
"""Preprocess raw iSIM images before running them throught the neural network.
Returns a 3D numpy array that contains the data for the neural network and the
positions dict generated by getTilePositions for tiling.
"""
# Set iSIM speci... | b43f064ebbb63043db047cc406ad64df1edb0b44 | 18,334 |
def get_key(val):
"""
Get dict key by value
:param val:
:return:
"""
for key, value in HANDSHAKE.items():
if val == value:
return key | df5924127bec434cadbfae3a4d9e347c55678ae5 | 18,335 |
import re
def valid_text(val, rule):
"""Return True if regex fully matches non-empty string of value."""
if callable(rule):
match = rule(val)
else:
match = re.findall(rule, val)
return (False if not match or not val else
True if match is True else
match[0] == va... | aa6f6ac3a3210d34b44eba1f2e8e8cff851ff038 | 18,336 |
def settings():
"""Render the settings page."""
c = mongo.db[app.config['USERS_COLLECTION']]
user = c.find_one({'username': current_user.get_id()})
if not user:
return render_template()
user['id'] = str(user['_id'])
user.pop('_id', None)
return render_template('settings.html', user=u... | 3a6e3cb38680aea581f3fda1edb11fb0237df355 | 18,337 |
def exportAllScansS3(folder_id):
""" Exports all Tenable scans found in a folder to S3. """
scan_list = []
scans = client.scan_helper.scans(folder_id=folder_id)
for scan in scans:
if scan.status() != 'completed':
continue
scan.download("./%s.html" % scan.details().info.name, format='html')
s... | 2f460d5cc0d96bfcaab8fca8d1f103120ae78ca4 | 18,338 |
def download_handler(resource, _, filename=None, inline=False, activity_id=None):
"""Get the download URL from LFS server and redirect the user there
"""
if resource.get('url_type') != 'upload' or not resource.get('lfs_prefix'):
return None
context = get_context()
data_dict = {'resource': re... | 16fcf2ae97ff5d8d2d0d206c1e3035092a034006 | 18,341 |
def body_open():
"""open the main logic"""
return " @coroutine\n def __query(__connection):" | d8792f2b3237f024f20a12c6b7d371af1dbdb21e | 18,342 |
import sqlite3
def db_add_entry(user_auth,\
name:str, user_id:str, user_pw:str, url:str=''):
"""
Add an entry into the credentials database, and returns the inserted row.
If insertion fails, return None.
"""
# SQL Query
sql = f'INSERT INTO {DB_TABLE}'
sql += '(name, user_id, user_pw, ... | 217c54215c9ee49ed8a32b6093e2b274ce0fe7fe | 18,343 |
def First():
"""(read-only) Sets the first sensor active. Returns 0 if none."""
return lib.Sensors_Get_First() | 255eb920dae36a01f5e430c44a6922db7eaac0c9 | 18,344 |
def rch_from_model_ds(model_ds, gwf):
"""get recharge package from model dataset.
Parameters
----------
model_ds : xarray.Dataset
dataset with model data.
gwf : flopy ModflowGwf
groundwaterflow object.
Returns
-------
rch : flopy ModflowGwfrch
rch package
""... | 6af1fef950a951026d082762fd1dce99af7a3ab1 | 18,345 |
def _drawdots_on_origin_image(mats, usage, img, notation_type, color=['yellow', 'green', 'blue', 'red']):
"""
For visualizatoin purpose, draw different color on original image.
:param mats:
:param usage: Detection or Classfifcation
:param img: original image
:param color: color list for each cat... | 12ae7544c1ddc415c237835cb14b112e186d0d15 | 18,346 |
def scale(*args, x = 1, y = 1):
"""
Returns a transformation which scales a path around the origin by the specified amount.
`scale(s)`: Scale uniformly by `s`.
`scale(sx, sy)`: Scale by `sx` along the x axis and by `sy` along the y axis.
`scale(x = sx)`: Scale along the x axis only.
`scale(y = sy)`: Scale along... | 4853a2dd4dd8145cfbd502a38531a769674c203c | 18,347 |
async def async_setup_entry(hass, config_entry):
"""Set up Tile as config entry."""
websession = aiohttp_client.async_get_clientsession(hass)
client = await async_login(
config_entry.data[CONF_USERNAME],
config_entry.data[CONF_PASSWORD],
session=websession,
)
async def asyn... | 0aa031a56e32335cbe0aab83ff686eb970803b8c | 18,350 |
def get_selection_uri_template():
"""
Utility function, to build Selection endpoint's Falcon uri_template string
>>> get_selection_uri_template()
'/v1/source/{source_id}/selection.{type}'
"""
str_source_uri = get_uri_template(source.str_route)
path_selection = selection.str_route
param... | ec51a7ecc9476dfd060e717c11f4db9255a756dc | 18,351 |
def conv_single_step(a_slice_prev, W, b):
"""
Apply one filter defined by parameters W on a single slice (a_slice_prev) of the output activation
of the previous layer.
Arguments:
a_slice_prev -- slice of input data of shape (f, f, n_C_prev)
W -- Weight parameters contained in a window - ma... | 08528925783a6ad2e0d29e602aafe44082a8c50c | 18,352 |
def _is_pyqt_obj(obj):
"""Checks if ``obj`` wraps an underlying C/C++ object."""
if isinstance(obj, QtCore.QObject):
try:
obj.parent()
return True
except RuntimeError:
return False
else:
return False | 7be1750807eaee9ab54ee144019909d3c6890c65 | 18,353 |
from typing import Optional
from typing import Tuple
def get_optimizer(
optim_type: str,
optimizer_grouped_parameters,
lr: float,
weight_decay: float,
eps: Optional[float] = 1e-6,
betas: Optional[Tuple[float, float]] = (0.9, 0.999),
momentum: Optional[float] = 0... | b80ca6d38ada3aba310656c7609e73a34d8555b7 | 18,354 |
def forward(observations, transitions, sequence_len, batch=False):
"""Implementation of the forward algorithm in Keras.
Returns the log probability of the given observations and transitions
by recursively summing over the probabilities of all paths through
the state space. All probabilities are in loga... | 16e104ee3e4a55903b2874cbef74e9e63584174c | 18,355 |
def fib(n):
"""Return the n'th Fibonacci number.
"""
if n < 0:
raise ValueError("Fibonacci numbers are only defined for n >= 0.")
return _fib(n) | e25907deae2884e3ec69ba8ae29fb362aa50dbe3 | 18,356 |
def check_column(board):
"""
list -> bool
This function checks if every column has different numbers and returns
True is yes, and False if not.
>>> check_column(["**** ****", "***1 ****", "** 3****", \
"* 4 1****", " 9 5 ", " 6 83 *", "3 1 **", " 8 2***", " 2 ****"])
False
>>> ... | b903d1b589cd2981cc374ff47f985151d341e7ec | 18,357 |
def lines_len_in_circle(r, font_size=12, letter_width=7.2):
"""Return the amount of chars that fits each line in a circle according to
its radius *r*
Doctest:
.. doctest::
>>> lines_len_in_circle(20)
[2, 5, 2]
"""
lines = 2 * r // font_size
positions = [
x + (font_... | 43a7043d1c1632a9683476ab5cfa9d19f8105230 | 18,358 |
def capacitorCorrection(m_cap):
"""Apply a correction to the measured capacitance value
to get a value closer to the real value.
One reason this may differ is measurement varies based on frequency.
The measurements are performed at 30Hz but capacitance values
are normally quoted for 1kH... | 1942c177d534bc5533bb636e10f0107c1230c81d | 18,360 |
def get_s3_keys(bucket):
"""Get a list of keys in an S3 bucket."""
keys = []
resp = s3.list_objects(Bucket=bucket)
for obj in resp['Contents']:
keys.append(obj['Key'])
return keys | 2efb2e4e9a7ac943c3e35e69a0987933957800e1 | 18,364 |
from scipy.ndimage.filters import maximum_filter, minimum_filter
def plot_maxmin_points(lon, lat, data, extrema, nsize, symbol, color='k',
plotValue=True, transform=None):
"""
This function will find and plot relative maximum and minimum for a 2D grid. The function
can be used to pl... | a1d17972540346e96337e54da72960dc9e1f8afe | 18,365 |
def _get_results(model):
"""
Helper function to get the results from the solved model instances
"""
_invest = {}
results = solph.processing.convert_keys_to_strings(model.results())
for i in ["wind", "gas", "storage"]:
_invest[i] = results[(i, "electricity")]["scalars"]["invest"]
retu... | d054ef85df5603d8b450c0e35cd65ab5fb1cc278 | 18,366 |
def subtract_overscan(ccd, overscan=None, overscan_axis=1, fits_section=None,
median=False, model=None):
"""
Subtract the overscan region from an image.
Parameters
----------
ccd : `~astropy.nddata.CCDData`
Data to have overscan frame corrected.
overscan : `~astro... | 9d5d8333949f77e86000f836051c92122b96c87b | 18,368 |
from datetime import datetime
def read_raw(omega):
"""Read the raw temperature, humidity and dewpoint values from an OMEGA iServer.
Parameters
----------
omega : :class:`msl.equipment.record_types.EquipmentRecord`
The Equipment Record of an OMEGA iServer.
Returns
-------
:class:`... | 105e07d26774288319459ebdc485d75c3a909212 | 18,369 |
import math
def get_spell_slots(pcClass, level):
"""Return a list containing the available spell slots for each spell level."""
spell_slots = []
if pcClass.casefold() == "Magic-User".casefold():
highest_spell_level = min(math.ceil(level / 2), 9)
# MU_SPELL_SLOTS[level - 1] gives first lev... | 792110a79eb00965ea72e067e47c8eff2be4c293 | 18,370 |
from datetime import datetime, timedelta
def determine_dates_to_query_on_matomo(dates_in_database):
"""
Determines which dates need to be queried on Matomo to update the dataset.
"""
# determines which dates are missing from the database and could be queried on Matomo
# NOTE: start date was set ... | 40db63fb7ff339d5c306df37cf0f4b1765b91f90 | 18,371 |
def calc_total_energy(electron_energy, atomic_distance, energy0):
"""
Calculates the total energy of H2 molecule from electron_energy by
adding proton-proton Coulomb energy and defining the zero energy
energy0. The formula:
E = E_el + E_p - E_0
where e is the total energy, E_... | 3a948dc26e7147961e9c7677ef2b8b1d8f47d0ab | 18,373 |
def k8s_stats_response():
"""
Returns K8s /stats/summary endpoint output from microk8s on Jetson Nano.
"""
with open("tests/resources/k8s_response.json", "r") as response_file:
response = response_file.read()
return response | 68413108eeea6bdd80a782b962f3a5c97e1a4b73 | 18,374 |
def display_credentials():
"""
Function to display saved credentials.
"""
return Credentials.display_credential() | 0cfb2e7529bd46ae3a05e21aeec25761c062e04b | 18,375 |
from typing import Optional
from typing import Dict
def evaluate_absence_of_narrow_ranges(
piece: Piece, min_size: int = 9,
penalties: Optional[Dict[int, float]] = None
) -> float:
"""
Evaluate melodic fluency based on absence of narrow ranges.
:param piece:
`Piece` instance
:... | 4b487f1f749f31d33852d928b1b56d1489336827 | 18,376 |
from qalgebra.core.scalar_algebra import (
One,
Scalar,
ScalarTimes,
ScalarValue,
Zero,
)
from typing import OrderedDict
def collect_scalar_summands(cls, ops, kwargs):
"""Collect :class:`.ScalarValue` and :class:`.ScalarExpression` summands.
Example::
>>> srepr... | a6b7ba05db9e9d6434f217bcc7a67f2b6f7ba22b | 18,377 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.