content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
import sys
def alpha_161(code, end_date=None, fq="pre"):
"""
公式:
MEAN(MAX(MAX((HIGH-LOW),ABS(DELAY(CLOSE,1)-HIGH)),ABS(DELAY(CLOSE,1)-LOW)),12)
Inputs:
code: 股票池
end_date: 查询日期
Outputs:
因子的值
"""
end_date = to_date_str(end_date)
func_name = sys._getframe().f_c... | befa8b4d2c3148e8b0183873dd85fb225b90d753 | 15,200 |
def WeightedCrossEntropyLoss(alpha=0.5):
"""
Calculates the Weighted Cross-Entropy Loss, which applies a factor alpha, allowing one to
trade off recall and precision by up- or down-weighting the cost of a positive error relative
to a negative error.
A value alpha > 1 decreases the false negative co... | 5746bab38e39dd6f688ea648f29e7c30d7827466 | 15,201 |
def expand_stylesheet(abbr: str, config: Config):
"""
Expands given *stylesheet* abbreviation (a special Emmet abbreviation designed for
stylesheet languages like CSS, SASS etc.) and outputs it according to options
provided in config
"""
return stringify_stylesheet(stylesheet_abbreviation(abbr, ... | 17a65d1d6f6f2205a71e6e0ab653ef723672d756 | 15,202 |
def generate_legacy_dir(ctx, config, manifest, layers):
"""Generate a intermediate legacy directory from the image represented by the given layers and config to /image_runfiles.
Args:
ctx: the execution context
config: the image config file
manifest: the image manifest file
layers: the ... | 6001820e63ac3586625f7ca29311d717cc1e4c07 | 15,203 |
def workflow_key(workflow):
"""Return text search key for workflow"""
# I wish tags were in the manifest :(
elements = [workflow['name']]
elements.extend(workflow['tags'])
elements.extend(workflow['categories'])
elements.append(workflow['author'])
return ' '.join(elements) | 57347705b605e68a286dd953de5bb157ac50628e | 15,204 |
def get_logits(input_ids,mems,input_mask,target_mask):
"""Builds the graph for calculating the final logits"""
is_training = False
cutoffs = []
train_bin_sizes = []
eval_bin_sizes = []
proj_share_all_but_first = True
n_token = FLAGS.n_token
batch_size = FLAGS.batch_size
features =... | 4719104fdbb693411a9614e8a4048cbf6b932d1f | 15,205 |
import os
def serve_protocols(environ, start_response):
"""Serve a list of all protocols.
"""
status = '200 OK'
response_headers = [('Content-type', 'text/html')]
start_response(status, response_headers)
repo = os.path.join(APP_ROOT, 'storage')
protocols = [f_name for f_name in os.listdir(... | 2c4ae7b64b5ab5c6f56acd3c8f283dc895b0f594 | 15,206 |
def _api_get_scripts(name, output, kwargs):
""" API: accepts output """
return report(output, keyword="scripts", data=list_scripts()) | 88f002646cdec6911a76aa16cec2939b32cffd33 | 15,207 |
import requests
def get_children(key):
"""
Lists all direct child usages for a name usage
:return: list of species
"""
api_url = 'http://api.gbif.org/v1/species/{key}/children'.format(
key=key
)
try:
response = requests.get(api_url)
json_response = response.json()
... | 8d4a4ca4c1231ca2c7d98f7c0cede5ecdac003d5 | 15,208 |
def _extend(obj, *args):
"""
adapted from underscore-py
Extend a given object with all the properties in
passed-in object(s).
"""
args = list(args)
for src in args:
obj.update(src)
for k, v in src.items():
if v is None:
del obj[k]
return obj | 9fe1bffcd05ac44a3587b53a71f592c462975482 | 15,209 |
from asgiref.sync import async_to_sync
import functools
def async_test(func):
"""
Wrap async_to_sync with another function because Pytest complains about
collecting the resulting callable object as a test because it's not a true
function:
PytestCollectionWarning: cannot collect 'test_foo' because... | 10127bd083230404a7bb79d764502e6354f44b5a | 15,210 |
import logging
def get_logger(lname, logfile):
"""logging setup
logging config - to be moved to file at some point
"""
logger = logging.getLogger(lname)
logging.config.dictConfig({
'version': 1,
'disable_existing_loggers': False,
'formatters': {
'standard': {... | 0a4795f383077b52b84afb882f090e0f9140fd0f | 15,211 |
def get_percentiles(data, percentiles, integer_valued=True):
"""Returns a dict of percentiles of the data.
Args:
data: An unsorted list of datapoints.
percentiles: A list of ints or floats in the range [0, 100] representing the
percentiles to compute.
integer_valued: Whether or not the values are... | 763c0c1a724b55ac4bb5b83a6831fa5aa44993fd | 15,212 |
def estimate_poster_dedpul(diff, alpha=None, quantile=0.05, alpha_as_mean_poster=False, max_it=100, **kwargs):
"""
Estimates posteriors and priors alpha (if not provided) of N in U with dedpul method
:param diff: difference of densities f_p / f_u for the sample U, np.array (n,), output of estimate_diff()
... | 5d7fe900e379418f38f6097ac8024984fc2e66fa | 15,213 |
def get_short_topic_name(test_run_name):
"""Returns the collection name for the DLQ.
Keyword arguments:
test_run_name -- the unique id for this test run
"""
return test_run_name[3:] if test_run_name.startswith("db.") else test_run_name | 6901ecd14b9cde9e0d8b7b62d11cf3c04b3b4a2e | 15,214 |
from shapely.geometry import Point, LineString
def cut_in_two(line):
"""
Cuts input line into two lines of equal length
Parameters
----------
line : shapely.LineString
input line
Returns
----------
list (LineString, LineString, Point)
... | 95df9b6b3995a930b6772a5137db3a14f10b4b26 | 15,215 |
def get_processor(aid):
"""
Return the processor module for a given achievement.
Args:
aid: the achievement id
Returns:
The processor module
"""
try:
path = get_achievement(aid)["processor"]
base_path = api.config.get_settings()["achievements"]["processor_base_p... | 941e998e0e3ee81a6e22903976959e7696dd11ef | 15,216 |
import locale
import re
def parse_price(price):
"""
Convert string price to numbers
"""
if not price:
return 0
price = price.replace(',', '')
return locale.atoi(re.sub('[^0-9,]', "", price)) | bb90aa90b38e66adc73220665bb5e6458bfe5374 | 15,217 |
def render_content(template, context={}, request=None):
"""Renderiza el contenido para un email a partir de la plantilla y el contexto.
Deben existir las versiones ".html" y ".txt" de la plantilla.
Adicionalmente, si se recibe el request, se utilizará para el renderizado.
"""
if request:
context_class = Re... | 0ef06bb3d42f737e9ae112a852460595b8bb1824 | 15,218 |
def calculate_psi(expected, actual, buckettype="bins", breakpoints=None, buckets=10, axis=0):
"""Calculate the PSI (population stability index) across all variables
Args:
expected: numpy matrix of original values
actual: numpy matrix of new values
buckettype: type of strategy for creat... | d5250a93e784ce13cc24a1d16a88929d33426c1c | 15,219 |
import subprocess
def accsum(reports):
"""
Runs accsum, returning a ClassReport (the final section in the report).
"""
report_bytes = subprocess.check_output(
[ACCSUM_BIN] + reports,
stderr=subprocess.STDOUT
)
contents = report_bytes.decode('UTF-8')
return ClassReport.from... | 7a1fe84a3f5699b75d62ab1e3a3b93cd1baef372 | 15,220 |
import requests
def get_sid(token):
"""
Obtain the sid from a given token, returns None if failed connection or other error preventing success
Do not use manually
"""
r = requests.get(url=str(URL + "app"), headers={'Accept': 'text/plain',
'author... | eaa26681f988b8c27fecf489bbf1bb1d5c460810 | 15,221 |
def generer_lien(mots, commande="http://www.lextutor.ca/cgi-bin/conc/wwwassocwords.pl?lingo=French&KeyWordFormat=&Maximum=10003&LineWidth=100&Gaps=no_gaps&store_dic=&is_refire=true&Fam_or_Word=&Source=http%3A%2F%2Fwww.lextutor.ca%2Fconc%2Ffr%2F&unframed=true&SearchType=equals&SearchStr={0}&Corpus=Fr_le_monde.txt&ColloS... | 0a646603fb538468a4ae29b102cb8250479fedce | 15,222 |
import numpy
def ring_forming_scission_grid(zrxn, zma, npoints=(7,)):
""" Build forward WD grid for a ring forming scission reaction
# the following allows for a 2-d grid search in the initial ts_search
# for now try 1-d grid and see if it is effective
"""
# Obtain the scan coordinate
... | de6e521ae28603b5afea5148f98a65f578e7b349 | 15,223 |
import re
def parse_proj(lines):
""" parse a project file, looking for section definitions """
section_regex_start = re.compile(
'\s*([0-9A-F]+) /\* ([^*]+) \*/ = {$', re.I)
section_regex_end = re.compile('\s*};$')
children_regex = re.compile('\s*([0-9A-F]+) /\* ([^*]+) \*/,', re.I)
children_regex_start = ... | 28e979a6a3c82f5669704375e8a6104f406af33f | 15,224 |
import torch
def mot_decode(heat,
wh,
reg=None,
cat_spec_wh=False,
K=100):
"""
多目标检测结果解析
"""
batch, cat, height, width = heat.size() # N×C×H×W
# heat = torch.sigmoid(heat)
# perform nms on heatmaps
heat = _nms(heat) # 默认应用3×3ma... | 22d5c8f85bd90936c46faf73ecb6c520466fb6da | 15,225 |
def get_descriptors(smiles):
""" Use RDkit to get molecular descriptors for the given smiles string """
mol = Chem.MolFromSmiles(smiles)
return pd.Series({name: func(mol) for name, func in descList.items()}) | 2107b4e1d13c2a7a02e15392fe38e1448d1772c2 | 15,226 |
def mro(*bases):
"""Calculate the Method Resolution Order of bases using the C3 algorithm.
Suppose you intended creating a class K with the given base classes. This
function returns the MRO which K would have, *excluding* K itself (since
it doesn't yet exist), as if you had actually created the class.
... | 87d259d00b073c8728833d8608fed5e4f484a987 | 15,227 |
def ends_with(s, suffix, ignore_case=False):
"""
suffix: str, list, or tuple
"""
if is_str(suffix):
suffix = [suffix]
suffix = list(suffix)
if ignore_case:
for idx, suf in enumerate(suffix):
suffix[idx] = to_lowercase(suf)
s = to_lowercase(s)
suffix = tupl... | 4b92596f95bb482a196bf2b8a07a6a954f526045 | 15,228 |
def compareVersion(self, version1, version2):
"""
:type version1: str
:type version2: str
:rtype: int
"""
# 学学
version1 = [int(val) for val in version1.split(".")]
version2 = [int(val) for val in version2.split(".")]
if len(version1) > len(version2):
min_version = version2
... | 70ff77595f61620e1dac32d29be510e0906b505b | 15,229 |
import glob
import re
def create_capital():
""" Use fy and p-t-d capital sets and ref sets to make capital datasets """
adopted = glob.glob(conf['temp_data_dir'] \
+ "/FY*_ADOPT_CIP_BUDGET.xlsx")
proposed = glob.glob(conf['temp_data_dir'] \
+ "/FY*_PROP_CIP_BUDGET.xlsx")
t... | 64abc2c73e1455d42b94039cf857534a03075c41 | 15,230 |
def gen_gt_from_quadrilaterals(gt_quadrilaterals, input_gt_class_ids, image_shape, width_stride, box_min_size=3):
"""
从gt 四边形生成,宽度固定的gt boxes
:param gt_quadrilaterals: GT四边形坐标,[n,(x1,y1,x2,y2,x3,y3,x4,y4)]
:param input_gt_class_ids: GT四边形类别,一般就是1 [n]
:param image_shape:
:param width_stride: 分割的步... | 4dfd81bd7a0f20334385bc9e1c9681d371e6f609 | 15,231 |
def monotonic(l: list):
"""Return True is list elements are monotonically increasing or decreasing.
>>> monotonic([1, 2, 4, 20])
True
>>> monotonic([1, 20, 4, 10])
False
>>> monotonic([4, 1, 0, -10])
True
"""
#[SOLUTION]
if l == sorted(l) or l == sorted(l, reverse=True):
retu... | 1f8a34943e288ea9695f040be91f18cfe82a6e48 | 15,232 |
import time
from re import DEBUG
def get_region_dimm_list(region):
"""
returns list of pmem dimms assocaited with pmem region
"""
name = 'get_region_dimm_list()'
tic = time.perf_counter()
global ndctl
dimm_list = []
# if DEBUG: print("DEBUG: Function:", __name__, "Region:", regio... | b9ecce7d4ce7cc34fcb3e8acd84252e30cadc141 | 15,233 |
from sys import path
def readme():
"""Get the long description from the README file."""
with open(path.join(project_path, 'README.rst'), encoding='utf-8') as f:
return f.read() | 043bbcfd187340ec9101410f5c22f831de10fe6d | 15,234 |
import os
def RFR_dict(input_date: str = None, cache: dict = {}) -> dict:
"""
Returns a dict with url and filenames from the EIOPA website based on the
input_date
>>> RFR_dict(datetime(2018,1,1))
{'input_date': datetime.datetime(2018, 1, 1, 0, 0),
'reference_date': '20171231',
'url': 'h... | 5069be9ffd95ffd0e3a0451846635db3789694e7 | 15,235 |
import math
def get_weight(stats):
"""
Return a data point weight for the result.
"""
if stats is None or 'ci_99_a' not in stats or 'ci_99_b' not in stats:
return None
try:
a = stats['ci_99_a']
b = stats['ci_99_b']
if math.isinf(a) or math.isinf(b):
# ... | 7e44032bc9e51e5fe7522c3f51ead5e733d4107a | 15,236 |
import torch
def get_true_posterior(X: Tensor, y: Tensor) -> (Tensor, Tensor, float, float, float):
"""
Get the parameters of the true posterior of a linear regression model fit to the given data.
Args:
X: The features, of shape (n_samples, n_features).
y: The targets, of shape (n_samples... | 3431513d52905ec51bbe7b694af02a8274cbf48e | 15,237 |
def findmax(engine,user,measure,depth):
"""Returns a list of top (user,measure) pairs, sorted by measure, up to a given :depth"""
neighbors = engine.neighbors(user)
d = {v:measure(user,v) for v in neighbors}
ranked = sorted(neighbors,key=lambda v:d[v],reverse=True)
return list((v,d[v]) for v in rank... | ecf6d72f8c689f1b7af78a714e55d8fbfe57f2ad | 15,238 |
from typing import OrderedDict
def cart_update(request, pk):
"""
Add/Remove single product (possible multiple qty of product) to cart
:param request: Django's HTTP Request object,
pk: Primary key of
products to be added to cart
:return: Success message
... | 1673b299a41bdccaf6d0a27b15fbf85a0bb7028f | 15,239 |
from typing import Union
from typing import List
def hyperopt_cli(
config: Union[str, dict],
dataset: str = None,
training_set: str = None,
validation_set: str = None,
test_set: str = None,
training_set_metadata: str = None,
data_format: str = None,
experiment_name: str = "experiment",... | 8abca7e92e64216f50cab5c1d3757e01111e9512 | 15,240 |
def mlp_gradient(x, y, ws, bs, phis, alpha):
"""
Return a list containing the gradient of the cost with respect to z^(k)for each layer.
:param x: a list of lists representing the x matrix.
:param y: a list of lists of output values.
:param ws: a list of weight matrices (one for each layer)
:para... | 0e148d5b3b343a982d9332637c4f51be8b3afa3b | 15,241 |
import torch
def src_one(y: torch.Tensor, D: torch.Tensor, *,
k=None, device=None) -> torch.Tensor:
"""
y = Dx
:param y: image (h*w)
:param D: dict (class_sz, train_im_sz, h*w)
:param k:
:param device: pytorch device
:return: predict tensor(int)
"""
assert y.dim() == 1
... | b779e3313fb707bb6659fe48f59b030b9c9ae7d3 | 15,242 |
from typing import Union
from typing import Sequence
def average_false_positive_score(
y_true: Union[Sequence[int], np.ndarray, pd.Series],
y_pred: Union[Sequence[int], np.ndarray, pd.Series],
) -> float:
"""Calculates the average false positive score. Used for when we have more than 2 classes and want ou... | 4b789381e25efffc0aa811287bab8299edf6b962 | 15,243 |
import html
def display_text_paragraph(text: str):
"""Displays paragraph of text (e.g. explanation, plot interpretation)
Args:
text (str): Informational text
Returns:
html.Small: Wrapper for text paragraph
"""
return html.P(children=[text],
style={'font-size': '... | 8c4ae8f7b606b81726149891fb5db624647ba484 | 15,244 |
def is_numeric(_type) -> bool:
"""
Check if sqlalchemy _type is derived from Numeric
"""
return issubclass(_type.__class__, Numeric) | 1d604873e4043206b50ddc09c691331c4c50c49c | 15,245 |
def make_generic_time_plotter(
retrieve_data,
label,
dt,
time_unit=None,
title=None,
unit=None,
):
"""Factory function for creating plotters that can plot data over time.
The function returns a function which can be called whenever the plot should be drawn.
... | 3fa391a94973e5b98394e684d8e4018fa16811df | 15,246 |
def registration(request):
"""Registration product page
"""
if request.method == 'POST':
user_form = UserRegistrationForm(request.POST)
if user_form.is_valid():
# Create a new user object but avoid saving it yet
new_user = user_form.save(commit=False)
# Se... | d176a5027058124dfd30a247f924776a87f7aba3 | 15,247 |
def error_measure(predictions, labels):
""" calculate sum squared error of predictions """
return np.sum(np.power(predictions - labels, 2)) / (predictions.shape[0]) | 135b3b90047895ecff90aed6f4a37d73ef0ddd17 | 15,248 |
def add3(self, x, y):
"""Celery task: add numbers."""
return x + y | 0d1017953dcdd1a0791afe291ce005247547f198 | 15,249 |
def zscore(dat, mean, sigma):
"""Calculates zscore of a data point in (or outside of) a dataset
zscore: how many sigmas away is a value from the mean of a dataset?
Parameters
----------
dat: float
Data point
mean: float
Mean of dataset
sigma: flaot
Sigma of dataset
... | b11216e50632e2024af0a389184d5e1dba7ed4fd | 15,250 |
from typing import OrderedDict
from typing import Tuple
from re import S
def _create_ast_bilinear_form(terminal_expr, atomic_expr_field,
tests, d_tests,
trials, d_trials,
fields, d_fields, constants,
... | 0929f83f1cfcc6424b00d5b931017ec5af6ffaee | 15,251 |
import six
import sys
import os
def get_package_for_module(module):
"""Get package name for a module.
Helper calculates the package name of a module.
Args:
module: Module to get name for. If module is a string, try to find
module in sys.modules.
Returns:
If module contains 'pac... | 0914a6f2018a046fc13589081976f2e1a67a803f | 15,252 |
import math
def asen(x):
"""
El arcoseno de un número.
El resultado está expresado en radianes.
.. math::
\\arcsin(x)
Args:
x (float): Argumento.
Returns:
El ángulo expresado en radianes.
"""
return math.asin(x) | c52f7fc504c1eb02eb240378b14b19b0752c7299 | 15,253 |
def get_mock_response(status_code: int, reason: str, text: str):
"""
Return mock response.
:param status_code: An int representing status_code.
:param reason: A string to represent reason.
:param text: A string to represent text.
:return: MockResponse object.
"""
MockResponse = namedtup... | e1743755c64796e5644a00e26414fc16c110c1b6 | 15,254 |
import traceback
def get_user_stack_depth(tb: TracebackType, f: StackFilter) -> int:
"""Determines the depth of the stack within user-code.
Takes a 'StackFilter' function that filters frames by whether
they are in user code or not and returns the number of frames
in the traceback that are within user... | e02f1ca3ee6aeb765a09806ecded5919a28b5df0 | 15,255 |
def unused(attr):
"""
This function check if an attribute is not set (has no value in it).
"""
if attr is None:
return True
else:
return False | febc225f3924fdb9de6cfbf7eba871cce5b6e374 | 15,256 |
def compute_npipelines_xgbrf_5_6():
"""Compute the total number of XGB/RF pipelines evaluated"""
df = _load_pipelines_df()
npipelines_rf = np.sum(df['pipeline'].str.contains('random_forest'))
npipelines_xgb = np.sum(df['pipeline'].str.contains('xgb'))
total = npipelines_rf + npipelines_xgb
resul... | 7e7b9ea536564b4796dcf9eea6866a8c64ce0c4e | 15,257 |
def get_evaluate_SLA(SLA_terms, topology, evaluate_individual):
"""Generate a function to evaluate if the flow reliability and latency requirements are met
Args:
SLA_terms {SLA} -- an SLA object containing latency and bandwidth requirements
topology {Topology} -- the reference topology object f... | 81fdaa07e3fc21066ab734bef0cc71457d40fb5b | 15,258 |
def latest_consent(user, research_study_id):
"""Lookup latest valid consent for user
:param user: subject of query
:param research_study_id: limit query to respective value
If latest consent for user is 'suspended' or 'deleted', this function
will return None. See ``consent_withdrawal_dates()`` f... | 2295b592a0c1fdaf3b1ed21e065f39e73a4bb622 | 15,259 |
def microarray():
""" Fake microarray dataframe
"""
data = np.arange(9).reshape(3, 3)
cols = pd.Series(range(3), name='sample_id')
ind = pd.Series([1058685, 1058684, 1058683], name='probe_id')
return pd.DataFrame(data, columns=cols, index=ind) | 7bca3cf21f2942819c62c597af8761ec04fa91ba | 15,260 |
from typing import Tuple
def find_next_tag(template: str, pointer: int, left_delimiter: str) -> Tuple[str, int]:
"""Find the next tag, and the literal between current pointer and that tag"""
split_index = template.find(left_delimiter, pointer)
if split_index == -1:
return (template[pointer:], le... | 82d091ef6738ffbe93e8ea8a0096161fc359e9cb | 15,261 |
def hasNLines(N,filestr):
"""returns true if the filestr has at least N lines and N periods (~sentences)"""
lines = 0
periods = 0
for line in filestr:
lines = lines+1
periods = periods + len(line.split('.'))-1
if lines >= N and periods >= N:
return True;
return Fa... | d75c4d241d7c4364c410f2dbae06f1c4d439b14e | 15,262 |
def CAMNS_LP(xs, N, lptol=1e-8, exttol=1e-8, verbose=True):
"""
Solve CAMNS problem via reduction to Linear Programming
Arguments:
----------
xs : np.ndarray of shape (M, L)
Observation matrix consisting of M observations
N : int
Number of observations
lp... | e7f0416e0fa6949e50341b7a0009e574ecf6b0be | 15,263 |
def hamiltonian_c(n_max, in_w, e, d):
"""apply tridiagonal real Hamiltonian matrix to a complex vector
Parameters
----------
n_max : int
maximum n for cutoff
in_w : np.array(complex)
state in
d : np.array(complex)
diagonal elements of Hamiltonian
e : np.array(com... | 9b78d86592622100322d7a4ec031c1bd531ca51a | 15,264 |
def unique_badge():
""" keep trying until a new random badge number has been found to return """
rando = str(randint(1000000000, 9999999999))
badge = User.query.filter_by(badge=rando).first()
print("rando badge query = {}".format(badge))
if badge:
unique_badge()
return rando | 64a60dd420516bdc08a8ac2102b83e0cf92086ef | 15,265 |
def mid_price(high, low, timeperiod: int = 14):
"""Midpoint Price over period 期间中点价格
:param high:
:param low:
:param timeperiod:
:return:
"""
return MIDPRICE(high, low, timeperiod) | 7092d057da86b12b10da6928367aee705e14569a | 15,266 |
import pickle
def load_pyger_pickle(filename):
""" Load pyger data from pickle file back into object compatible with pyger plotting methods
:param filename: File name of pickled output from calc_constraints()
This is only meant to be used to read in the initial constraints object produced by
calc_co... | 23f4d4f2e3cae514ed65d62035277417c9b246a8 | 15,267 |
import sys
import os
def absPath(myPath):
""" Get absolute path to resource, works for dev and for PyInstaller """
try:
# PyInstaller creates a temp folder and stores path in _MEIPASS
base_path = sys._MEIPASS
return os.path.join(base_path, os.path.basename(myPath))
except Exception... | d1e17deb0c2adcea5b630950b4347dac9daa6f47 | 15,268 |
from typing import OrderedDict
def createitemdict(index, tf2info):
"""Take a TF2 item and return a custom dict with a limited number of
keys that are used for search"""
item = tf2info.items[index]
name = item['item_name']
classes = tf2api.getitemclasses(item)
attributes = tf2api.getitemattribu... | 9f9eceb588c7dc031bab633eadc139095806d38a | 15,269 |
def port_list(request, board_id):
"""Get ports attached to a board."""
return iotronicclient(request).port.list() | 0fcf7fc4db60678c7e5ec4606e9b12174966912f | 15,270 |
import urllib
import os
import fnmatch
import mimetypes
def _get_archive(url, mode='r', opts=None):
"""Get archive plugin for given URL."""
if opts is None:
opts = {}
logger.debug('readdata._get_archive: url %s' % url)
url_tuple = urllib.parse.urlsplit(url, scheme="file")
if os.name == 'n... | 5ae0b2ba5867ae99f4a07666365fef6084334a0c | 15,271 |
def pure_python_npairs_per_object_3d(sample1, sample2, rbins, period=None):
"""
"""
if period is None:
xperiod, yperiod, zperiod = np.inf, np.inf, np.inf
else:
xperiod, yperiod, zperiod = period, period, period
npts1, npts2, num_rbins = len(sample1), len(sample2), len(rbins)
co... | 98b45bbbf50eea9e4dfa39cfd9093ec6fc0c0459 | 15,272 |
def cal_aic(X, y_pred, centers, weight=None):
"""Ref: https://en.wikipedia.org/wiki/Akaike_information_criterion
"""
if weight is None:
weight = np.ones(X.shape[0], dtype=X.dtype)
para_num = centers.shape[0] * (X.shape[1] + 1)
return cal_log_likelihood(X, y_pred, centers, weight) - para_num | fd6f7019dcd6aec7efb21ff159541cee0e56bdfb | 15,273 |
def get_gid(cfg, groupname):
"""
[description]
gets and returns the GID for a given groupname
[parameter info]
required:
cfg: the config object. useful everywhere
groupname: the name of the group we want to find the GID for
[return value]
returns an integer representing t... | ee139abfe8904de1983e505db7bf882580768080 | 15,274 |
from typing import Set
from typing import Dict
from typing import Any
def _elements_from_data(
edge_length: float,
edge_width: float,
layers: Set[TemperatureName],
logger: Logger,
portion_covered: float,
pvt_data: Dict[Any, Any],
x_resolution: int,
y_resolution: int,
) -> Any:
"""
... | 80bef4fc80a22da823365fcdc756b6e35d19cdf2 | 15,275 |
def GetControllers(wing_serial):
"""Returns control gain matrices for any kite serial number."""
if wing_serial == m.kWingSerial01:
airspeed_table = (
[30.0, 60.0, 90.0]
)
flap_offsets = (
[-0.209, -0.209, 0.0, 0.0, 0.009, 0.009, -0.005, 0.017]
)
longitudinal_gains_min_airspeed =... | e9e557909cfb9a7e885f14d20948436b653f4f31 | 15,276 |
def rotate(mat, degrees):
"""
Rotates the input image by a given number of degrees about its center.
Border pixels are extrapolated by replication.
:param mat: input image
:param degrees: number of degrees to rotate (positive is counter-clockwise)
:return: rotated image
"""
rot_mat = cv2... | 6de73e2701fdad422497dd53d271accc1f039128 | 15,277 |
def spec_defaults():
"""
Return a mapping with spec attribute defaults to ensure that the
returned results are the same on RubyGems 1.8 and RubyGems 2.0
"""
return {
'base_dir': None,
'bin_dir': None,
'cache_dir': None,
'doc_dir': None,
'gem_dir': None,
... | 5f220168e2cc63c4572c29c17cb4192a7a5d1427 | 15,278 |
def rdict(x):
"""
recursive conversion to dictionary
converts objects in list members to dictionary recursively
"""
if isinstance(x, list):
l = [rdict(_) for _ in x]
return l
elif isinstance(x, dict):
x2 = {}
for k, v in x.items():
x2[k] = rdict(v)
... | dd09486aa76ee1a27306510a1100502bae482015 | 15,279 |
import requests
from bs4 import BeautifulSoup
def get_pid(part_no):
"""Extract the PID from the part number page"""
url = 'https://product.tdk.com/en/search/capacitor/ceramic/mlcc/info?part_no=' + part_no
page = requests.get(url)
if (page.status_code != 200):
print('Error getting page({}): {}'... | 8cc01b011e23d3bc972cb5552662b55ab998dba0 | 15,280 |
def verbatim_det_lcs_all(plags, psr, susp_text, src_text, susp_offsets, src_offsets, th_shortest):
"""
DESCRIPTION: Uses longest common substring algorithm to classify a pair of documents being compared as verbatim plagarism candidate (the pair of documents), and removing the none verbatim cases if positive
... | d233f3745bdd458fe65cbbdbc056c8cca611d755 | 15,281 |
import multiprocessing
import logging
import multiprocessing.dummy as m
import multiprocessing as m
import itertools
def autopooler(n,
it,
*a,
chunksize=1,
dummy=False,
return_iter=False,
unordered=False,
**ka):
"""Uses multiprocessing.Pool or multiprocessing.dummy.Pool to r... | 489426a16977b632dd16fe351eee167c7eb5fb0d | 15,282 |
def grow_population(initial, days_to_grow):
"""
Track the fish population growth from an initial population, growing over days_to_grow number of days.
To make this efficient two optimizations have been made:
1. Instead of tracking individual fish (which doubles every approx. 8 days which will result O... | 88b8283e5c1e6de19acb76278ef16d9d6b94de00 | 15,283 |
import PySide.QtGui as QtGui
import PyQt5.QtGui as QtGui
def get_QBrush():
"""QBrush getter."""
try:
return QtGui.QBrush
except ImportError:
return QtGui.QBrush | 548226da434077ee1d0d1d2fb4a6762faf5f091d | 15,284 |
def apply_odata_query(query: ClauseElement, odata_query: str) -> ClauseElement:
"""
Shorthand for applying an OData query to a SQLAlchemy query.
Args:
query: SQLAlchemy query to apply the OData query to.
odata_query: OData query string.
Returns:
ClauseElement: The modified query... | 666dd05856db79ce90f29e864aeaf4188bd425d0 | 15,285 |
def get_sql(conn, data, did, tid, exid=None, template_path=None):
"""
This function will generate sql from model data.
:param conn: Connection Object
:param data: data
:param did: Database ID
:param tid: Table id
:param exid: Exclusion Constraint ID
:param template_path: Template Path
... | 45ec23f3e061491ad87ea0a59b7e08e32e5183a2 | 15,286 |
import six
import base64
def bytes_base64(x):
# type: (AnyStr) -> bytes
"""Turn bytes into base64"""
if six.PY2:
return base64.encodestring(x).replace('\n', '') # type: ignore
return base64.encodebytes(bytes_encode(x)).replace(b'\n', b'') | 543b0f1105545cda516890d2d6f4c5a8059c4365 | 15,287 |
def is_planar_enforced(gdf):
"""Test if a geodataframe has any planar enforcement violations
Parameters
----------
Returns
-------
boolean
"""
if is_overlapping(gdf):
return False
if non_planar_edges(gdf):
return False
_holes = holes(gdf)
if _holes.shape[... | 0587cd351fcc7355d0767a404e446d91f8c59d4d | 15,288 |
def bson2uuid(bval: bytes) -> UUID:
"""Decode BSON Binary UUID as UUID."""
return UUID(bytes=bval) | 6fc81f03b6eabee3496bab6b407d6c665b001667 | 15,289 |
def ape_insert_new_fex(cookie, in_device_primary_key, in_model, in_serial, in_vendor):
""" Auto-generated UCS XML API Method. """
method = ExternalMethod("ApeInsertNewFex")
method.cookie = cookie
method.in_device_primary_key = in_device_primary_key
method.in_model = in_model
method.in_serial = ... | 2d10c37f26357ac9714d0dfe91967f4029857cd5 | 15,290 |
import aiohttp
import asyncio
async def get_pool_info(address, api_url="https://rest.stargaze-apis.com/cosmos"):
"""Pool value and current rewards via rest API.
Useful links:
https://api.akash.smartnodes.one/swagger/#/
https://github.com/Smart-Nodes/endpoints
"""
rewards_url = f"{api_... | 34c54c840ed3a412002b99f798c23f495e1eb75d | 15,291 |
def _process_image(filename, coder):
"""Process a single image file.
Args:
filename: string, path to an image file e.g., '/path/to/example.JPG'.
coder: instance of ImageCoder to provide TensorFlow image coding utils.
Returns:
image_buffer: string, JPEG encoding of RGB image.
height:... | 111025b6dddcf7380fd912a84154b551df4be5f3 | 15,292 |
def mnist_reader(numbers):
"""
Read MNIST dataset with specific numbers you needed
:param numbers: A list of number from 0 - 9 as you needed
:return: A tuple of a numpy array with specific numbers MNIST training dataset,
labels of the training set and the length of the training dataset.
... | 627a7fd41047383cd5869fe83efea2c2b0e2d25a | 15,293 |
import six
def _ensure_list(alist): # {{{
"""
Ensure that variables used as a list are actually lists.
"""
# Authors
# -------
# Phillip J. Wolfram, Xylar Asay-Davis
if isinstance(alist, six.string_types):
# print 'Warning, converting %s to a list'%(alist)
alist = [alist]... | bd8115dad627f4553ded17757bfb838cfdb0200b | 15,294 |
def _parse_einsum_input(operands):
"""Parses einsum operands.
This function is based on `numpy.core.einsumfunc._parse_einsum_input`
function in NumPy 1.14.
Returns
-------
input_strings : str
Parsed input strings
output_string : str
Parsed output string
operands : list ... | 8c95c3d842a29fa637e6190e006638420b8a0d83 | 15,295 |
def convert_to_numpy(*args, **kwargs):
"""
Converts all tf tensors in args and kwargs to numpy array
Parameters
----------
*args :
positional arguments of arbitrary number and type
**kwargs :
keyword arguments of arbitrary number and type
Returns
-------
list
... | 8059832fc4841b4cb96dcc77e96dd354dba399c2 | 15,296 |
async def delete_contact(
contact_key: int, hash: str, resource: Resource = Depends(get_json_resource)
):
"""
Delete the contact with the given key.
If the record has changed since the hash was obtained, a 409 error is returned.
"""
try:
await resource.delete(contact_key, hash)
excep... | f984c5ece28ac8b58bb2d2137dcc94e2f3a7bf7c | 15,297 |
import jsonschema
def update_model_instance_meta_schema(request, file_type_id, **kwargs):
"""copies the metadata schema from the associated model program aggregation over to the model instance aggregation
"""
# Note: decorator 'authorise_for_aggregation_edit' sets the error_response key in kwargs
if ... | c6f67f2f6386065919239f7d868797d97aec6874 | 15,298 |
def _calculate_permutation_scores_per_col(estimator, X, y, sample_weight, col_idx,
random_state, n_repeats, scorer):
"""Calculate score when `col_idx` is permuted."""
random_state = check_random_state(random_state)
# Work on a copy of X to to ensure thread-safety i... | 52c49ac3e4fd53490af04c9d862b506214e08f95 | 15,299 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.