content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
from typing import Callable
import typing
import logging
import inspect
def list_(router_generator) -> Callable:
"""
list action default using fastapi-pagination to process paginate
"""
resource = router_generator.cls()
action_func = getattr(resource, 'list')
# noinspection PyProtectedMember,... | 963e6cf6d40da9d0fdd53abf30e171e0a922eae7 | 3,625,200 |
def WD_shift_kernel(X, Y=None, l = 3, shift_range = 1):
"""Weighted degree kernel with shifts.
Compute the mixed spectrum kernel between X and Y:
K(x, y) = \sum_{d = 1}^{l} \sum_j^{L-d} \sum_{s=0 and s+j <= L}
beta_d * gamma_j * delta_s *
(k_d^{spectrum}(x[j+s:j+s+d],y[j:j+d]) + ... | 46b3259361d43eeb9cbebc2cf00b820842c0a19f | 3,625,201 |
def _populate_entity(m):
"""
"""
if not m:
return None
entity = AuthUserEntity(key=get_key_from_resource_id(m.id))
entity.username = m.username
entity.first_name = m.first_name
entity.last_name = m.last_name
entity.email = m.email
return entity | 33aa34d0211c99277c83fc2c5e02a080c39c3f35 | 3,625,202 |
from typing import List
async def cringo_card(list_of_emojis: List[List[str]]) -> List[List[str]]:
"""This makes the Cringo! card complete with headers."""
top_row = ['🇦', '🇧', '🇨', '🇩', '🇪', '🇫']
side_column = ['<:lemonface:623315737796149257>', '1️⃣', '2️⃣', '3️⃣', '4️⃣', '5️⃣', '6️⃣']
list_... | 44421d02c8b9c0b7f873e6d5ad5e8de803ac70d6 | 3,625,203 |
def count(object):
""" count(object):
Count the number of elements in the given object.
An element is defined as one of the 7 datatypes supported by ssdf
(dict/struct, tuple/list, array, string, int, float, None).
"""
n = 1
if isstruct(object) or isinstance(object, dict... | 00cc1dded43d59210751d955499696cd90bd5bdb | 3,625,204 |
def prepare(desc_file, nocheck_init):
"""Create and prepare the temporary run directory.
The temporary run directory is created with a UUID as its name.
Symbolic links are created in the directory to the files and
directories specifed to run NEMO.
The output of :command:`hg parents` is recorded in ... | 3338eaf126910cbf37990d28c9d8eedd0a634230 | 3,625,205 |
def get_http_method(query):
"""Work out if this should be GET, POST, PUT or DELETE"""
lower_query = query.strip().lower()
http_method = "GET"
for method in METHOD_MAP:
if method[0] in lower_query:
http_method = method[1]
break
return http_method | e1deabf2f4a5e331fe08936d6afaaee1a02f2b92 | 3,625,206 |
def FlowInterestEnd(builder):
"""This method is deprecated. Please switch to End."""
return End(builder) | 69819eb18842c5094444d19bc4fb94a7d163b09e | 3,625,207 |
import tensorflow as tf
from lfads_tf2.models import LFADS
import os
from sys import path
def create_trainable_class(epochs_per_generation=50):
"""Creates a tuneLFADS class with specified number of epochs per
generation. Uses static variable that can be accessed by instances.
"""
# make epochs_per_gen... | 827869b9d62170fd4dae1471d033be80859cb329 | 3,625,208 |
import random
def lucky_enough(luck=0):
"""
Check if you lucky enough.
:param luck: should be an int between 0-100
:return: Bool
"""
return random.randint(0, 99) < luck | 158179ab5da330561f6d3b7be06697b0b319b1db | 3,625,209 |
def relu(attrs, inputs, proto_obj):
"""Computes rectified linear function."""
return 'relu', attrs, inputs | d45c7f517c2cef57206db56b1ed7402127e72a01 | 3,625,210 |
import importlib
import argparse
def application_type(value):
"""
Return aiohttp application defined in the value.
"""
try:
module_name, app_name = value.split(":")
except ValueError:
module_name, app_name = value, "app"
module = importlib.import_module(module_name)
try:
... | 0de6fb898edc48d319415fb48c9d2f51e210d1db | 3,625,211 |
def remote_empty(draw: st.DataObject) -> TemporaryDirectory:
"""Create an empty git remote repository."""
root = TemporaryDirectory()
_run_helper(args=["init", "--bare"], cwd=root.name)
return root | d12acc0b31b0697df53515e1142e39ed61558f60 | 3,625,212 |
import re
def _reformat_stack(stack):
"""Post processes the stack trace through _relative_path()."""
out = stack.splitlines(True)
def replace(l):
m = re.match(RE_STACK_TRACE_FILE, l, re.DOTALL)
if m:
groups = list(m.groups())
groups[1] = _relative_path(groups[1])
return ''.join(groups)... | f3ee98bd9896fc26cdb74bd3c68c0a668af567bb | 3,625,213 |
def adaboost_predict ( trees, alphas, X ):
"""
Predict labels for test data using a fitted AdaBoost
ensemble of decision trees.
# Arguments
trees: a list of decision tree dicts
alphas: a vector of weights for the trees
X: an array of sample data, where rows are samples
... | 3b0729b3fc05cc131ebc15f49dde1c5635cdf907 | 3,625,214 |
import logging
def check_multiple_insert_param(columns_to_insert, insert_values_dict_lst):
"""
Checks if the pararmeter passed are of correct order.
:param columns_to_insert:
:param insert_values_dict_lst:
:return:
"""
column_len = len(columns_to_insert)
for row in insert_values_dict_l... | ffb5a4eb595b84a439f3a910d81d699289c1d69a | 3,625,215 |
def KK_RC4(w, Rs, R_values, t_values):
"""
Kramers-Kronig Function: -RC-
Kristian B. Knudsen (kknu@berkeley.edu / kristianbknudsen@gmail.com)
"""
return (
Rs
+ (R_values[0] / (1 + w * 1j * t_values[0]))
+ (R_values[1] / (1 + w * 1j * t_values[1]))
+ (R_values[2] / (1... | 28a968a4799741cd9cb03f51971fe50cf3d09ce0 | 3,625,216 |
def keep_active(useruid: str):
"""
試著保持著登入狀態
"""
# 取得使用者物件
user = User(useruid)
session = get_session(useruid)
# 確認登入狀態
if session.active:
return True
# 嘗試重新登入
try:
session.login(user.userid,
user.passwd,
session.cours... | 98399c5e63775265a3c0d67bcc7cf5e40ced06b6 | 3,625,217 |
import random
import string
def random_string(length=16):
"""Generate a random string of the given length."""
result = ""
while len(result) < length:
result += random.choice(string.ascii_letters + string.digits)
return result | 04bf92658ce8d9535aa91c751c5d9f1746827eaf | 3,625,218 |
def getIfacesInZone(zone_ifaces):
"""
Parse given interfaces for a zone for associating a zone with an interface
and set any properties listed to defined values upon fan control starting
on the zone.
"""
ifaces = []
for i in zone_ifaces:
iface = {}
# Interface name not neede... | 040236570a17ea7faf3dd4d839082bfc47ff7337 | 3,625,219 |
def calculate_confusion(config, predicted_indices, y_indices):
"""Helper method that calculates confusion matrix."""
confusion = np.zeros((config.label_size, config.label_size), dtype=np.int32)
for i in xrange(len(y_indices)):
correct_label = y_indices[i]
guessed_label = predicted_indices[i]... | 4316587fe9ccc0636878f639a273c2056d19162a | 3,625,220 |
from pathlib import Path
def make_surrogates(data, parcellation, scale, spatnull):
"""
Generates surrogates for `data` using `spatnull` method
Parameters
----------
data : (N,) pd.DataFrame
parcellation : {'atl-cammoun2012', 'atl-schaefer2018'}
scale : str
spatnull : {'burt2018', 'bur... | 4dbfa59e06e0ff1ec0090f336147b34bde02be01 | 3,625,221 |
import os
def basename(filename):
"""
Return basename of given filename.
Parameters
----------
filename : :class:`str`
Name of the file (may contain absolute path and extension) the
basename should be returned for.
Returns
-------
basename : :class:`str`
Basen... | d10f50c4f0264e6b1e8ce3bc82fea97230708a3b | 3,625,222 |
def add_birth_rate_functions(_tb_model, _input_database, _country_iso3):
"""
Add crude birth rate function to existing epidemiological model
:param _tb_model: EpiModel or StratifiedModel class
SUMMER model object to be assigned bcg vaccination coverage functions
:param _input_database: sql data... | ea9c13d60c8eb3eeba937598f503fbf15b08db85 | 3,625,223 |
def generate_kml_end_str():
""" Generates the footer for a KML file
"""
kml_str = '</Document>'
kml_str += '</kml>'
return kml_str | b67ed779e29f0c358a7e76c7662c36a714e50649 | 3,625,224 |
import getpass
def _GetUserTypeAndPassword(username, password=None, is_admin=False):
"""Returns the user-type and password for a user.
Args:
username: Username for the user.
password: Password for the user. If None, or not provided, we will prompt
for one via the terminal.
is_admin: Indicates w... | 75327a94894329e7b0d7fcf3e83bdc24b733720d | 3,625,225 |
def top_ions(df1, df2):
""" function to compute the top species, top filename and top species/plant part for each ion
Args:
df1 = reduced_df, table of with index on sp/part column and features only.
df2 = quantitative.csv file, output from MZmine
Returns:
None
"""
#compu... | d85146cce080be70519ff67851aff8111d6deb11 | 3,625,226 |
from pathlib import Path
def get_genome_group(src_loc: Path, config: Config) -> GenomeGroup:
"""Get the ``GenomeGroup`` based on ``src_loc`` and ``config``.
``Config`` is used to set global filter codes and exclude files on group creation.
Args:
src_loc: Path, can be directory or file
co... | a2060257576d51ee55d22c8739b610bc16fbb64f | 3,625,227 |
def rtl_dashboard(request):
"""RTL Dashboard page.
"""
return render(request, "django_sb_admin/sb_admin_rtl_dashboard.html",
{"nav_active":"rtl_dashboard"}) | 1b821aa71d0b0f0839fe4febf06d0e18788650f3 | 3,625,228 |
def relationship(flights, planes):
"""
Here we are having two columns common between flights and planes tables, which are
tailnum and year.
from above two common fields we consider tailnum column as keys in both the table.
In
"""
print(planes.shape) # (3322, 9)
print(planes.tailnum.nuni... | da1f31a4afa1720caeb01fc4bbec445999da4f56 | 3,625,229 |
def numpy_unpad(x, pad_width):
"""Unpad an array.
Args:
x (numpy.ndarray): array to unpad
pad_width (tuple): padding
Returns:
numpy.ndarray
"""
slices = []
for c in pad_width:
e = None if c[1] == 0 else -c[1]
slices.append(slice(c[0], e))
return x[tu... | 31f41a7a741d7efa870670c95a8acf8be365975a | 3,625,230 |
def linear(a, b, c):
"""exec a * b + c"""
print('exec linear')
ret = a * b + c
print('linear: %s * %s + %s = %s' % (a, b, c, ret))
return ret | fc5c1c99bd03f61e5f8fd87d4d1863002469c57d | 3,625,231 |
import json
def start():
"""start goal"""
print("/start <- ")
print(request.get_json())
goal_id = request.get_json()['goal_id']
resDB = db.start(goal_id)
jsonResult = {
"result" : resDB
}
resJson = json.dumps(jsonResult)
print("/start -> ")
print(resJson)
return r... | a917baf7c352540d87e17d01421e50249d8e33e5 | 3,625,232 |
import warnings
def get_eer_values(fmr, fnmr):
"""Returns the value of the Equal Error Rate
Equal Error Rate (EER): is the point where FNMR(t) = FMR(t).
In practice the score distribution are not continuous so and interval
is returned instead. The EER value will be set as the midpoint of
this int... | b6242b38a2031c655f17c46e38b0bfd2b0ff897f | 3,625,233 |
def validate_spec(index, spec):
""" Validate the value for a parameter specialization.
This validator ensures that the value is hashable and not None.
Parameters
----------
index : int
The integer index of the parameter being specialized.
spec : object
The parameter specializa... | 3612d927ef7e61613e0991ffc04ea76555d1b115 | 3,625,234 |
import ctypes
def ENgetflowunits():
"""Retrieves a code number indicating the units used to express all flow rates."""
j= ctypes.c_int()
ierr= _lib.ENgetflowunits(ctypes.byref(j))
if ierr!=0: raise ENtoolkitError(ierr)
return j.value | 41bdaa84d2e14a3ba63b9d42e8b790be196d5499 | 3,625,235 |
import os
import yaml
import logging
def read_config(config_path, defaults):
"""Read config file from given location, and parse properties"""
if not os.path.isdir(config_path):
raise ValueError("{0} is not a directory".format(config_path))
try:
return yaml_load(config_path, defaults)
... | c4e5ad25f802fd566ffa0ef029dbf15b3db53e5c | 3,625,236 |
def _get_file_names():
"""Returns the file names expected to exist in the input_dir."""
file_names = {}
file_names['train'] = ['data_batch_%d' % i for i in xrange(1, 5)]
file_names['validation'] = ['data_batch_5']
file_names['eval'] = ['test_batch']
return file_names | c2fb7a28fb7e0a1da0ab914f008f580e0f4b17b0 | 3,625,237 |
def index_of_best(list):
"""
low distance is better
:param list:
:return:
"""
a_list, error_count, error = remove_errors(list)
return list.index(min(a_list)) | 03c484e0579cb78054ce9177cfe52520f692247a | 3,625,238 |
def mold(
content: VyList,
shape: VyList,
) -> VyList:
"""Mold one list to the shape of the other. Uses the mold function
that Jelly uses."""
# https://github.com/DennisMitchell/jellylanguage/blob/70c9fd93ab009c05dc396f8cc091f72b212fb188/jelly/interpreter.py#L578
if isinstance(content, str):
... | d28ccab5c3e3338b0e55dc1ff2be327721856919 | 3,625,239 |
import json
import torch
import copy
import pickle
def goal_optimization(model_exp_key, opt_exp_key=None, write_results=True):
"""
Optimize random goal states using a model-based estimator.
Note: tailored to HalfCheetah-v2 environment currently.
Args:
model_exp_key (str): model-based experime... | fbe668784003dbce61bfbd499dc80cb26fed3457 | 3,625,240 |
import gzip
import struct
from functools import reduce
import operator
def _read_datafile(path, expected_dims):
"""Utility function for reading mnist data files."""
base_magic_num = 2048
with gzip.GzipFile(path) as f:
magic_num = struct.unpack('>I', f.read(4))[0]
expected_magic_num = base_... | 12b0940e369769b8948867f30e7b0ee436723609 | 3,625,241 |
def _vsos(da, pos, method_sos="median"):
"""
vSOS = Value at the start of season
Params
-----
da : xarray.DataArray
method_sos : str,
If 'first' then vSOS is estimated
as the first positive slope on the
greening side of the curve. If 'median',
then vSOS is estima... | 6b4bf26d6c0d3b7d6fecfbed07dabf3ec202ae41 | 3,625,242 |
def parse_coordSys(config, coordSys=batoid.CoordSys()):
"""
@param config configuration dictionary
@param coordSys sys to which transformations in config are added
"""
shift = [0.0, 0.0, 0.0]
if any(x in config for x in ['x', 'y', 'z']):
if 'shift' in config:
raise ValueErr... | 461ca4fe295ffa5bb47dd40d2af00f4034c5222c | 3,625,243 |
import hashlib
def password_hasher(password):
"""
Just hashes the password
:param password:
:return: 32 byte hash
:rtype: bytes
"""
return hashlib.pbkdf2_hmac('sha256', password.encode('utf-8'), b'salt', 100000) | 44e921903c63f1703bbc79869f1a63a25bfe5916 | 3,625,244 |
def index_alpha_beta(i, ij, ik, points):
"""
Finds for each input point the index of it's bounding triangle
and the alpha and beta value for that point in the triangle. Note
this means that the following statements will always be true:
alpha + beta <= 1
alpha >= 0
beta >= 0
f... | 4799890b1e292bce19628779294e068f73744e76 | 3,625,245 |
import array
def flac_read_file_f32(filename: str) -> DecodedSoundFile:
"""Reads and decodes the whole flac audio file. Resulting sample format is 32 bits float."""
filenamebytes = _get_filename_bytes(filename)
with ffi.new("unsigned int *") as channels, \
ffi.new("unsigned int *") as sample_rate,... | d455a941ef27cdc7b696fae648556c31b3664135 | 3,625,246 |
import ctypes
def version() -> str:
"""
Version library
:return: version
"""
pfun = _lib.zmVersionLib
pfun.restype = None
pfun.argtypes = (ctypes.c_char_p,)
ver = ctypes.create_string_buffer(32)
pfun(ver)
return ver.value.decode("utf-8") | d91f04d7c614d11803df4d6d5b6f3b96c6d60202 | 3,625,247 |
def get_all_books(request):
"""
This view is to return all the books
"""
books = Book.objects.all()
context = {
'books': books
}
return render(request, 'books/books.html', context=context) | 059b9db54fdb52b1918de4e5c32f48f6400acf4e | 3,625,248 |
def _GetSchemaPath(release_track, for_help=False):
"""Returns the resource schema path."""
return export_util.GetSchemaPath(
'compute',
_GetApiVersion(release_track),
'TargetHttpsProxy',
for_help=for_help) | 02ef6e67daf4337859716cbc71edf41bb14cfaa5 | 3,625,249 |
def login():
"""Login a user"""
if not request.is_json:
return jsonify(error="Missing JSON in request"), 400
username = request.json.get("username", None)
password = request.json.get("password", None)
remember = request.json.get("remember", False)
if not username:
return jsonify(... | 5e0af9233b15ac81918dbbd0459fa192905d52f7 | 3,625,250 |
import json
def _load_state(path):
"""Load a GUI state from a JSON file."""
try:
logger.debug("Load %s for GUIState.", path)
data = load_json(str(path))
except json.decoder.JSONDecodeError as e: # pragma: no cover
logger.warning("Error decoding JSON: %s", e)
data = {}
... | b29fdb9f2c3b3bdf162bf5fdfb4ed7d7e0b04422 | 3,625,251 |
def client_host(server_host):
"""Return the host on which a client can connect to the given listener."""
if server_host == '0.0.0.0':
# 0.0.0.0 is INADDR_ANY, which should answer on localhost.
return '127.0.0.1'
if server_host in ('::', '::0', '::0.0.0.0'):
# :: is IN6ADDR_ANY, which should answer on localhost... | 93d1b23c7714e5252efc866daa10dd5f7f53e0e7 | 3,625,252 |
def get_context(bot, update, session, user):
"""Create a context object for callback queries."""
context = CallbackContext(session, bot, update.callback_query, user)
add_breadcrumb(
crumb={
"query": update.callback_query,
"data": update.callback_query.data,
"user... | 4cb0259e8dd1ddcde8e4142c92da5ba5b2514d33 | 3,625,253 |
def customer_all_detail(request, pk):
"""客户详情(不能更改信息)"""
customer = get_object_or_404(Customer, pk=pk, is_valid=True)
form = CustomerForm(instance=customer)
# 添加上地址信息
# 下面这里引入异常处理,如果数据库里没有该字段,那么表单渲染为空
try:
customer_shop = CustomerShop.objects.get(customer=pk)
shopform = CustomerS... | a239f01a73a519880c6372bacd79370e07268841 | 3,625,254 |
import logging
def logmethod(func):
""" Decorator to add logging information around calls for use with . """
def _wrapper(self, *args, **kwds):
logging.info("Start::%s.%s:%s",
func.__module__,
self.__class__.__name__,
func.__name__)
... | 7f8223ab99d6f9101088bff050f79fd0669231d4 | 3,625,255 |
import os
def robots():
""" "Just in case?" """
return send_from_directory(os.path.join(app.root_path, 'static'),
'robots.txt',
mimetype='text/plain') | 8bb714eac890515d5188c3e50e49272f2de01b3f | 3,625,256 |
def to_isbn(ean):
"""Convert EAN to ISBN"""
clean = clean_isbn(ean)
isbn = clean[3:-1]
isbn.append(isbn_check_digit(isbn))
return ''.join(str(d) for d in isbn) | 3537e28de6c296bb07d791fb7b7a87eec6539057 | 3,625,257 |
def markdown_cell(content):
"""
Create a markdown cell with a given content.
"""
return nbformat.notebooknode.NotebookNode({"cell_type": "markdown", "source": content, "metadata": {}}) | fadb7ad9d2e3a1df3393aab5cef7f012612a99b0 | 3,625,258 |
def _replace_suffix(string, old, new):
"""Returns a string with an old suffix replaced by a new suffix."""
return string.endswith(old) and string[:-len(old)] + new or string | 4e487f62126b130d973f249cd34abc5a75df3eaa | 3,625,259 |
def compute_fig(grid, col_x, col_y, col_z, value_coupe, n_points, xlim, ylim):
"""uses user input parameters to compute the values to plot
Parameters
----------
grid : pandas.DataFrame
full data grid
col_x : string
horizontal column in final plot
col_y : string
vertical ... | 0e8614cbf625560bce8ac533184c36d7b464e72e | 3,625,260 |
def is_empty_json_response_from_s3(context):
"""Check if the JSON response from S3 is empty (but not None)."""
return context.s3_data == {} | 6ec3a41646de74d82f3786e772228da55d91b63a | 3,625,261 |
def vault_value(key, default=None):
"""
Returns the secret referenced by the key supplied.
If the vault has not been initialized, returns the provided default instead
:param key:
:param default:
:return:
"""
if not vault_ready():
return default
try:
return _get_from_... | e7c055a4e1e8f6a1b7c8fb9fe1f2d219a84fb5e6 | 3,625,262 |
def show_expression_of_KO_genes(
sample_meta_file: str,
normalized_matrix: str,
ko_list: list,
ko_dict: dict = "",
percentile: bool = False,
heat: bool = False,
):
"""
Show expression of the genes that were actually knocked out.
Parameters
----------
sample_meta_file
... | d647b2c54dd4049176667122196fcc8bd595549a | 3,625,263 |
from datetime import datetime
def preprocessEventData(eventData):
"""
Ensures that the event data dictionary is consistent before it reaches the template or event logic.
- dates should exist and be date objects if there is a value
- checkbaxes should be True or False
- if term is ... | ceea909651a706e2aef532855788205d9b962f8c | 3,625,264 |
def get_data(self):
"""Generate the PWM matrix
Parameters
----------
self : ImportGenPWM
An ImportGenPWM object
Returns
-------
matrix: ndarray
The generated PWM matrix
"""
# Tpwmu=np.arange(fs*duration)/fs,
Tpwmu = np.linspace(0, self.duration, self.fs * self.... | e2aea3c7acfdda09601a5e1d92192390b1276310 | 3,625,265 |
def set_code_by_activity_hash(db, overwrite=False):
"""Use ``activity_hash`` to set dataset code.
By default, won't overwrite existing codes, but will if ``overwrite`` is ``True``."""
for ds in db:
if 'code' not in ds or overwrite:
ds['code'] = activity_hash(ds)
return db | 539c4b0618ff9112136a4e697dce34efabf0bee6 | 3,625,266 |
def ca_time_sync(h_session, ultime):
"""
:param int h_session: Session handle
:param ultime:
"""
ret = CA_TimeSync(h_session, CK_ULONG(ultime))
return ret | c80a5a328826d63f661bf0a20156ddf6147a2a19 | 3,625,267 |
def add_subparser(parser):
"""Add the subparser that needs to be used for this command"""
plot_parser = parser.add_parser("plot", help=DESCRIPTION, description=DESCRIPTION)
cli.get_basic_args_group(plot_parser)
plot_parser.add_argument(
"kind",
type=str,
choices=SINGLE_EXPERIME... | 35f460076138655f7bc2db871bb1919fe29dfdaf | 3,625,268 |
def Potential_bruteforce_parallel(x,m,softening,G=1.):
"""Returns the exact mutually-interacting gravitational potential for a set of particles with positions x and masses m, evaluated by brute force.
Arguments:
x -- shape (N,3) array of particle positions
m -- shape (N,) array of particle masses
s... | 034f526d2597f9c418430ff26aeae2ee9adcf867 | 3,625,269 |
from typing import Mapping
from typing import Any
from typing import List
import collections
def _validate_plurals(mapping: Mapping[str, Any],
ref: str) -> List[SchemaError]:
"""
Check that no graph field conflicts with a instance registry field.
The instance registry field is iden... | b57096d223400385c2d1671e91359e6b52907a6a | 3,625,270 |
def mock_validator_execute_validator(*args, **kwargs):
"""
Mock method to just return the builded command line without
executing it.
"""
cls = args[0]
command = args[1]
return command | d03cc70f1f0a5bd59e7a116e3774b99aa8db5a03 | 3,625,271 |
def load_seq(seq_path):
"""Load HPatches sequences."""
seq = cv2.imread(seq_path, 0)
n_patch = seq.shape[0] / 65
seq = np.reshape(seq, (n_patch, 65, 65, 1)).astype(np.float32)
resized_seq = np.zeros((n_patch, 32, 32), np.float32)
for i in range(n_patch):
tmp_patch = cv2.resize(seq[i], (... | 2f605ab5fcdc6c336613d8397e87721ba762ecf1 | 3,625,272 |
def mode_check_decorator(func):
"""Decorate load()/save() CookieJar methods."""
def wrapper(cls, **kwargs):
try:
filename = kwargs['filename']
except KeyError:
filename = cls.filename
res = func(cls, **kwargs)
file_mode_checker(filename, mode=0o600)
... | 3c36b920b84dc14bd23bd189c15b7b5247705c61 | 3,625,273 |
def has_gap(k1, k2, min_gap=0.002):
"""判断 k1, k2 之间是否有缺口"""
assert k2['dt'] > k1['dt']
if k1['high'] < k2['low'] * (1-min_gap) \
or k2['high'] < k1['low'] * (1-min_gap):
return True
else:
return False | 642d9793dcc6f85d3bf21e1abf6f481292c053f1 | 3,625,274 |
def get_pronoun_lemmas(conll_document):
"""
Returns the list of lemmatized pronouns found in the given contents of a CONLL document (list of triples).
:param conll_document: the contents of a CONLL file, as a list of triples
:return:
"""
pronouns = []
for (form, lemma, pos) in conll_document... | 17507968c67e145c754da940743cea554102f7f4 | 3,625,275 |
def isdisjoint(pth1, pth2):
""" returns 0 if disjoint
"""
edge1 = list(pairwise(pth1))
edge2 = list(pairwise(pth2))
for edge in edge1:
if edge in edge2:
return 1
return 0 | 2632d3c336871ecfb0cb3693db2f86d8ae527792 | 3,625,276 |
def delete_post(post_id):
"""function for deleting a business by id"""
business = Business.query.get_or_404(post_id)
if business.business != current_user:
abort(403)
db.session.delete(business)
db.session.commit()
flash('Your post has been deleted!', 'success')
return redirect(url_fo... | af445a24c71b57eb26b5cc2603ff6cc246f8859d | 3,625,277 |
def retract(request):
"""retracts a cash invitations"""
params = request.get_params(schemas.RetractSchema())
device = get_device(request)
customer = device.customer
access_token = get_wc_token(request, customer)
postParams = {
'reason': 'other'
}
response = wc_contact(
re... | 7d93210b985e36300adfe3e20006a5bec5918b8e | 3,625,278 |
def generate_fileattr_metadata(local_path, metadata):
# type: (blobxfer.models.upload.LocalPath, dict) -> dict
"""Generate file attribute metadata dict
:param blobxfer.models.upload.LocalPath local_path: local path
:param dict metadata: existing metadata dict
:rtype: dict
:return: merged metadat... | 4231af249ccc9f57f413ca02735ae57c3a91d8bc | 3,625,279 |
def build_estimator(model_dir):
"""Build an estimator."""
m = tf.estimator.LinearClassifier(
model_dir=model_dir, feature_columns=base_columns,
optimizer=tf.train.FtrlOptimizer(
learning_rate=0.1,
l1_regularization_strength=1.0,
l2_regularization_strength=1.0)
)
return m | 6ec9ad927d86aafc4bf8b20771ff8092ab652a50 | 3,625,280 |
import logging
def _set_logger(
logger_file_path: str,
logger_name: str = "default_logger",
write_to_console: bool = True,
) -> logging.Logger:
"""Set logger to log to the given path.
Modified from https://docs.python.org/3/howto/logging-cookbook.html
Args:
logger_file_path (str): Fi... | 338999fbcd34367f1dc4140143688965663bf486 | 3,625,281 |
def sort_and_print(body, num):
"""
Sorts the values of dictionaries and prints respective
top sentences
:param body: list of dictionaries of 'sentence': score
:param num: no of sentences to be printed
:return: prints
"""
result = []
rank = []
for sentdict in body:
for sen... | 400b11f84d0e68fb393c261736856257b4681c52 | 3,625,282 |
def get_trans_func(name):
"""
Retrieves the transformation module by name.
"""
trans_funcs = {
"bottleneck_transform": BottleneckTransform,
"basic_transform": BasicTransform,
}
assert (
name in trans_funcs.keys()
), "Transformation function '{}' not supported".format(... | 2fbad8e9034734bedccf6a21842c389b63b26336 | 3,625,283 |
import torch
def get_box_pair_info(box1, box2):
"""
input:
box1 [batch_size, (x1,y1,x2,y2,cx,cy,w,h)]
box2 [batch_size, (x1,y1,x2,y2,cx,cy,w,h)]
output:
32-digits: [box1, box2, unionbox, intersectionbox]
"""
# union box
unionbox = box1[:,:4].clone()
unionbox[:, 0]... | 6461d64ae2d5ef0338cb69dda40fad65882a8803 | 3,625,284 |
def bintogrid(
x,
y,
unc=None,
newx=None,
dx=None,
weighting="inversevariance",
drop_nans=True,
):
"""
x = the independent variable (wavelength)
y = the measurement (transit depth)
unc = the uncertainty on the measurement (sigmas on the transit depths)
newx = a (linearly)... | e392dadfda3eec08e32f2d74f1ac5729f00176c4 | 3,625,285 |
def parse_date(date_str: str) -> date:
"""Just a wrapper to avoid having to declare dateutil as a dependency in other projects."""
return dateutil_parser(date_str).date() | 8fdf6ae162f46547f488a4ccd1b7fe82a60ac731 | 3,625,286 |
import torch
def dagger(x: torch.Tensor) -> torch.Tensor:
"""Conjugate transpose of a batch of matrices. Matrix dimensions are
assumed to be the final two, with all preceding dimensions batched over."""
return x.conj().transpose(-2, -1) | 672d26333182803b18f3d1d10e49ef393e216f5f | 3,625,287 |
def node_factory(edge_model, children_null=True, base_model=models.Model):
"""
Dag Node factory
"""
class Node(base_model, NodeBase):
class Meta:
abstract = True
children = models.ManyToManyField(
"self",
blank=children_null,
symmetrical=... | 9b739490baab70a5b24a90b611e2db6e1a3664fa | 3,625,288 |
def geometry_mask(
geometries,
out_shape,
transform,
all_touched=False,
invert=False):
"""Create a mask from shapes.
By default, mask is intended for use as a
numpy mask, where pixels that overlap shapes are False.
Parameters
----------
geometries : iter... | 726865aff256bdb73c3215f57dd2c7bfa0a58dd6 | 3,625,289 |
def detection_area(self):
"""
Checks the area to have obstacles
:return: float
"""
image = ImageGrab.grab(self.area)
gray_img = ImageOps.grayscale(image)
arr = np.array(gray_img.getcolors())
# print(arr.mean())
return arr.mean() | 4893e33696a3e11db290dae28a8f346c21c02a51 | 3,625,290 |
from pathlib import Path
import requests
def _get_data_by_filename(fname: str) -> Path:
"""
Download file or used cached version.
Args:
fname (str): name of file to download
Returns:
Path: path at which file lives
"""
full_fname = DATA_PATH.joinpath(fname)
# check if fil... | 11b908b801db2c4002a837c78a3266608cbe3056 | 3,625,291 |
def build_input(data_path, batch_size, size, mode):
"""Build image and targets.
Args:
data_path: Filename for data.
batch_size: Input batch size.
mode: Either 'train' or 'eval'.
Returns:
volumes: Batches of volumes. [batch_size, volume_size, volume_size, volume_size]
targets: Batches of targe... | 20bce2efcbb7a4f1998b754daf1577af1c885507 | 3,625,292 |
def _get_publication(paper_entry: dict) -> Publication:
"""
Using a paper entry provided, this method builds a publication instance
Parameters
----------
paper_entry : dict
A paper entry retrieved from arXiv API
Returns
-------
Publication, or None
A publication instanc... | bb530e8e4d6fbb5dad7438e18a1a63dc028b44b8 | 3,625,293 |
def get_table_13():
"""表 13 玄関ポーチに設置された照明設備の人感センサーによる補正係数
Args:
Returns:
list: 表 13 玄関ポーチに設置された照明設備の人感センサーによる補正係数
"""
table_13 = (0.9, 1.0)
return table_13 | 91a89343800ad5e3c587371c91e7d256d9ed85a1 | 3,625,294 |
def Parse(text: str) -> ParsedUniversalDependencies:
"""Parses the provided text."""
doc = nlp(text)
return __parse_tokens(doc) | 9878eb1cfd82d2590663635ba659f997c5619f23 | 3,625,295 |
def Log_GetTimestamp(*args):
"""Log_GetTimestamp() -> wxChar"""
return _misc_.Log_GetTimestamp(*args) | ec3574361a50cf12c8fd21bd9b51885905e61477 | 3,625,296 |
def get_seismic1d_eign_matrix(mu, density):#TODO!!
""" Retrun matrix of eigenvectors"""
c_p = np.sqrt(mu/density)
return np.array([[1/c_p, 1/c_p], [1, 1]]) | eb8758c903442c7b690bad04fb0a4282ac66979e | 3,625,297 |
def computer_move(state) -> bool:
"""
Method to decide which movements
"""
sorted_movements = sorted(explore_leaves(state), key=lambda x: x[0], reverse=state.board.turn)
if len(sorted_movements) == 0:
logger.debug('No moves to make: GAME OVER?')
return True
_log_moves(sorted_mov... | 15aec435af156ff6c04ac87b96babc6739359168 | 3,625,298 |
def find_left_anchor_index(fragment_info, fragments):
"""
Description:
Use the fragment information to find which fragment is the left anchor
:param fragment_info: [list[dict]] the list of fragment information
:param fragments: [list] the list of fragments being searched
:return: left_anchor_ind... | 502473f7fee00a5ccd1ed3d6cf5c938e8c4d2041 | 3,625,299 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.