content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
import struct
def collect_js(
deps,
closure_library_base = None,
has_direct_srcs = False,
no_closure_library = False,
css = None):
"""Aggregates transitive JavaScript source files from unfurled deps."""
srcs = []
direct_srcs = []
ijs_files = []
infos = []
... | 7a243401280646103522ed339ff20c35f05e031d | 3,646,400 |
import termios
import struct
import fcntl
def send_control(uuid, type, data):
"""
Sends control data to the terminal, as for example resize events
"""
sp = sessions[uuid]
if type == 'resize':
winsize = struct.pack("HHHH", data['rows'], data['cols'], 0, 0)
fcntl.ioctl(sp['ptymaster... | 262ef0ccffac80c0293d1446eb0e38e50b2ce687 | 3,646,401 |
import os
def get_absolute_path(path):
"""
Returns absolute path.
"""
if path.startswith("/"):
return path
else:
return os.path.join(HOME_DIR, path) | 6754a947cd1081a760cc529fbb94270a7f867e68 | 3,646,402 |
import os
def get_prefix_by_xml_filename(xml_filename):
"""
Obtém o prefixo associado a um arquivo xml
Parameters
----------
xml_filename : str
Nome de arquivo xml
Returns
-------
str
Prefixo associado ao arquivo xml
"""
file, ext = os.path.splitext(xml_filena... | 169b5571ae0bfca2a923c4030325002503790f6e | 3,646,403 |
def dgausscdf(x):
"""
Derivative of the cumulative distribution function for the normal distribution.
"""
return gausspdf(x) | e968f20ca28555eb50d5766440c5f3f47522c1ff | 3,646,404 |
import os
import sys
def LStatFile(path):
"""
LStat the file. Do not follow the symlink.
"""
d = None
error = None
try:
d=os.lstat(path)
except OSError as error:
print("Exception lstating file " + path + " Error Code: " + str(error.errno) + " Error: " +error.strerror, fi... | 54ea199de8eef527743a882940140aad7e44add4 | 3,646,405 |
import tqdm
def model_datasets_to_rch(gwf, model_ds, print_input=False):
"""convert the recharge data in the model dataset to a recharge package
with time series.
Parameters
----------
gwf : flopy.mf6.modflow.mfgwf.ModflowGwf
groundwater flow model.
model_ds : xr.DataSet
datas... | b32442c508e17205737ddb8168fe323b57cfbb2f | 3,646,406 |
from typing import List
from datetime import datetime
def create_events_to_group(
search_query: str,
valid_events: bool,
group: Group,
amount: int = 1,
venue: bool = False,
) -> List[Event]:
"""
Create random test events and save them to a group
Arguments:
search_query {str} -... | 31045c8f9311d677d766d87ed9fc1d6848cc210d | 3,646,407 |
def alt_stubbed_receiver() -> PublicKey:
"""Arbitrary known public key to be used as reciever."""
return PublicKey("J3dxNj7nDRRqRRXuEMynDG57DkZK4jYRuv3Garmb1i98") | c07461fc060f9dc637e93cadd32604aae892f924 | 3,646,408 |
import base64
def create_api_headers(token):
"""
Create the API header.
This is going to be sent along with the request for verification.
"""
auth_type = 'Basic ' + base64.b64encode(bytes(token + ":")).decode('ascii')
return {
'Authorization': auth_type,
'Accept': 'applicatio... | 41ba1e22898dab2d42dde52e4458abc40640e957 | 3,646,409 |
def _combine(bundle, transaction_managed=False, rollback=False,
use_reversion=True):
"""
Returns one sreg and DHCP output for that SREG.
If rollback is True the sreg will be created and then rolleback, but before
the rollback all its HWAdapters will be polled for their DHCP output.
"""... | 0171e804e4f10167d85e92608a09bca55308edfa | 3,646,410 |
def get_node_session(*args, **kwargs):
"""Creates a NodeSession instance using the provided connection data.
Args:
*args: Variable length argument list with the connection data used
to connect to the database. It can be a dictionary or a
connection string.
**kwargs... | bb992b7e49a698dfb7b54b1492616913a6b5df27 | 3,646,411 |
import os
def load_aaz_command_table(loader, aaz_pkg_name, args):
""" This function is used in AzCommandsLoader.load_command_table.
It will load commands in module's aaz package.
"""
profile_pkg = _get_profile_pkg(aaz_pkg_name, loader.cli_ctx.cloud)
command_table = {}
command_group_table = {}... | 6c75fd9f3e13e8397cf7064fbcf22385c63f2a29 | 3,646,412 |
def edit_role(payload, search_term):
"""Find and edit the role."""
role = Role.query.get(search_term)
# if edit request == stored value
if not role:
return response_builder(dict(status="fail",
message="Role does not exist."), 404)
try:
if payload... | 8690c8fc1c1aea5245d9cef540c355a2903a8484 | 3,646,413 |
def use_redis_cache(key, ttl_sec, work_func):
"""Attemps to return value by key, otherwise caches and returns `work_func`"""
redis = redis_connection.get_redis()
cached_value = get_pickled_key(redis, key)
if cached_value:
return cached_value
to_cache = work_func()
pickle_and_set(redis, k... | a2c631466aef18c7bb640b17e57421e257ad7314 | 3,646,414 |
def counting_sort(array, low, high):
"""Razeni pocitanim (CountingSort). Seradte zadane pole 'array'
pricemz o poli vite, ze se v nem nachazeji pouze hodnoty v intervalu
od 'low' po 'high' (vcetne okraju intervalu). Vratte serazene pole.
"""
counts = [0 for i in range(high - low + 1)]
for elem i... | bd4ccccdb24786ec3f3d867afe1adf340c9e53b5 | 3,646,415 |
import re
def normalize_archives_url(url):
"""
Normalize url.
will try to infer, find or guess the most useful archives URL, given a URL.
Return normalized URL, or the original URL if no improvement is found.
"""
# change new IETF mailarchive URLs to older, still available text .mail archive... | e8a5351af28338c77c3e94fdf2b81e22c7a6edfd | 3,646,416 |
import os
def logs():
"""
:return: The absolute path to the directory that contains Benchmark's log file.
"""
return os.path.join(benchmark_confdir(), "logs") | a94f2435b705a23b19c5c9da57e0bff0448a9f4b | 3,646,417 |
def getIsolatesFromIndices(indices):
"""
Extracts the isolates from the indices of a df_X.
:param pandas.index indices:
cn.KEY_ISOLATE_DVH, cn.KEY_ISOLATE_MMP
:return dict: keyed by cn.KEY_ISOLATE_DVH, cn.KEY_ISOLATE_MMP
values correspond to rows element in the index
"""
keys = [n for n in indice... | 4e9200c722ce0c478d13eddcc799f4a8f7cab6db | 3,646,418 |
def save_group_geo_org(user_id, group_id, area_id, org_unit_id):
"""Method for attaching org units and sub-counties."""
try:
if org_unit_id:
geo_org_perm, ctd = CPOVCUserRoleGeoOrg.objects.update_or_create(
user_id=user_id, group_id=group_id, org_unit_id=org_unit_id,
... | ed7750760405e12f790454e247e54917184e7044 | 3,646,419 |
def tf_efficientnet_lite0(pretrained=False, **kwargs):
""" EfficientNet-Lite0 """
# NOTE for train, drop_rate should be 0.2, drop_path_rate should be 0.2
kwargs['bn_eps'] = BN_EPS_TF_DEFAULT
kwargs['pad_type'] = 'same'
model = _gen_efficientnet_lite(
'tf_efficientnet_lite0', channel_multipli... | 49ea1c68f168ad613222808e2fbb1ead52190243 | 3,646,420 |
import os
def ensuredir(dirpath):
"""
ensure @dirpath exists and return it again
raises OSError on other error than EEXIST
"""
try:
os.makedirs(dirpath, 0o700)
except FileExistsError:
pass
return dirpath | 447f4542faa00e8928e30f0a9793436b8377964a | 3,646,421 |
import ast
from typing import Optional
def get_qualname(node: ast.AST) -> Optional[str]:
"""
If node represents a chain of attribute accesses, return is qualified name.
"""
parts = []
while True:
if isinstance(node, ast.Name):
parts.append(node.id)
break
eli... | 0d08b25a50b7d159f5df3b0b17282725eb748f38 | 3,646,422 |
def traceUsage(addr, register, steps):
"""
Given a start address, a register which holds a value and the number of steps,
this function disassembles forward #steps instructions and traces the value of <register>
until it is used in a call instruction. It then returns the offset added to <register> and the addre... | 78c805af660b5e98348de1bd1ae4b7ce9a57238b | 3,646,423 |
import os
def index_folder(folder, images=[]):
"""
simple multi threaded recusive function to map folder
Args:
@param folder: folder str path to folder
@param images: images list containing absolute paths of directory images
Returns:
List with image paths
"""
print(f'En... | ef6fb4a1fc9fa9d16756ff3a0c0855fde7d66bc1 | 3,646,424 |
def array3d (surface):
"""pygame.surfarray.array3d (Surface): return array
Copy pixels into a 3d array.
Copy the pixels from a Surface into a 3D array. The bit depth of the
surface will control the size of the integer values, and will work
for any type of pixel format.
This function will temp... | a2079a540453d5ba69f5b10e292341ef6fcfb972 | 3,646,425 |
import torch
def masked_kl_div(input, target, mask):
"""Evaluate masked KL divergence between input activations and target distribution.
Parameters:
input (tensor) - NxD batch of D-dimensional activations (un-normalized log distribution).
target (tensor) - NxD normalized target distribution.
... | afdd704bac7caabd7d0cbbd2599af6c1a440ae1c | 3,646,426 |
import os
import random
def create_sample_data(input_seqs, sample_size):
"""
Takes a sample of size 'sample_size' from an input file
containing sequences and their associated expression levels,
and writes them to a separate file. The format of the first
2 lines of the resulting output file will be... | e7490ec512472536c5c12c4d229b836220249417 | 3,646,427 |
def find_peaks(ts, mindist=100):
"""
Find peaks in time series
:param ts:
:return:
"""
extreme_value = -np.inf
extreme_idx = 0
peakvalues = []
peaktimes = []
find_peak = True
idx = 0
for r in ts.iteritems():
# print(r)
if find_peak:
# look fo... | 5f4dbf0b6c9e4e8961c14b1ba255ebcdf210c50b | 3,646,428 |
import os
import datasets
def load_dataset(name, root, sample="default", **kwargs):
"""
Default dataset wrapper
:param name (string): Name of the dataset (Out of cifar10/100, imagenet, tinyimagenet, CUB200, STANFORD120, MIT67).
:param root (string): Path to download the dataset.
:param sample (st... | b59b427b032c7360d68a3f79d358c6ae938de7bd | 3,646,429 |
def get_flanking_seq(genome, scaffold, start, end, flanking_length):
"""
Get flanking based on Blast hit
"""
for rec in SeqIO.parse(genome, "fasta"):
if rec.id == scaffold:
return str(
rec.seq[int(start) - int(flanking_length) : int(end) + int(flanking_length)]
... | 509002a7099ad62b0449e1c5de9a1a7dd875bc0c | 3,646,430 |
import re
def d(vars):
"""List of variables starting with string "df" in reverse order. Usage: d(dir())
@vars list of variables output by dir() command
"""
list_of_dfs = [item for item in vars if (item.find('df') == 0 and item.find('_') == -1 and item != 'dfs')]
list_of_dfs.sort(key=lambda x:int(... | 4961ae70a61e45b81e06e55ee9553ff61fd45d18 | 3,646,431 |
import inspect
def get_class_namespaces(cls: type) -> tuple[Namespace, Namespace]:
"""
Return the module a class is defined in and its internal dictionary
Returns:
globals, locals
"""
return inspect.getmodule(cls).__dict__, cls.__dict__ | {cls.__name__: cls} | 46f275bcc328d9ca87ffdebf616d42096705d3fb | 3,646,432 |
from .io import select_driver
def write_stream(path, sync=True, *args, **kwargs):
"""Creates a writer object (context manager) to write multiple dataframes into one file. Must be used as context manager.
Parameters
----------
path : str, filename or path to database table
sync : bool, default True
Set to `Fal... | 8e2274e102b60b139b6e40f425682d06268e10a5 | 3,646,433 |
from typing import Dict
def diff(
df: DataFrame,
columns: Dict[str, str],
periods: int = 1,
axis: PandasAxis = PandasAxis.ROW,
) -> DataFrame:
"""
Calculate row-by-row or column-by-column difference for select columns.
:param df: DataFrame on which the diff will be based.
:param colum... | 38ed83fc7e1847a2c9e31abb217990becc1bc04f | 3,646,434 |
import base64
def decodeTx(data: bytes) -> Transaction:
"""Function to convert base64 encoded data into a transaction object
Args:
data (bytes): the data to convert
Returns a transaction object
"""
data = base64.b64decode(data)
if data[:1] != tx_flag:
return None
... | da52e9dcb641d2986fa47d15f9da8d1edea28659 | 3,646,435 |
def create_package_from_datastep(table):
"""Create an importable model package from a score code table.
Parameters
----------
table : swat.CASTable
The CAS table containing the score code.
Returns
-------
BytesIO
A byte stream representing a ZIP archive which can be importe... | 0874f1a755ed73af09091a7c0f1b3fb3e5e861e4 | 3,646,436 |
def _test_diff(diff: list[float]) -> tuple[float, float, float]:
"""Последовательный тест на медианную разницу с учетом множественного тестирования.
Тестирование одностороннее, поэтому p-value нужно умножить на 2, но проводится 2 раза.
"""
_, upper = seq.median_conf_bound(diff, config.P_VALUE / populat... | 024d0eaba612361e4fef39839bfd31474d5be5a6 | 3,646,437 |
def get_repo_of_app_or_library(app_or_library_name):
""" This function takes an app or library name and will return the corresponding repo
for that app or library"""
specs = get_specs()
repo_name = specs.get_app_or_lib(app_or_library_name)['repo']
if not repo_name:
return None
return Rep... | 72c0349354fdc11da3ff16f2dfa3126eb02fa381 | 3,646,438 |
from datetime import datetime
def get_index_price_change_by_ticker(fromdate: str, todate: str, market: str="KOSPI") -> DataFrame:
"""입력된 기간동안의 전체 지수 등락률
Args:
fromdate (str ): 조회 시작 일자 (YYMMDD)
todate (str ): 조회 종료 일자 (YYMMDD)
market (str, optional): 조회 시장 (KOSPI... | 6d65ffeaccd1e5fe307e1e5387e413db3c2eb5fe | 3,646,439 |
def axpy(alpha, x, y, stream=None):
"""y <- alpha*x + y """
global _blas
if not isinstance(alpha, Number): raise ValueError('alpha is not a numeric type')
validate_argument_dtype(x, 'x')
validate_argument_dtype(y, 'y')
if not _blas: _blas = Blas()
_blas.stream = stream
dtype = promote(... | 10b8c46b1fc160d637241750c408957b8f184ee9 | 3,646,440 |
def _unenroll_get_hook(app_context):
"""Add field to unenroll form offering data removal, if policy supports."""
removal_policy = _get_removal_policy(app_context)
return removal_policy.add_unenroll_additional_fields(app_context) | 6c8e6a06d45fecfa8828ce8a24ca9e1e910b1e9c | 3,646,441 |
from typing import Union
def query_fetch_bom_df(search_key: str, size: int) -> Union[pd.DataFrame, None]:
"""Fetch and return bom dataframe of the article
Runs recursive query on database to fetch the bom.
"""
# Recursive query
raw_query = f"""WITH cte AS (
SELECT *
FROM [{DB_NAM... | 753f0378590df1c2b3e50f7bad8d2b15490ae488 | 3,646,442 |
def zscore(collection, iteratee=None):
"""Calculate the standard score assuming normal distribution. If iteratee
is passed, each element of `collection` is passed through a iteratee before
the standard score is computed.
Args:
collection (list|dict): Collection to process.
iteratee (mix... | a813295f6cce309b936b94a9d70f082f435a4b89 | 3,646,443 |
from typing import Tuple
def AND(
*logicals: Tuple[func_xltypes.XlExpr]
) -> func_xltypes.XlBoolean:
"""Determine if all conditions in a test are TRUE
https://support.office.com/en-us/article/
and-function-5f19b2e8-e1df-4408-897a-ce285a19e9d9
"""
if not logicals:
raise xlerror... | ebdc5c4f2c3cab31a78507923eded284eb679fd4 | 3,646,444 |
def check_mask(mask):
"""Check if mask is valid by its area"""
area_ratio = np.sum(mask) / float(mask.shape[0] * mask.shape[1])
return (area_ratio > MASK_THRES_MIN) and (area_ratio < MASK_THRES_MAX) | a82f415d95ea07571da2aabeeddc6837b0a80f8d | 3,646,445 |
def supported_estimators():
"""Return a `dict` of supported estimators."""
allowed = {
'LogisticRegression': LogisticRegression,
'RandomForestClassifier': RandomForestClassifier,
'DecisionTreeClassifier': DecisionTreeClassifier,
'KNeighborsClassifier': KNeighborsClassifier,
... | 1bb76e81252c3b959a376f23f2462d4faef234a9 | 3,646,446 |
from hiicart.gateway.base import GatewayError
from hiicart.gateway.amazon.gateway import AmazonGateway
from hiicart.gateway.google.gateway import GoogleGateway
from hiicart.gateway.paypal.gateway import PaypalGateway
from hiicart.gateway.paypal2.gateway import Paypal2Gateway
from hiicart.gateway.paypal_adaptive.gateway... | c60e3e88cf6bb919208821d8ee214368d39dc7f6 | 3,646,447 |
import sqlite3
def execute_query(db, query):
"""get data from database
"""
result = []
with closing(sqlite3.connect(db)) as conn:
conn.row_factory = sqlite3.Row
cur = conn.cursor()
for row in cur.execute(query):
result.append({name: row[name] for name in row.keys()}... | 75476c8a9f14751eb46fc2891ba5e7bddecd3c0e | 3,646,448 |
from zipimport import zipimporter
import os
def module_list(path):
"""
Return the list containing the names of the modules available in
the given folder.
:param path: folder path
:type path: str
:returns: modules
:rtype: list
"""
if os.path.isdir(path):
folder_list = os.l... | ef0b80a91a350d3909e580dd8a592e09bfaa38ad | 3,646,449 |
def to_mgb_supported_dtype(dtype_):
"""get the dtype supported by megbrain nearest to given dtype"""
if (
dtype.is_lowbit(dtype_)
or dtype.is_quantize(dtype_)
or dtype.is_bfloat16(dtype_)
):
return dtype_
return _detail._to_mgb_supported_dtype(dtype_) | 864b5bb7099771705ad478e5e89db8f3035f1c4f | 3,646,450 |
def get_reset_state_name(t_fsm):
"""
Returns the name of the reset state.
If an .r keyword is specified, that is the name of the reset state.
If the .r keyword is not present, the first state defined
in the transition table is the reset state.
:param t_fsm: blifparser.BlifParser().blif.fsm ob... | c65ea80f94f91b31a179faebc60a97f7260675c4 | 3,646,451 |
def gridmake(*arrays):
"""
Expands one or more vectors (or matrices) into a matrix where rows span the
cartesian product of combinations of the input arrays. Each column of the
input arrays will correspond to one column of the output matrix.
Parameters
----------
*arrays : tuple/list of np.... | 56c5375024170fbd599500c0603e0e3dcc7f53d4 | 3,646,452 |
import logging
import math
def pagerotate(document: vp.Document, clockwise: bool):
"""Rotate the page by 90 degrees.
This command rotates the page by 90 degrees counter-clockwise. If the `--clockwise` option
is passed, it rotates the page clockwise instead.
Note: if the page size is not defined, an ... | 37f0a9e726f490c357afb48ace49484cfcae84ce | 3,646,453 |
import argparse
from typing import Tuple
import atexit
import json
def create_new_deployment(runner: Runner,
args: argparse.Namespace) -> Tuple[str, str]:
"""Create a new Deployment, return its name and Kubernetes label."""
run_id = str(uuid4())
def remove_existing_deployment():... | 2cf76661fb4ab89ec94efb8648d917abedf70f48 | 3,646,454 |
from .org import org_organisation_logo
from re import A
def inv_send_rheader(r):
""" Resource Header for Send """
if r.representation == "html" and r.name == "send":
record = r.record
if record:
db = current.db
s3db = current.s3db
T = current.T
... | 5fddfaeede501531674557a0ecf8e4fb43989bdf | 3,646,455 |
import torch
def gauss_reparametrize(mu, logvar, n_sample=1):
"""Gaussian reparametrization"""
std = logvar.mul(0.5).exp_()
size = std.size()
eps = Variable(std.data.new(size[0], n_sample, size[1]).normal_())
z = eps.mul(std[:, None, :]).add_(mu[:, None, :])
z = torch.clamp(z, -4., 4.)
ret... | 5c4fa87c5287aae3727608a003c3c91c2ba5c1a9 | 3,646,456 |
import os
import sys
import unicodedata
def run_setup_py(cmd, pypath=None, path=None,
data_stream=0, env=None):
"""
Execution command for tests, separate from those used by the
code directly to prevent accidental behavior issues
"""
if env is None:
env = dict()
for... | 12fca9f58444f9b1e3ba3c890e8956c9bbed60cc | 3,646,457 |
def forward_pass(img, session, images_placeholder, phase_train_placeholder, embeddings, image_size):
"""Feeds an image to the FaceNet model and returns a 128-dimension embedding for facial recognition.
Args:
img: image file (numpy array).
session: The active Tensorflow session.
images_pl... | 846c05a167e116ca4efbe3888486a3ee740d33ef | 3,646,458 |
import urllib
def check_url(url):
"""Returns True if the url returns a response code between 200-300,
otherwise return False.
"""
try:
req = urllib.request.Request(url, headers=headers)
response = urllib.request.urlopen(req)
return response.code in range(200, 209)
except... | 79f20eeb14724b728f020ff4c680e49f6a1a2473 | 3,646,459 |
def build_permutation_importance(
data,
data_labels,
feature_names,
model,
metrics,
repeats=100,
random_seed=42
):
"""Calculates permutation feature importance."""
pi_results = {}
for metric in metrics:
pi = sklearn.inspection.permutation_i... | 3b0b87ddf53446156b20189dad7c3d0b3ae2a1c2 | 3,646,460 |
def _load_parent(collection, meta):
"""Determine the parent document for the document that is to be
ingested."""
parent = ensure_dict(meta.get("parent"))
parent_id = meta.get("parent_id", parent.get("id"))
if parent_id is None:
return
parent = Document.by_id(parent_id, collection=collect... | 2f53440fa9610f9e8ca494ec8ec27bf9d6a09273 | 3,646,461 |
import requests
def get_latest_sensor_reading(sensor_serial, metric):
"""
Get latest sensor reading from MT sensor
metrics: 'temperature', 'humidity', 'water_detection' or 'door'
"""
headers = {
"Content-Type": "application/json",
"Accept": "application/json",
"X-Cisco-Mera... | 88de9d770f3be91700e3c86ff6460e2fdaa35d01 | 3,646,462 |
def border_msg(msg: str):
"""
This function creates boarders in the top and bottom of text
"""
row = len(msg)
h = ''.join(['+'] + ['-' * row] + ['+'])
return h + "\n" + msg + "\n" + h | cdd9d17ba76014f4c80b9c429aebbc4ca6f959c3 | 3,646,463 |
def create_app(config_name='development'):
"""Returns flask app based on the configuration"""
flask_app = Flask(__name__)
flask_app.config.from_object(app_config[config_name])
flask_app.config['JSON_SORT_KEYS'] = False
flask_app.url_map.strict_slashes = False
flask_app.register_error_handler(400... | 783edefb40c2f3cc0aefa0788b0c1c04d581aa39 | 3,646,464 |
def auto_merge_paths(data, auto_merge_distance, auto_close_paths=True):
"""
This function connects all paths in the given dataset, for which the start or endpoints are closer than
auto_merge_distance.
:param data: Should be a list or tuple containing paths, attributes, svg_attributes.
:param auto_m... | 34ec7d0b853a70159ebef6244236475375a3ca9d | 3,646,465 |
def is_authorized(secure: AccessRestriction):
"""Returns authorization status based on the given access restriction.
:param secure: access restriction
:type secure: AccessRestriction
:return: authorization status (``True`` or ``False``)
"""
if secure == AccessRestriction.ALL:
return Tru... | e070ae5521db1079426b80b6ff8a3fc5c9a9ba09 | 3,646,466 |
def create_link_forum(**attrs):
"""Save a new link forum."""
link = build_link_forum(**attrs)
link.save()
return link | e94e1001e42f46cd1c1803fbff35d0eded89858e | 3,646,467 |
from datetime import datetime
def open_report():
"""Probe Services: Open report
---
parameters:
- in: body
name: open report data
required: true
schema:
type: object
properties:
data_format_version:
type: string
format... | c5e824157ed382267236a5de98f0199b2b5ff23d | 3,646,468 |
def prepare_scan():
"""
Returns a lexical scanner for HTSQL grammar.
"""
# Start a new grammar.
grammar = LexicalGrammar()
# Regular context.
query = grammar.add_rule('query')
# Whitespace characters and comments (discarded).
query.add_token(r'''
SPACE: [\s]+ | [#] [^\0\r... | ffc30354378a03f95be988b7ee62b01708795f41 | 3,646,469 |
def get_test_server(ctxt, **kw):
"""Return a Server object with appropriate attributes.
NOTE: The object leaves the attributes marked as changed, such
that a create() could be used to commit it to the DB.
"""
kw['object_type'] = 'server'
get_db_server_checked = check_keyword_arguments(
... | 03d754223274282b15aeb9b5cf636f6acd90024c | 3,646,470 |
def keras_model(optimizer="Adamax", activation="softplus", units=32):
"""Function to create model, required for KerasClassifier"""
model = Sequential()
model.add(Dense(units, activation="relu", input_dim=2500))
model.add(Dense(2, activation=activation))
model.compile(loss="categorical_crossentropy",... | ccd1cc5652a207e3c4c2bc170d43fe22b4375c0b | 3,646,471 |
def start_end_key(custom_cmp):
"""
Compare models with start and end dates.
"""
class K(object):
"""
Define comparison operators.
http://code.activestate.com/recipes/576653-convert-a-cmp-function-to-a-key-function/
"""
def __init__(self, obj, *args):
s... | b1d7b48cc3e9926b6138850ad3b8307adbb4f2f3 | 3,646,472 |
def get_previous_release_date():
""" Fetch the previous release date (i.e. the release date of the current live database) """
releases = Release.objects.all().order_by('-date')
return str(releases[1].date) | 764d90daaf5c60460f22e56063a40c261cb6b45e | 3,646,473 |
def readLensModeParameters(calibfiledir, lensmode='WideAngleMode'):
"""
Retrieve the calibrated lens correction parameters
"""
# For wide angle mode
if lensmode == 'WideAngleMode':
LensModeDefaults, LensParamLines = [], []
with open(calibfiledir, 'r') as fc:
# Read the... | 51245aa19f32ebb31df5748e0b40022ccae01e24 | 3,646,474 |
def scale(boxlist, y_scale, x_scale, scope=None):
"""scale box coordinates in x and y dimensions.
Args:
boxlist: BoxList holding N boxes
y_scale: (float) scalar tensor
x_scale: (float) scalar tensor
scope: name scope.
Returns:
boxlist: BoxList holding N boxes
"""
with... | adffbdce632470852e0499bb93915f93a7695d5a | 3,646,475 |
import requests
def fetch(uri: str, method: str = 'get', token: str = None):
""":rtype: (str|None, int)"""
uri = 'https://api.github.com/{0}'.format(uri)
auth = app.config['GITHUB_AUTH']
headers = {'Accept': 'application/vnd.github.mercy-preview+json'}
json = None
if token:
headers['A... | 14cde2808108173e6ab86f3eafb4c8e35daf4b40 | 3,646,476 |
from typing import OrderedDict
from typing import Mapping
from typing import Sequence
from typing import Container
from typing import Iterable
from typing import Sized
def nested_tuple(container):
"""Recursively transform a container structure to a nested tuple.
The function understands container types inher... | 60dac69865d753b14558d7156e40703e26fb57a1 | 3,646,477 |
from typing import OrderedDict
def _validate_args(func, args, kwargs):
"""Validate customer function args and convert them to kwargs."""
# Positional arguments validate
all_parameters = [param for _, param in signature(func).parameters.items()]
# Implicit parameter are *args and **kwargs
if any(pa... | 51d357d032dc0b26aeb32d1850b1a630bafab508 | 3,646,478 |
def _qual_arg(user_value,
python_arg_name,
gblock_arg_name,
allowable):
"""
Construct and sanity check a qualitative argument to
send to gblocks.
user_value: value to try to send to gblocks
python_arg_name: name of python argument (for error string)
gbl... | 7bf6717ee3dbeb533902773c86316d2bbdcd59a9 | 3,646,479 |
def is_valid_ip(ip_addr):
"""
:param ip_addr:
:return:
"""
octet_ip = ip_addr.split(".")
int_octet_ip = [int(i) for i in octet_ip]
if (len(int_octet_ip) == 4) and \
(0 <= int_octet_ip[0] <= 255) and \
(0 <= int_octet_ip[1] <= 255) and \
(0 <= int_octet_ip... | 7d776107f54e3c27a2a918570cbb267b0e9f419e | 3,646,480 |
def make_replay_buffer(env: gym.Env, size: int) -> ReplayBuffer:
"""Make a replay buffer.
If not ShinEnv:
Returns a ReplayBuffer with ("rew", "done", "obs", "act", "log_prob", "timeout").
If ShinEnv:
Returns a ReplayBuffer with ("rew", "done", "obs", "act", "log_prob", "timeout", "state").
... | 27f7c0bae37fc1963f4f7c72b42e8da424ab313e | 3,646,481 |
from typing import Callable
import decimal
def scale_places(places: int) -> Callable[[decimal.Decimal], decimal.Decimal]:
"""
Returns a function that shifts the decimal point of decimal values to the
right by ``places`` places.
"""
if not isinstance(places, int):
raise ValueError(
... | aaf2d9eb14d7a1b28d169d971011b456e2164000 | 3,646,482 |
def create_model(params : model_params):
"""
Create ReasoNet model
Args:
params (class:`model_params`): The parameters used to create the model
"""
logger.log("Create model: dropout_rate: {0}, init:{1}, embedding_init: {2}".format(params.dropout_rate, params.init, params.embedding_init))
# Query and Doc... | b175adef530dbbbdb132fed0a6653945ec02fef9 | 3,646,483 |
def _process_voucher_data_for_order(cart):
"""Fetch, process and return voucher/discount data from cart."""
vouchers = Voucher.objects.active(date=date.today()).select_for_update()
voucher = get_voucher_for_cart(cart, vouchers)
if cart.voucher_code and not voucher:
msg = pgettext(
'... | d89816fc24192d7d2d4ce7d8edaf11ae94e3f171 | 3,646,484 |
def transform_batch(images,
max_rot_deg,
max_shear_deg,
max_zoom_diff_pct,
max_shift_pct,
experimental_tpu_efficiency=True):
"""Transform a batch of square images with the same randomized affine
transformation.
"""... | 5486b1e9bbaf162e7a188c25517b0c164c8da317 | 3,646,485 |
def prep_seven_zip_path(path, talkative=False):
"""
Print p7zip path on POSIX, or notify if not there.
:param path: Path to use.
:type path: str
:param talkative: Whether to output to screen. False by default.
:type talkative: bool
"""
if path is None:
talkaprint("NO 7ZIP\nPLEA... | c9d4cc77111c8fc9768c713556fb16e5b8f69ec2 | 3,646,486 |
from typing import Dict
async def root() -> Dict[str, str]:
"""
Endpoint for basic connectivity test.
"""
logger.debug('root requested')
return {'message': 'OK'} | 97721416c745d460cd60cea486fa5367ff52cffa | 3,646,487 |
def overlapping_community(G, community):
"""Return True if community partitions G into overlapping sets.
"""
community_size = sum(len(c) for c in community)
# community size must be larger to be overlapping
if not len(G) < community_size:
return False
# check that the set of nodes in the... | da9e3465c6351df0efd19863e579c49bbc6b9d67 | 3,646,488 |
import json
def validate_credential(zone, credential):
"""
Token is already calculated
"""
source = DataSource(DataSource.TYPE_DATABASE, CONNECTION_FILE_PATH)
canAccess = source.get_or_create_client_access_rights(credential, zone)
if canAccess:
return json.dumps({'success':True}), 200, {'ContentType':'appli... | 083ecc977b53e6f5c5df64b0ed52ad9ebeeee821 | 3,646,489 |
def gm(data,g1=0.0,g2=0.0,g3=0.0,inv=False):
"""
Lorentz-to-Gauss Apodization
Functional form:
gm(x_i) = exp(e - g*g)
Where: e = pi*i*g1
g = 0.6*pi*g2*(g3*(size-1)-i)
Parameters:
* data Array of spectral data.
* g1 Inverse exponential width.
* g2 ... | 7c6aec6d9a21f9c5b2800aa742e5aaa3ead1ac63 | 3,646,490 |
import torch
def exp_t(u, t):
"""Compute exp_t for `u`."""
if t == 1.0:
return torch.exp(u)
else:
return torch.relu(1.0 + (1.0 - t) * u) ** (1.0 / (1.0 - t)) | 8b1a8773b8a5159d9332332d6f77d65cacc68d7c | 3,646,491 |
def decode_json_dict(data):
# type: (Dict) -> Dict
"""Converts str to python 2 unicodes in JSON data."""
return _strify(data) | d2512ea50bf5cfca059ca706adc403bea5af1753 | 3,646,492 |
from typing import Any
def linear_search(lst: list, x: Any) -> int:
"""Return the index of the first element of `lst` equal to `x`, or -1 if no
elements of `lst` are equal to `x`.
Design idea: Scan the list from start to finish.
Complexity: O(n) time, O(1) space.
For an improvement on linear se... | 47e73d53ff68954aadc6d0e9e293643717a807d8 | 3,646,493 |
def get_color_cmap(name, n_colors=6):
"""
Return discrete colors from a matplotlib palette.
:param name: Name of the palette. This should be a named matplotlib colormap.
:type: str
:param n_colors: Number of discrete colors in the palette.
:type: int
:return: List-like object of colors as h... | 90550127196bb1841f48d37ed1f304462d165037 | 3,646,494 |
def logkde2entropy(vects, logkde):
"""
computes the entropy of the kde
incorporates vects so that kde is properly normalized (transforms into a truly discrete distribution)
"""
vol = vects2vol(vects)
truth = logkde > -np.infty
return -vects2vol(vects)*np.sum(np.exp(logkde[truth])*logkde[trut... | 5ce96636607bc3b2160791cda28ef586cb0f29c2 | 3,646,495 |
from typing import Optional
from typing import Dict
import json
def get_deployment_json(
runner: Runner,
deployment_name: str,
context: str,
namespace: str,
deployment_type: str,
run_id: Optional[str] = None,
) -> Dict:
"""Get the decoded JSON for a deployment.
If this is a Deployment... | b9cb4cabea6a506cc33c18803bbe45699cf2b222 | 3,646,496 |
import ctypes
def is_admin() -> bool:
"""Check does the script has admin privileges."""
try:
return ctypes.windll.shell32.IsUserAnAdmin()
except AttributeError: # Windows only
return None | 000fdc8034bf026045af0a5264936c6847489063 | 3,646,497 |
import urllib
def get_firewall_status(gwMgmtIp, api_key):
"""
Reruns the status of the firewall. Calls the op command show chassis status
Requires an apikey and the IP address of the interface we send the api request
:param gwMgmtIp:
:param api_key:
:return:
"""
global gcontext... | 16d06a5659e98b3d420ab90b21d720367ecde97a | 3,646,498 |
import logging
def create_logger(name, logfile, level):
"""
Sets up file logger.
:param name: Logger name
:param logfile: Location of log file
:param level: logging level
:return: Initiated logger
"""
logger = logging.getLogger(name)
handler = logging.FileHandler(logfile)
forma... | 83a0614053c558682588c47e641eceee368f88e0 | 3,646,499 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.