content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def _auc(labels, predictions, weights=None, num_thresholds=200,
metrics_collections=None, updates_collections=None,
curve='ROC', name=None, summation_method='trapezoidal'):
"""Computes the approximate AUC via a Riemann sum.
Modified version of tf.metrics.auc. Add support for AUC computation
of ... | bf68176e5c210e4a575ff404538965767127c118 | 3,594,993 |
def list_combiners_id(component):
"""
:param component: instance of ComponentModel
:return: list of parents' id values
"""
result = ''
for combiner in component.combiners.all():
result += str(combiner.id) + ","
return result[:-1] | 5482023a8af2975361de4bb593ed1f43182aa78f | 3,594,994 |
def parse_proxy_return(r, stdout, stderr):
"""Proxies may return a variety of outputs. This handles them generally.
Parameters
----------
r : tuple, str, int, or None
Return from proxy function
stdout : file-like
Current stdout stream
stdout : file-like
Current stderr st... | 30e21b172f70a650c25c50f34982554d03b72263 | 3,594,995 |
def locationEntry(dwarf, offset):
"""
Each entry in a location list is either:
* a base address selection entry
* an end of list entry
* a location list entry
"""
beginning_address = dwarf.read_addr()
ending_address = dwarf.read_addr()
if beginning_address == dwarf.max_add... | 14ed1a0a479943a0b56325d8a9ed393aded6a456 | 3,594,996 |
from typing import Union
import time
from datetime import datetime
import calendar
import email
def format_http_timestamp(ts: Union[int, float, tuple, time.struct_time, datetime]) -> str:
"""Formats a timestamp in the format used by HTTP.
The argument may be a numeric timestamp as returned by `time.time`,
... | 0523c6f53625da85a2a46f8840a3ae24c14010e3 | 3,594,997 |
def list_users():
"""list users.
Supported paramters: ['email', 'is_admin', 'active']
"""
data = _get_request_args(
is_admin=_bool_converter,
active=_bool_converter
)
return utils.make_json_response(
200, user_api.list_users(user=current_user, **data)
) | 5560f8a78c79aaeb78cdc9a9332fb6ee4ecbebd3 | 3,594,998 |
import timeit
def exec_time(func):
"""Returns the execution time of a function"""
def wrapper(*args, **kwargs):
start_time = timeit.default_timer()
res = func(*args, **kwargs)
elapsed = timeit.default_timer() - start_time
print 'Elapsed time: %f' % elapsed
return res
return wrapper | fc93bbbc420c97f5523527ba398f2fd1287bafcb | 3,595,000 |
def prepare_single_input(pdb_input, psf_input=None):
"""Input of the CNS file.
This section will be written for any recipe even if some CNS variables
are not used, it should not be an issue.
"""
input_str = f'{linesep}! Input structure{linesep}'
if psf_input:
# if isinstance(psf_input,... | 74061f7d3b014d9711a05ba4574100ed4a6da7d8 | 3,595,001 |
def register_form():
"""
Show register form.
Author: Sémy Drif
"""
form = Register()
return render_template('register.html', form=form) | 1c31032de5cf2d30ef03cace7a73f33e58f9c9ee | 3,595,002 |
from pathlib import Path
import requests
from bs4 import BeautifulSoup
def Soup(s, features='lxml', **kw):
""" A fake class, of what BeautifulSoup should have been
It accepts a url or a file, in addition to html/xml as usual
"""
if isinstance(s, Path):
src = s.read_text()
elif s.star... | 71ac4ad935caf5a97c45710d98a9bf6980751a81 | 3,595,004 |
def getDataDict(displayName = "", data = None, icon = QIcon(":/group")):
"""
Utility function for creating a data dictionary for using the the BaseTreeItem
:param displayName: [string] which gets display by the TreeView
:param data: [*] any data the user might want to store with the item
:param ico... | cbe6b33b38ec526581d48b9e3e614846940f491e | 3,595,005 |
def prep_inv_objects(all_event_inv_params, inv_option):
"""Function to prep. inversion objects (X, y) for many events."""
# Get events and stations keys for all events:
event_keys = list(all_event_inv_params.keys())
n_events = len(event_keys)
station_keys_all_events = []
for i in range(len(event... | 4044589dfc6b2c7d2105f42b0320a27233154882 | 3,595,006 |
import copy
def manual_gradient(goal, target, emb, kb_ids, vocab, goal_struct, batch_mask, l2, k_max, max_depth, n_facts):
"""Use simple structure of model to calculate gradient manually given goal, training facts, and embedding. """
# Get nkb that includes 'fake' struct consisting of goal
kb_goal = copy... | 4671ceb3f0bf679e85fd0d60980b9dc0183cb540 | 3,595,007 |
def timeit(f):
"""
Timing decorator for a function f
:param f: a function
:return: timing
"""
def timed(*args, **kw):
"""
A timed function
:param args:
:param kw:
:return:
"""
ts = time.time()
result = f(*args, **kw)
te = t... | 7830b027e0315aebe3c957cafcc559eb0225426a | 3,595,008 |
def horizon_transform(X, y, horizon=12):
"""
For each step in the horizon, adds a new column and shifts the
target variable one step. This allows the model to be trained
on arbitrary intervals into the future.
Takes the following:
* X (array): design matrix (already lag transformed)
* y (arr... | c9fb961efacacfb36f8019bc00724b41a213a734 | 3,595,010 |
def svn_repos_db_env(*args):
"""svn_repos_db_env(svn_repos_t repos, apr_pool_t pool) -> char"""
return _repos.svn_repos_db_env(*args) | 609195a84ec2dd8bd27b778bebfb0f3f25ea1fc6 | 3,595,011 |
def divergence(vector_field):
"""Vectorized computation of divergence, also called Laplacian."""
dims = vector_field.shape
result = np.zeros(dims[:-1])
for i in range(dims[-1]):
result += np.gradient(vector_field[..., i], axis=i)
return result | 3c4826408caae5e1778b8435df7a726b88ac512d | 3,595,012 |
def _numeric_arrays(arrays, kinds="buifc"):
"""
See if a list of arrays are all numeric.
Parameters
----------
ndarrays : array or list of arrays
arrays to check if numeric.
numeric_kinds : string-like
The dtypes of the arrays to be checked. If the dtype.kind of
the ndar... | f8a9471dd3f0f99b531c1e05abda5a559488d379 | 3,595,013 |
import sqlite3
def is_unique_failure(e: sqlite3.IntegrityError) -> bool:
"""
Return if the given error is representing a foreign key
failure, where an insertion was expecting something to
exist already in the DB but it didn't.
"""
return str(e).startswith("UNIQUE constraint") | 1292002a1296cd9ced4b35b59b3f58e9040b59a7 | 3,595,014 |
def address_update_form(address_id, erroneous_form=None):
"""Show form to update an address."""
address = _get_address_or_404(address_id)
server = guest_server_service.find_server(address.server_id)
party = party_service.get_party(server.party_id)
form = erroneous_form if erroneous_form else Addres... | 4a8d5ebf0ccbe12cee67ab0f025d34482f64b8a3 | 3,595,015 |
from typing import Optional
def zk_connect(zk_addr: str,
zk_user: Optional[str] = None,
zk_secret: Optional[str] = None) -> KazooClient:
"""Connect to ZooKeeper.
On connection failure, the function attempts to reconnect indefinitely with
exponential backoff up to 3 seconds. ... | bd105cb4920507d3f1a8c889661fb346cdb24a35 | 3,595,017 |
def divide(df: 'DataFrame', numerator_col: str, denominator_col: str) -> pd.DataFrame:
"""Divides one number by another.
Args:
df: the dataframe to append a column onto
numerator_col: the name of your numerator column
denominator_col: the name of your denominator column
Returns:
... | c2b784246e737ae6f6f3692100b4ed8e19585915 | 3,595,018 |
def unit_to_qt_int(unit):
"""Create a Qt integer from a Unit
Args:
unit (Unit): The source unit
Returns: int
"""
return int(GraphicUnit(unit).value) | 7f1d7a6d1c440a1545a85c5e6a02e2af12043057 | 3,595,019 |
def read_data(data_path='sentiment-analysis-on-movie-reviews/train.tsv'):
"""
加载数据,返回数据(句子)和标签,类型为np.array
"""
train_df = pd.read_csv(data_path, sep='\t')
return train_df['Phrase'].values, train_df['Sentiment'].values | 1be96fc0d203fd5ba9c661ae7e0fba2fb19dcd84 | 3,595,020 |
def normalize(
data: xr.DataArray,
norm: xr.DataArray | None = None,
*,
group: Grouper | str,
kind: str = ADDITIVE,
) -> xr.Dataset:
"""Normalize an array by removing its mean.
Normalization if performed group-wise and according to `kind`.
Parameters
----------
data: xr.DataArr... | fe5821692cda34b7388c34c29f4f89412f649c97 | 3,595,023 |
from typing import List
def get_elements(name: str) -> List[str]:
"""
Parse a valid composition string and return a list of containing elements.
Please note that a composition has to be in a valid pymatgen format
HoB2 -> correct
hob2 -> wrong
Hob2 -> wrong
etc
Parameters
----------... | fe9c23c5cbbde97178c47942331fb4dc262ed9d4 | 3,595,024 |
import torch
def evaluate(model, dataset, labels):
""" Evaluate the valid_data on the current model.
:param model: Module
:param train_data: 2D FloatTensor
:param valid_data: A dictionary {user_id: list,
question_id: list, is_correct: list}
:return: float
"""
# Tell PyTorch you are ev... | 498b5c62a8921d698a31d8030b248ba391677536 | 3,595,025 |
def convert_bbox_to_z(bbox):
"""
Takes a bounding box in the form [x1,y1,x2,y2] and returns z in the form
[x,y,s,r] where x,y is the centre of the box and s is the scale/area and r is
the aspect ratio
"""
w = bbox[2]-bbox[0]
h = bbox[3]-bbox[1]
x = bbox[0]+w/2.
y = bbox[1]+h/2.
s = w*h #scale... | ee0a45c5b3b30cc8c72a8b65899e731b1fcd6b19 | 3,595,026 |
def getCovers80EvalStatistics(ScoresParam, topsidx, fout, name = "default"):
"""
Compute MR, MRR, MAP, and Median Rank for the covers80 dataset
:param ScoresParam: A 160x160 array holding all pairwise
scores, where the first 80 songs are in the the first 80 rows
and the second 80 songs are in the la... | 12335914b86e10b4b209a1ab740243e9de3033dd | 3,595,027 |
import re
def read_sns(fname):
"""Sensor coordinate extraction in MEG space
Parameters
----------
fname : str
Absolute path to sensor definition file.
Returns
-------
locs : numpy.array, shape = (n_points, 3)
Sensor coil location.
"""
p = re.compile(r'\d,[A-Za-z]*... | 4d37f240bc1670570002b6c54c1bde13977c38b9 | 3,595,028 |
def _get_p_y_z_halfspace(particles):
"""
This function calcualtes the probabilities of y and z half space
for a given set of particles
Parameters
----------
particles : list
List of SourceParticle
Returns
-------
p_y_halfspace : float
The probability of y half space... | fb822d7b03b4fc387fff8723d5a8d7dafe8f9bfc | 3,595,029 |
import torch
def get_data(generic_iterator, generic_loader):
"""Code to get minibatch from data iterator
Inputs:
- generic_iterator; iterator for dataset
- generic_loader; loader for dataset
Outputs:
- data; minibatch of data from iterator
- generic_iterator; iterator for dataset, reset i... | e827ab7cea13c96953260d6b157a3e6ab370c6c9 | 3,595,030 |
def open_output_file(path, columns):
""" Opens or creates output file for writing """
file = open(path, "w+")
return {
"file": file,
"writer": DictWriter(file, columns)
} | 2186d7a0bc45be7031f1f6a6c9586a6755c08a0e | 3,595,031 |
from typing import Callable
from typing import Tuple
from typing import Dict
import torch
def run_layer_benchmark(
num_repeats: int,
forward_only: bool = False,
create_layer: Callable = LayerFactory.create,
**kwargs,
) -> Tuple[float, Dict[str, int]]:
"""Benchmarks a single layer for runtime and C... | 6d7c9f5b4626bf02af52702e8247bcfc8fd31f18 | 3,595,032 |
import json
def split_cmd(cmdstr):
"""Interprets JSON and method and params"""
cmd = json.loads(cmdstr)
return cmd['method'], cmd.get('params', {}), cmd.get('rune') | cb580c244699fe9657e7e43b243ddc48e8f5d6f6 | 3,595,033 |
def byte_strings(label, length, entropy):
"""
Build byte strings of the given length with at most the given amount of
entropy.
These are cheaper for Hypothesis to construct than byte strings where
potentially the entire length is random.
"""
if len(label) + entropy > length:
raise V... | 32deff7a1e048cf56a92d6a4e295e5a51db79d80 | 3,595,034 |
def get_name(schema_url):
""" Extract the item name from it's URL
:param schema_url: the URL of the schema
:return name: the name of the schema (eg: 'item_schema.json')
"""
name = schema_url.split("/")[-1].replace("#", '')
return name | e7632dc959a4503b51cc5c3f851a063056893507 | 3,595,035 |
def TdiDecompile(mdsobject,**kwargs):
"""Decompile an MDSplus object. Format: TdiDecompile(mdsobject)"""
return _ver.tostr(_cmp.DECOMPILE(mdsobject)._setTree(**kwargs).evaluate()) | 297f302c9c69fcb30b4e4fe98b5c95e3911eb419 | 3,595,036 |
def resnet_v1(input_shape, depth, num_classes=10):
"""ResNet 版本 1 模型构建器 [a]
2 x (3 x 3) Conv2D-BN-ReLU 的堆栈
最后一个 ReLU 在快捷连接之后。
在每个阶段的开始,特征图大小由具有 strides=2 的卷积层减半(下采样),
而滤波器的数量加倍。在每个阶段中,这些层具有相同数量的过滤器和相同的特征图尺寸。
特征图尺寸:
stage 0: 32x32, 16
stage 1: 16x16, 32
stage 2: 8x8, 64
参数数量与 [... | 68831fa37c588e98aa32ccd47daf47493875c1e9 | 3,595,037 |
def movies(year):
""" Sample movies endpoint. """
fe = Key('year').eq(int(year));
pe = "#yr, title, info.rating"
# Expression Attribute Names for Projection Expression only.
ean = { "#yr": "year", }
esk = None
response = table.scan(
FilterExpression=fe,
ProjectionExpression... | 628880696287d204fa7d9324a00e8cfa42fc40e2 | 3,595,038 |
def worker_engine(dbconf):
"""Create a new stand-alone SQLAlchemy engine to be instantiated in worker
context.
"""
return create_engine(format_dsn(dbconf)) | bdcd2445ffd035cd5ad81035662afd12627ff5f3 | 3,595,039 |
def append_images(images, direction='vertical',
bg_color=(255, 255, 255), aligment='center'):
"""
Appends images in horizontal/vertical direction.
Args:
images: List of PIL images
direction: direction of concatenation, 'horizontal' or 'vertical'
bg_color: Backgroun... | 6a337e2730bf95634eff66b7aa1598a97b786d08 | 3,595,040 |
def create_time(t):
"""之后加入日 月 星期等条件"""
return (f"null null null null null {t}") | 1e5ae6c5cac9b984c4f02b8c02e58a2da5b7972f | 3,595,041 |
import logging
def rouge_eval(ref_dir, dec_dir):
"""Evaluate the files in ref_dir and dec_dir with pyrouge, returning results_dict"""
r = pyrouge.Rouge155('/home/lshekhar/ROUGE-1.5.5')
r.model_filename_pattern = '#ID#_reference.txt'
r.system_filename_pattern = '(\d+)_decoded.txt'
r.model_dir = ref_dir
r.s... | ed3326788936294eb0d6fe5b3a2f55c458e96829 | 3,595,042 |
def client(app):
"""Return a client query the web application.
:rtype: webtest.TestApp
"""
return webtest.TestApp(app) | 5dbfdf184a6b03ea9bae66057891906a0117531d | 3,595,043 |
import re
def get_populartimes_from_search(place_identifier, get_detail=False):
"""
request information for a place and parse current popularity
:param place_identifier: name and address string
:return:
"""
jdata = make_google_search_request(place_identifier)
# get info from result a... | 6a950a952a2e0237ff9ce64a798a4d2b70548c2b | 3,595,044 |
def get_roles(person_id: str = None):
"""
Returns all active roles for a particular person (or the current users if no person_id is specified).
:param person_id: The numeric ID of the person whose roles you wish to retrieve. If not specified, the roles for the logged-in user will be returned.
:returns... | 138afe16190bedd3a3186d9b29390c49d30c7a00 | 3,595,045 |
import torch
from typing import Callable
def encode_and_aggregate(input_tensor: torch.Tensor,
encoder: torch.nn.Module,
num_encoder_input_channels: int,
num_image_channels: int,
encode_channels_jointly: bool,
... | f2d65e1c2c214cfddae40dd235fba86a61866277 | 3,595,048 |
import re
def path_parameter(payload):
"""Extract container name from the path parameters
"""
path = urlsplit(payload.uri).path
match = re.match(r"^/v\d.\d{2}/[^/]+/([a-zA-Z0-9_-]+)/?", path)
if match is None:
raise UnauthorizedException(
'Container name not found in path'
... | 5dd0894d7bc6b9338ef111e5364c7a1078f6ddaf | 3,595,049 |
def _inverse(x):
"""The inverse of a 3x3 matrix
X . _inverse(x) = I
:param x: a 3x3 matrix (e.g. a list of lists) of arrays
:returns: a similar 3x3 matrix where each 3x3 is the inverse of the matrix
"""
det_x = _determinant3(x)
x_t = _transpose(x)
return [[_sign(i, j) * _determinant2(_... | 8f322d26bb52090f25cfd9b77bebba1b6e0be218 | 3,595,050 |
def max_dot_product(a, b):
"""
Given two sequences 𝑎1, 𝑎2, . . . , 𝑎𝑛 (𝑎𝑖 is the profit per click of the
𝑖-th ad) and 𝑏1, 𝑏2, . . . , 𝑏𝑛 (𝑏𝑖 is the average number of clicks per day
of the 𝑖-th slot), we need to partition them into 𝑛 pairs (𝑎𝑖, 𝑏𝑗) such
that the sum of their produc... | afdf565cf32c3bcc9e0a69a4ea565a3dcdd8f8a4 | 3,595,051 |
def Matter_power_spectrum(z, run, code, l_max, zplot, kmin=1e-4, kmax=2, number_points=2000, plot="yes", units='(Mpc/h)^3'):
"""compute matter power spectrum
Args:
z (list): array of redshifts
run (func): initialization CAMB or CLASS
code (str): "camb" or "class"
l_max (float): ... | a9416a6f12440413ac39c2ef29e96b17e6e263ee | 3,595,052 |
def apply_each(functions, *args, **kwargs):
"""Returns list containing result of applying each function to args."""
return [f(*args, **kwargs) for f in functions] | 15dc85cb155db030f4eaf2eccdbd40ed20585b82 | 3,595,053 |
def dmp_ground_monic(f, u, K):
"""Divides all coefficients by `LC(f)` in `K[X]`. """
if not u:
return dup_monic(f, K)
if dmp_zero_p(f, u):
return f
lc = dmp_ground_LC(f, u, K)
if K.is_one(lc):
return f
else:
return dmp_quo_ground(f, lc, u, K) | bcee0a3ff4c6cec677f03fc1bbd8f9d87b523ebe | 3,595,054 |
import select
async def setup_select(config, key, setter, parent, options):
"""Setup select"""
if key not in config:
return None
conf = config[key]
slct = cg.new_Pvariable(conf[CONF_ID], parent)
await select.register_select(slct, conf, options=options)
cg.add(setter(slct))
return s... | 0b91d60637918ed588733bd70b5886aca3bec40a | 3,595,055 |
def _model_delete_by_id_function_name(model):
"""Returns the name of the function to delete a model by id"""
return '{}_delete_by_id'.format(model.get_table_name()) | df3e1de727b585c1cab403dfcfea08eafe25aeec | 3,595,056 |
import time
import test
def learning(data, max_val, learning_rate, batch_size, dropout):
""" Training of the denoising autoencoder
Returns:
Autoencoder trained on a data provided by FLAGS from utils/flags.py
"""
with tf.Graph().as_default():
tf.set_random_seed(FLAGS.seed)
sta... | 7f9efecd6c53d06b50c17bc590b312d84549ab3b | 3,595,057 |
def list_all_services():
"""POST /list
List running ConPaaS services under a specific application if the user is
authenticated. Return False otherwise.
"""
return build_response(simplejson.dumps([
ser.to_dict() for ser in g.user.services.all()
])) | aa44f63d4f3ee5853ada21b2493047428ab1769a | 3,595,058 |
import copy
import sympy
def dynamic_identification_model(robo, symo):
"""
Compute the Dynamic Identification model of a robot using
Newton-Euler algorithm.
"""
# init forces vectors
Fjnt = ParamsInit.init_vec(robo)
Njnt = ParamsInit.init_vec(robo)
# init transformation
antRj, antP... | 0c609c92a4c8eb7c4f3678921254497d6e44476c | 3,595,059 |
def del_encoding(*args):
"""
del_encoding(idx) -> bool
Delete an encoding (1-based)
@param idx (C++: int)
"""
return _ida_nalt.del_encoding(*args) | bf23f0bc9ab0d1e740b6b47ab2db171b71104517 | 3,595,061 |
def runs_once(func):
"""
Decorator preventing wrapped function from running more than once.
By keeping internal state, this decorator allows you to mark a function
such that it will only run once per Python interpreter session, which in
typical use means "once per invocation of the ``fab`` program"... | 9b620ccb6832be13863ec29bd4804e6a59e1e6c5 | 3,595,062 |
from datetime import datetime
def calc_season_from_datetime(now):
"""
Retrieved the season (for northern hemisphere) based on a datetime.
"""
if (isinstance(now, datetime) and pd.notnull(now)):
now = now.date()
else:
return np.nan
now = now.replace(year=2000)
return next(se... | 28d634df65c73a92547567b22c7fe2d6cf8203d9 | 3,595,063 |
from apex import amp
from typing import Callable
def trace_model(
model: Model,
predict_fn: Callable,
batch=None,
method_name: str = "forward",
mode: str = "eval",
requires_grad: bool = False,
opt_level: str = None,
device: Device = "cpu",
predict_params: dict = None,
) -> ScriptMo... | 204c8d46fb4c238372eacf84caf98aa0315bfcf7 | 3,595,064 |
def identify_and_tag_collaborations(line, collaborations_kb):
"""Given a line where Authors have been tagged, and all other tags
and content has been replaced with underscores, go through and try
to identify extra items of data which should be placed into 'h'
subfields.
Later on, these t... | 7081cc5f15db8c7bf44054b6bf578f5aef8f3e7e | 3,595,065 |
import site
def get_docs_blueprint(app: Flask) -> Blueprint:
"""Generate a blueprint for base marXdown static files and templates."""
if app.config.get('RELATIVE_STATIC_PATHS'):
url_prefix = f'{site.get_url_prefix()}/_marxdown'
else:
url_prefix = '/_marxdown'
return Blueprint('docs', _... | fca2fdce1b6beaafa5a701d2d1c150ff286cd494 | 3,595,066 |
def calculate_bounding_box(origin: CoordinatePoint, radius: int) -> (float, float, float, float):
"""Calculates the Bounding Box for the Overpass API"""
upper_right = point_from_distance_and_angle(origin, radius, 45)
lower_left = point_from_distance_and_angle(origin, radius, 225)
return (lower_left.la... | 66d81dcb5608b8ad0212cfcc1b85f56ff3e5bccd | 3,595,067 |
def getPage(name):
"""Returns the PyOrigin.Pages() object of the page with that name.
If that name doesn't exist, None is returned.
Args:
name (str): name of the page to get
Returns:
PyOrigin.Pages(name) of what you asked for
"""
if name in pageNames():
return PyOrigin... | bdc158476f9749fc2b23bc2e142b8c5972fa3d23 | 3,595,068 |
def calculate_v5_Psi23(chi_523, chi_523_err, vn_array):
"""v5(Psi23) = chi_523*sqrt(<abs(V2)**2*abs(V3)**2>)"""
dN = real(vn_array[:, 0])
Q1 = dN*vn_array[:, 1]
Q2 = dN*vn_array[:, 2]
Q3 = dN*vn_array[:, 3]
Q5 = dN*vn_array[:, 5]
nev = len(dN)
N4_weight = dN*(dN - 1.)*(dN - 2.)*(dN - 3.... | 9b78ce2cee4643548aa080500f6d055de6d18b36 | 3,595,070 |
import requests
import json
def update_device_management_interface(serial, ip, vlan):
"""
Update Device Management Interface: https://developer.cisco.com/meraki/api-v1/#!update-device-management-interface
"""
url = f"{base_url}devices/{serial}/managementInterface"
payload = {
"wan1": {
... | eb54b14dc4be11a618b8d5edd3dea593de14abb8 | 3,595,073 |
import json
def load_user_data_from_disk(user_data_path: str) -> json:
""" Load the slack user data from the given path
:param user_data_path: path to the file with the user data.
:return: a json object with information about all slack users.
"""
print('Loading user data from {}'.format(user_dat... | ba1d680dd016e70819ca643b8543d68f5ab7becf | 3,595,074 |
import torch
def apply_transform(filter, interp_vars, filters_size, old_bilinear_interpolation=True):
""" Apply a transform specified by the interpolation_variables to a filter """
dim = 2 if len(filter.size()) == 4 else 3
if dim == 2:
if old_bilinear_interpolation:
[x0_0, x1_0], [x0... | c95171a17d3247e419e53e9cf140a722379757c3 | 3,595,076 |
def train_gauss(x):
"""
Estimates gaussian distribution from data.
(MU, COV) = TRAIN_GAUSS(X) return Maximum Likelihood estimates of mean
vector and covariance matrix estimated using training data X
"""
return np.mean(x, axis=0), np.cov(x.T, bias=True) | 25afe458b34a9475d4bb7ed83783beb96faf1812 | 3,595,077 |
def create_translation(features):
"""
Process the features to create a translation map of form
{
id: {C: translation, E, translation, T: translation},
...
}
"""
res = {}
seen_categories = set()
counter = 1
for f in features:
eng_name = f['properties']['ENGLISH... | 5e14d0a8fcbd4a03ffdeaea446db875e56e8a815 | 3,595,078 |
import json
def create_pipeline(role, pipeline_name, sagemaker_session=None, **kwarg)-> Pipeline:
"""[summary]
Args:
role ([type]): [description]
pipeline_name ([type]): [description]
sagemaker_session ([type], optional): [description]. Defaults to None.
Returns:
Pipelin... | b3528e6f6df20fa7a839c0a1982d810dcf82df27 | 3,595,079 |
def mark_all_tables_per_draw(draw, boards_data_dict):
"""
Once a draw has been drawn,
we need to update the table
with a say a * at that point
:param draw: int [number drawn]
:param boards_data_dict: dictionary of tables
"""
for key in boards_data_dict:
table = boards_data_dict[k... | e1c3fc89e5082e6b365299be86b0ba5bb8ce46b5 | 3,595,080 |
from datetime import datetime
def create_member() -> tuple:
"""
create or update member
"""
try:
member_details: dict = request.get_json()
if ("uid" in member_details) and (member_details["uid"] != ""):
uid: str = member_details.get("uid")
else:
mess... | 41bd89678f684c66f5ef73792dc4282172a64f23 | 3,595,081 |
def delete(blob_keys, rpc=None, _token=None):
"""Deletes a blob from Blobstore.
Args:
blob_keys: A single `BlobKey` instance or a list of blob keys. A blob key
can be either a string or an instance of `BlobKey`.
rpc: Optional UserRPC object.
Returns:
None.
"""
rpc = delete_async(blob_... | 3b42cc622df20443c553eb9af8eaed05a2b505a8 | 3,595,083 |
def _two_by_two_solve(m, vec):
"""Solve a 2x2 system by direct inversion.
Args:
m: A length 2 list of length 2 lists, is a 2x2 matrix of [[a, b], [c, d]].
vec: The length 2 list of length 1 lists, a vector of [e, f].
Returns:
matmul(m^{-1}, vec).
"""
a = m[0][0]
b = m[0][1]
c = m[1][0]
d =... | 21b942df7d24fec451ec3a12c51f3cd6c12120d3 | 3,595,084 |
def make_otb_feature(df: pd.DataFrame) -> pd.DataFrame:
"""Make a categorical variable: Online vs Otb game"""
domains = ['.com', '.org']
online_sites = [item for item in df['Site'].unique() if np.array(
[domain in item for domain in domains]).any()]
df['Otb'] = df['Site'].apply(
lambda ... | 3b33bda2607fbd31e209202f4742b27b52676b34 | 3,595,085 |
def galaxies_moc(field, moc_field, radius, moc_order=15):
"""
MOC with the intersection of field with galaxies
included in the 2MASS Large Galaxy Atlas.
"""
galaxies = Irsa.query_region(field, catalog="lga_v2",
spatial="Cone", radius=2*u.deg)
moc_galaxies = MOC()... | ba08d1a65e9636db2ae9643e7d27783356728f23 | 3,595,086 |
def filter_overlapping_files(files):
"""Filter combinations of overlapping files.
Uses as base comparing file the one with lowest frequency.
Parameters
----------
files: dict
dict with frequencies as keys and list of files as values.
Returns
-------
dict_files_all: dict
... | 912c058695ba5bf46ee1cb12df15419eb00d3474 | 3,595,087 |
def encrypt(src):
"""encoding"""
print(src)
value = signing.dumps(src)
print(value)
return value | 39d8e47f079f478a2cb984f5b8adb21f00df4bb0 | 3,595,088 |
def get_exons(gencode):
"""
Filter Gencode table to exons and format fields.
"""
exons = gencode.filter(hl.set(["exon", "CDS", "UTR"]).contains(gencode.feature))
exons = exons.select(
feature_type=exons.feature,
transcript_id=exons.transcript_id.split("\\.")[0],
gene_id=exons... | e8bd13193f064a4303181522f7e702f748be6a9e | 3,595,089 |
def in_unit_test_mode() -> bool:
"""
Return True if we are inside a pytest run.
This is set by `conftest.py`.
"""
return _CONFTEST_IN_PYTEST | 2726e688c8ce8ee150a027ac75d019ffcdf35f04 | 3,595,090 |
def Hex2Rgb(hex="#ffffff"):
"""
将十六进制的颜色字符串转换为 RGB 格式
https://blog.csdn.net/sinat_37967865/article/details/93203689
"""
r = int(hex[1:3], 16)
g = int(hex[3:5], 16)
b = int(hex[5:7], 16)
rgb = str(r) + "+" + str(g) + "+" + str(b) # 自定义 rgb 连接符号
return rgb | 7a71fdac7907252e945774429a61ac60702b92a1 | 3,595,094 |
def ssim(img1: np.ndarray, img2: np.ndarray) -> float:
"""
Compute Structural Similarity Index (SSIM) between two input images.
Parameters
----------
img1, img2 : ndarray
Input images of the same shape
Returns
-------
float:
SSIM between the two input images
"""
... | d0ad5725c8f3be5d98f969ec7681bcbd965abeef | 3,595,095 |
def check_output(list_of_commands):
"""
Adding check_output for python < 2.7
"""
process = subprocess.Popen(list_of_commands, stdout=subprocess.PIPE)
output = process.communicate()[0]
print output
#output, unused_err = process.communicate()
#retcode = process.poll()
#if retcode... | 90fc941eb86f9735a37ecf93bd05de2c19a3b730 | 3,595,096 |
def subset_matrix(matrix, name_list_1, name_list_2):
"""Subsetting matrix into two symetric matrices given two label lists
Parameter:
----------
matrix : Pandas DataFrame
Full similarity matrix
name_list_1 : list
list of names
name_list_2 : list
list of names
Returns:
--------
list:
list with subset... | 1b36308c73c864fa446b0bc756240d4d2a8639a6 | 3,595,097 |
def join_path_native(a, *p):
"""As join path, but makes sure an OS native path is returned. This is only
needed to play it safe on my dear windows and to assure nice paths that only
use '\'"""
return to_native_path(join_path(a, *p)) | b10a908ba96781b0cdb71f0259186c0d1164af84 | 3,595,098 |
def data_connectionconnection_id_post(connection_id, body=None): # noqa: E501
"""data_connectionconnection_id_post
creates connection.Connection # noqa: E501
:param connection_id: Id of connection
:type connection_id: str
:param body: connection.Connection to be added to list
:type body: dict... | eb8a8541a3b33894f1faf76a6cc5a46c90a952a8 | 3,595,100 |
import ctypes
def xclCreateReadQueue(handle, q_ctx, q_hdl):
"""
Create Read Queue
:param handle:Device handle
:param q_ctx:Queue Context
:param q_hdl:Queue handle
:return:
This is used to create queue based on information provided in Queue context. Queue handle is generated if creation
... | 13854cc34f4f331b44f250f3311f5bd657dc5be6 | 3,595,101 |
async def async_setup_entry(hass: HomeAssistantType, entry: ConfigEntry):
"""Load the saved entities."""
hass.async_create_task(
hass.config_entries.async_forward_entry_setup(entry, "sensor")
)
return True | ca5fbd3af9c8a29195460c25d33d624d200fc81a | 3,595,102 |
def get_empty_frame():
"""Generate a copy of the base frame
Returns:
ndarray: Base annotated frame to modify
"""
global base_frame
return np.copy(base_frame) | 415782f5c7cebbb1dbd0c80f2d017ee710e81bb2 | 3,595,103 |
def check_energy_service_service_tech_count(ds_es_ec_map, ds_es_ec):
"""checks if combination of DS-EC-ES-ST has at least two items in it
"""
if len(ds_es_ec_map) > 1: # either multiple energy services
return True
else:
ds, es, ec = next(iter(ds_es_ec)) # this will have only one item i... | cd4a3611600983bd39ad90f138d61289c76d0ceb | 3,595,104 |
def get_feature_extractor(feature):
"""Fetches the feature extraction function associated with the given
raw logs"""
return _FEATURE_EXTRACTORS[feature] | fbb0eaf908b4f616328b72d6d876ec4edfdb726a | 3,595,105 |
import torch
def get_reward_multidimMAB(a_t, rewards):
"""define the reward function at time t
Parameters
----------
a_t : int
action
rewards : list
rewards across arms
Returns
-------
torch.FloatTensor, scalar
immediate reward at time t
"""
r_t = rew... | 918b13728d8c72df668b239b158017c4e6f799fc | 3,595,107 |
def divide_molecule(mol, a0, a1):
""" Divide a molecule into two sets of atom indices - a stationary group and a rotated group """
G = deepcopy(mol.molecules[0])
bond = (a0, a1)
if bond not in G.edges() and bond[::-1] not in G.edges():
raise RuntimeError('%s must be a bond in the molecule' % str... | 69a1e08fb836af115f4a30ce416e1141eaff8469 | 3,595,108 |
def point_to_pixel(coord, grid_dims):
"""
converts the coordinates of a dot from normalized space to pixel space
.. note::
Recall, whether normalized or in pixel space, with coordinates of the form (x,y), x represents the vertical \
position and y the horizontal position. Small x correspond... | a71c24a106eb139a30e823f662c3277be53d8311 | 3,595,109 |
def sanitize_image(author_img_url):
""" Sanitizes the text from the author string. """
if author_img_url is None:
author_img_url = "https://www.pngkey.com/png/detail/230-2301779_best-classified-apps-default-user-profile.png"
return author_img_url | e980126e589a19f0ae750dfebdcc4095c700081b | 3,595,110 |
def first_choice_hill_climbing(space: AbstractHillClimbableSpace, initial_state: AbstractHillClimbingState)\
-> AbstractHillClimbingState:
"""
get approximately best state in given space
:param space: the space on which to find approximately best state
:param initial_state: the state to begin th... | 878bfae7c09daa77fdb1785fa173df9c1e1b5b7a | 3,595,111 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.