content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def check_table_exist(conn):
"""Check if a table exists.
We do not use IF EXISTS in creating the table so as to we will not create
hyper table twice when the table already exists.
Args:
conn (psycopg2.extensions.connection): The connection to PostgreSQL database.
Returns:
... | 47,100 |
def get_err_str(exception, message, trace=True):
"""Return an error string containing a message and exception details.
Args:
exception (obj): the exception object caught.
message (str): the base error message.
trace (bool): whether the traceback is included (default=True).
"""
... | 47,101 |
def epoch_data(data, window_length = 2,overlap=0.5):
"""
Separates the data into equal sized windows
Input:
- data: data to seperate into windows
- window_length: length of the window in seconds
- overlap: overlap, float in [0,1), in percentage overlap of win... | 47,102 |
def dailyUsagePer15minn(index_list, tank_data_list):
"""Process tank temperatures series to water usage series divided into 96 15 minutes intervals, where each
interval has value in liters equal to used normalized hot water(37deg of c).
:param index_list: list of indexes
:param tank_data_list: list of ... | 47,103 |
def is_valid(number):
"""Check if the number provided is a valid CAS RN."""
try:
return bool(validate(number))
except ValidationError:
return False | 47,104 |
def get_kernel(kernel_type, input_dim, on_gpu=True, **kwargs):
"""
Initializes one of the following gpytorch kernels: RBF, Matern
Args:
kernel_type (str):
Kernel type ('RBF', Matern52', 'Spectral)
input_dim (int):
Number of input dimensions
(translates in... | 47,105 |
def __ne__(self, other):
"""Returns true if both objects are not equal"""
return not self == other | 47,106 |
def down_sample(source, freq_vocab, replacement='', threshold=1e-3, min_freq=0, seed=None, name=None):
"""Randomly down-sample high frequency tokens in `source` with `replacement` value.
Args:
source: string `Tensor` or `RaggedTensor` or `SparseTensor` of any shape, items to be sampled.
freq_vo... | 47,107 |
def load_pickle(f):
"""使用pickle加载文件"""
version = platform.python_version_tuple() # 取python版本号
if version[0] == '2':
return pickle.load(f) # pickle.load, 反序列化为python的数据类型
elif version[0] == '3':
return pickle.load(f, encoding='latin1')
raise ValueError("invalid python version: {}".f... | 47,108 |
def main():
""" main entry point for module execution
"""
backup_spec = dict(filename=dict(), dir_path=dict(type="path"))
argument_spec = dict(
src=dict(type="path"),
lines=dict(aliases=["commands"], type="list"),
parents=dict(type="list"),
before=dict(type="list"),
... | 47,109 |
def extract_hashtags(text_list):
"""Return a summary dictionary about hashtags in :attr:`text_list`
Get a summary of the number of hashtags, their frequency, the top
ones, and more.
:param list text_list: A list of text strings.
:returns summary: A dictionary with various stats about hashtags
... | 47,110 |
async def test_authorization(host, device_token, user_token):
"""Makes sure that all authenticated APIs return errors when auth fails."""
bad_auth_headers = {"Authorization": f"Bearer {device_token}"}
calls = [
lambda session: api_new_device(session, host, "foobar", "foobar", "foobar"),
lambda session: api_new_... | 47,111 |
def skipif_32bit(param):
"""
Skip parameters in a parametrize on 32bit systems. Specifically used
here to skip leaf_size parameters related to GH 23440.
"""
marks = pytest.mark.skipif(
compat.is_platform_32bit(), reason="GH 23440: int type mismatch on 32bit"
)
return pytest.param(par... | 47,112 |
def main(dump, root, top_album, share_mapping, select_last):
"""
Convert bviewer albums to behappy.ini
Run query on bviewer db and export as csv (';' as delimiter)
SELECT
core_album.id,
core_album.parent_id,
core_album.title,
core_album.description,
... | 47,113 |
def check_int(data: Any) -> int:
"""Check if data is `int` and return it."""
if not isinstance(data, int):
raise TypeError(data)
return data | 47,114 |
def UpdateStatus(key_name, status):
"""Update the status/state of the specified bug.
Args:
key_name: Key name of the bug to update.
status: A string containing the new status of the bug.
Returns:
Bug object with the updated target_element information.
"""
bug = GetBugByKey(key_name)
bug.status... | 47,115 |
def onehot_encoding(categories, max_categories):
"""Given a list of integer categories (out of a set of max_categories)
return one-hot enocded values"""
out_array = np.zeros((len(categories), max_categories))
for key, val in enumerate(categories):
out_array[key, int(val)] = 1.0
return out_... | 47,116 |
def canny(gl_image, low_threshold=50, high_threshold=150):
"""Applies the Canny transform"""
return cv2.Canny(gl_image, low_threshold, high_threshold) | 47,117 |
def res_stage(block:nn.Module, ic:int, oc:int, num_layers:int, dflag:bool=True,
btype:str='basic', fdown:bool=False):
"""
Arguments
---------
block : nn.Module
the block type to be stacked one upon another
ic : int
# of input channels
oc : int
# of output channels
... | 47,118 |
def getFirstValid(opts, default):
"""Returns the first valid entry from `opts`, or `default` if none found.
Valid is defined as ``if o`` returns true."""
for o in opts:
if o: return o
return default | 47,119 |
def read_json(path: str) -> Dict[Any, Any]:
"""
Read a JSON file.
Args:
- path: The path of the JSON file.
Return:
- The data of the JSON file.
"""
_logger.debug(f"Reading JSON file: {path}")
with open(path, encoding="utf-8") as file:
data = json.load(file)
_l... | 47,120 |
def load_history(filename,
start_time=datetime(1, 1, 1),
end_time=datetime(1, 1, 1),
grid=None,
epoch=default_epoch, url=_url, load_data=False):
"""
Download soda data and save into local file
Parameters
----------
filename: string... | 47,121 |
def delete_volume() -> None:
"""Delete Volume"""
print("=============================================")
print()
show_svm()
print()
svm_name = input(
"Enter the SVM from which the Volumes need to be listed:-")
print()
show_volume(svm_name)
print()
volname = input("Enter t... | 47,122 |
def upload_thumb():
""" Used when another app has uploaded the main file to the cloud, and is
sending the thumb for local display.
"""
image = request.files["thumb_file"]
fname = request.form["filename"]
tpath = os.path.join(IMAGE_FOLDER, "thumbs", fname)
image.save(tpath)
return "OK" | 47,123 |
def grid_density_gaussian_filter(data, size, resolution=None, smoothing_window=None):
"""Smoothing grid values with a Gaussian filter.
:param [(float, float, float)] data: list of 3-dimensional grid coordinates
:param int size: grid size
:param int resolution: desired grid resolution
:param int smo... | 47,124 |
def channel_message_to_zerver_message(
realm_id: int,
users: List[ZerverFieldsT],
slack_user_id_to_zulip_user_id: SlackToZulipUserIDT,
slack_recipient_name_to_zulip_recipient_id: SlackToZulipRecipientT,
all_messages: List[ZerverFieldsT],
zerver_realmemoji: List[ZerverFieldsT],
subscriber_map... | 47,125 |
def custom_counters(state):
"""Collect cutom metric using benchmark.Counter."""
num_foo = 0.0
while state:
# Benchmark some code here
pass
# Collect some custom metric named foo
num_foo += 0.13
# Automatic Counter from numbers.
state.counters["foo"] = num_foo
# S... | 47,126 |
def print_train_time(start, end, device=None):
"""Prints difference between start and end time.
Args:
start (float): Start time of computation (preferred in timeit format).
end (float): End time of computation.
device ([type], optional): Device that compute is running on. Defaults to N... | 47,127 |
def filter_false_positive_matches(
matches,
trace=TRACE_REFINE or TRACE_FILTER_FALSE_POSITIVE,
reason=DiscardReason.FALSE_POSITIVE,
):
"""
Return a filtered list of kept LicenseMatch matches and a list of
discardable matches given a ``matches`` list of LicenseMatch by removing
matches to fal... | 47,128 |
def Moving_Average_ADX(data, period=14, smooth=14, limit=18):
"""
Moving Average ADX
ADX Smoothing Trend Color Change on Moving Average and ADX Cross. Use on Hourly Charts - Green UpTrend - Red DownTrend - Black Choppy No Trend
Source: https://www.tradingview.com/script/owwws7dM-Moving-Average-ADX/
... | 47,129 |
def test_always_defect():
"""Test the always defect strategy"""
strategy = prisonersdilemma.strategy.play_always_defect
assert not strategy([])
assert not strategy([(True, True)])
assert not strategy([(True, False)])
assert not strategy([(False, True)])
assert not strategy([(False, False)]) | 47,130 |
def delete_file(filepath: Path):
"""Delete a file. Do not follow symlinks.
If it is read-only, chmod it first to make sure we can delete it.
"""
try:
filepath.chmod(stat.S_IWRITE | stat.S_IREAD)
filepath.unlink()
except FileNotFoundError:
pass | 47,131 |
def insert_restaurant(restaurant):
"""
Method that allows to inser a Restaurant object to rest collection.
It also prints que inserted restaurant id
@param restaurant: Restaurant object to be inserted
@param nome:
"""
inserted_restaurant = rest.insert_one(restaurant)
print(inserted_rest... | 47,132 |
def test_populate_blueprint():
"""Confirm subset of collection."""
collection = collection_json()
test_collection = collection.copy()
for blueprint in blueprints:
test_collection = populate_blueprint(collection, blueprints, blueprint, routes)
assert collection.keys() <= test_collection.keys(... | 47,133 |
def forbid_end(interval, function):
""" Forbids an interval variable to end during specified regions.
In the declaration of an interval variable it is only possible to specify a range of possible end times.
This function allows the user to specify more precisely when the interval variable can end.
In p... | 47,134 |
def pack_dataset(hdfobject, key, value):
"""Packs a given key value pair into a dataset in the given hdfobject."""
isdt = None
if isinstance(value, datetime):
value = value.timestamp()
isdt = True
if hasattr(value, '__iter__'):
if all(isinstance(i, datetime) for i in value):
... | 47,135 |
def get_all_anime(total_pages: int) -> list:
"""
Get all the anime listed on all the pages of the website.
:param total_pages: Total number of pages of HorribleSubs.
:return: List containing the names of all the anime.
"""
titles = []
for page in range(1, total_pages + 1):
print(f"P... | 47,136 |
def network_generator(
rw: int,
cl: int,
b: float,
xi: float,
P: float,
mu: float,
bipartite: bool,
) -> ArrayLike:
"""
function to generate synthetic networks with nested, modular and in-block nested structures. Generates
networks with a fixed block size and increasing number of... | 47,137 |
def convert_rgb_to_hex(rgb: tuple([int, int, int])) -> str:
"""Take an RGB value and convert it to hex code.
Args:
rgb: a color represented as rgb values.
Returns:
Hex code of color or None if the RGB code is invalid.
"""
# Validate user Input is not negative or greater than 255
... | 47,138 |
def localVarName(value, position):
"""A name of a class."""
if not value[0].islower():
return Error('BadLocalVariableName', 'Local variable must start with a lower case letter', position, LINES)
return None | 47,139 |
def nodeAndOutputFromScenegraphLocationString(string, dag):
"""
Returns a tuple containing the node defined in a location string and its
corresponding Output.
"""
try:
outputNodeUUID = uuidFromScenegraphLocationString(string)
outputNode = dag.node(nUUID=outputNodeUUID)
outputNodeOutputName = string.split(":... | 47,140 |
def rivers_with_station(stations):
"""Returns the names of rivers on which a station is situated"""
return set(stations_by_river(stations).keys()) | 47,141 |
def check_string_is_nonempty(string, string_type='string'):
"""Ensures input is a string of non-zero length"""
if string is None or \
(not isinstance(string, str)) or \
len(string) < 1:
raise ValueError('name of the {} must not be empty!'
''.format(string_type))... | 47,142 |
def last_frame_with_txt(vid, txt, duration):
"""Take the last frame from vid, show it for duration with txt overlay."""
frame = list(vid.iter_frames())[-1]
clip = ImageClip(frame, duration=duration)
return CompositeVideoClip([
clip,
TextClip(txt, font=MOVIEPY_FONT, color='black', bg_colo... | 47,143 |
def load_dataset(dataset_size=100, dataset_start=0, shuffle=True, sentence_level=False, n_authors=15, k=5, features=u""):
"""
Load dataset
:return:
"""
# Load from directory
if sentence_level:
reutersc50_dataset = torchlanguage.datasets.ReutersC50SentenceDataset(
n_authors=n_... | 47,144 |
def df_as_table(dataframe, size='50'):
"""
:param dataframe: pandas dataframe to be displayed as a HTML table
:param size: string to set realtive table size in percent standard 50%
:return: string containing a html table
"""
shape = dataframe.shape
n_cols = shape[1]
n_rows = shape[0]
... | 47,145 |
def parsyfiles_global_config(multiple_errors_tb_limit: int = None, full_paths_in_logs: bool = None,
dict_to_object_subclass_limit: int = None):
"""
This is the method you should use to configure the parsyfiles library
:param multiple_errors_tb_limit: the traceback size (defaul... | 47,146 |
def ecdh(privkey, pubkey):
"""
Given a loaded private key and a loaded public key, perform an ECDH exchange
:param privkey:
:param pubkey:
:return:
"""
return ecdsa.ecdh(privkey, pubkey) | 47,147 |
def update_config_cli():
"""Get config from command line and write to a file"""
cfg = Config()
# FIXME: improve CLI experience
print('Note: Enter blank to keep the current value.')
for key in CFG_KEYS:
# Show (or hide) current value
if key in ENCRYPTED:
current = '*' if ... | 47,148 |
def gauge_to_base():
"""Move robot from the current tool position to base position.
Example::
# Move to base position
>>> gauge_to_base()
"""
session.getDevice('phis').speed = 2 * 50
session.getDevice('xt').speed = 2 * 40
dev_pos = [('robt', 13),
('zt', -400), ('r... | 47,149 |
def portfolio_margin_account(self, **kwargs):
"""Get Portfolio Margin Account Info (USER_DATA)
GET /sapi/v1/portfolio/account
https://binance-docs.github.io/apidocs/spot/en/#get-portfolio-margin-account-info-user_data
Keyword Args:
recvWindow (int, optional): The value cannot be greater than 60... | 47,150 |
def set_fan_mode(hass, fan_mode, entity_id=None):
"""Turn all or specified thermostat fan mode on."""
data = {
ATTR_FAN: fan_mode
}
if entity_id:
data[ATTR_ENTITY_ID] = entity_id
hass.services.call(DOMAIN, SERVICE_SET_FAN_MODE, data) | 47,151 |
def wcs_set_bladepowerlimit(device_id, powerlimit):
""" Set blade power limit
IMPORTANT! - Output formatted for compatibility with WcsCli
"""
try:
if device_id == 0:
mode = get_mode()
port_range = system_range(mode)
else:
port_range = (... | 47,152 |
def init_hyperparams(*, class_name: str, hyperparams, hyperparams_class) -> Any:
"""
Construct a hyperparams object from either a mapping or another hyperparams object.
"""
if isinstance(hyperparams_class, type) and is_dataclass(hyperparams_class):
if hyperparams is None:
return hype... | 47,153 |
def get_theta(k, lamada, sequence, alphabet):
"""Get the theta list which use frequency to replace physicochemical properties(the kernel of ZCPseKNC method."""
theta = []
L = len(sequence)
kmer = make_km_list(k, alphabet)
fre_list = [frequency_p(sequence, str(key))[0] for key in kmer]
fre_sum =... | 47,154 |
def add_pins(
component,
add_port_marker_function=add_pin_square,
port_type2layer=port_type2layer,
**kwargs,
):
""" add port markers:
Args:
component: to add ports
add_port_marker_function:
port_type2layer: dict mapping port types to marker layers for ports
Add devi... | 47,155 |
def _is_y(filename):
"""
Checks whether a file is a Nanometrics Y file or not.
:type filename: str
:param filename: Name of the Nanometrics Y file to be checked.
:rtype: bool
:return: ``True`` if a Nanometrics Y file.
.. rubric:: Example
>>> _is_y("/path/to/YAYT_BHZ_20021223.124800") ... | 47,156 |
def test_mutex_arguments(csv_path):
"""``replace`` and ``out_dir`` are mutually exclusive."""
with pytest.raises(ValueError):
fix_revolut.quote_numbers(csv_path, replace=True, out_dir=Path.cwd()) | 47,157 |
def remove_z_kpoints():
"""
Strips all linemode k-points from the KPOINTS file that include a
z-component, since these are not relevant for 2D materials and
slabs.
"""
kpoint_file = open('KPOINTS')
kpoint_lines = kpoint_file.readlines()
kpoint_file.close()
twod_kpoints = []
labe... | 47,158 |
def is_scheduler_filter_enabled(filter_name):
"""Check the list of enabled compute scheduler filters from config. """
filters = CONF.compute_feature_enabled.scheduler_available_filters
if len(filters) == 0:
return False
if 'all' in filters:
return True
if filter_name in filters:
... | 47,159 |
def juros_price(PV, PMT, n, PV0=0):
"""
Calcula taxa de juros de um parcelamento pela table price
Usado comummente em cŕedito concedido ao consumidor
:param PV: Valor a Vista / Valor Presente
:param PV0: Entrada
:param PMT: Valor da Parcela
:param n: Número de parcelas
:retur... | 47,160 |
def delexicalisation(out_src, out_trg, category, properties_objects):
"""
Perform delexicalisation.
:param out_src: source string
:param out_trg: target string
:param category: DBPedia category
:param properties_objects: dictionary mapping properties to objects
:return: delexicalised strings of the source and ta... | 47,161 |
def create_attention_mask_from_input_mask_v1(from_tensor, to_mask):
"""Create 3D attention mask from a 2D tensor mask.
Args:
from_tensor: 2D or 3D Tensor of shape [batch_size, from_seq_length, ...].
to_mask: int32 Tensor of shape [batch_size, to_seq_length].
Returns:
float Tensor o... | 47,162 |
def md5(filename):
"""Hash function for files to be uploaded to Fl33t"""
md5hash = hashlib.md5()
with open(filename, "rb") as filehandle:
for chunk in iter(lambda: filehandle.read(4096), b""):
md5hash.update(chunk)
return md5hash.hexdigest() | 47,163 |
def execute_scenario(scenario):
"""
Execute scenarios from the scenario pool to simulate abnormal token usage
:param scenario: A list containing a scenario
:return: none
"""
global attack_duration, protocol, host, port, payloads, user_agents, start_time, max_request_multiplier, min_request_multi... | 47,164 |
def pairwise(iterable: Iterable[Any]) -> Iterable[Tuple[Any, Any]]:
""" Divide the given iter into pairs and return as tuple pairs.
s -> (s0,s1), (s1,s2), (s2, s3), ...
"""
a, b = tee(iterable)
next(b, None)
return zip(a, b) | 47,165 |
def dustSurfaceDensitySingle(R, Rin, Sig0, p):
"""
Calculates the dust surface density (Sigma d) from single power law.
"""
return Sig0 * pow(R / Rin, -p) | 47,166 |
def ensure_no_empty_passwords(apps: StateApps, schema_editor: DatabaseSchemaEditor) -> None:
"""With CVE-2019-18933, it was possible for certain users created
using social login (e.g. Google/GitHub auth) to have the empty
string as their password in the Zulip database, rather than
Django's "unusable pas... | 47,167 |
def initialize(backends=("libcudnn.so", "cudnn64_65.dll")):
"""Loads shared library.
"""
cuffi.initialize()
global lib
if lib is not None:
return
with cuffi.lock:
_initialize(backends) | 47,168 |
def rightToPurchase(
symbol="", refid="", token="", version="", filter="", **timeseries_kwargs
):
"""Right to purchase up-to-date and detailed information on all new announcements, as well as 12+ years of historical records.
Updated at 5am, 10am, 8pm UTC daily
https://iexcloud.io/docs/api/#right-to-pu... | 47,169 |
def plot_gas_fraction(models, plot_output_path, plot_output_format=".png"):
"""
Plots the fraction of baryons that are in the cold gas reservoir as a function of
stellar mass for the specified models.
Parameters
----------
models : List of ``Model`` class instance
Models that will be p... | 47,170 |
def compute_edits(old, new):
"""Compute the in-place edits needed to convert from old to new
Returns a list ``[(index_1,change_1), (index_2,change_2)...]``
where ``index_i`` is an offset into old, and ``change_1`` is the
new bytes to replace.
For example, calling ``compute_edits("abcdef", "qbcdzw"... | 47,171 |
def gpx_to_lat_lon_list(filename):
"""
Summary: takes a .gpx file and turns the latitude and longitudes into a list of tuples
Returns: list of tuples (latitude, longitude).
"""
gpx_file = open(filename, "r")
gpx = gpxpy.parse(gpx_file)
latlonlist = []
if len(gpx.track... | 47,172 |
def pre_order(size):
"""List in pre order of integers ranging from 0 to size in a balanced
binary tree.
"""
interval_list = [None] * size
interval_list[0] = (0, size)
tail = 1
for head in range(size):
start, end = interval_list[head]
mid = (start + end) // 2
if mid ... | 47,173 |
def LockPrefix():
"""Returns the lock prefix as an operand set."""
return set([Operands(disasms=('lock',))]) | 47,174 |
def shimura_mass__maximal(self,):
"""
Use Shimura's exact mass formula to compute the mass of a maximal
quadratic lattice. This works for any totally real number field,
but has a small technical restriction when `n` is odd.
INPUT:
none
OUTPUT:
a rational number
EXAMPLE::... | 47,175 |
def distance(pt, pts):
"""Distances of one point `pt` to a set of points `pts`.
"""
return np.sqrt((pts[:,0] - pt[0])**2 + (pts[:,1] - pt[1])**2) | 47,176 |
def prepare_rw_output_stream(output):
"""
Prepare an output stream that supports both reading and writing.
Intended to be used for writing & updating signed files:
when producing a signature, we render the PDF to a byte buffer with
placeholder values for the signature data, or straight to the provid... | 47,177 |
def add_references(md, tmp_dir, args):
"""
Remember that this function is run for main, review, and editor.
"""
citations_to_do = tmp_dir / 'citations.json'
biblio = Path(args.library).with_suffix('.json')
_prepare_node_input(md, citations_to_do)
_check_citation_keys(citations_to_do, bibli... | 47,178 |
def get_args():
"""Get command-line arguments"""
parser = argparse.ArgumentParser(
description='Purpose: Create Workout Of (the) Day (WOD)',
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument('-f',
'--file',
help='CSV... | 47,179 |
def timestamp_now() -> Timestamp:
"""Returns a pandas timezone (UTC) aware Timestamp for the current time.
Returns:
pandas.Timestamp: Timestamp at current time
"""
from pandas import Timestamp
return timestamp_tzaware(Timestamp.now()) | 47,180 |
def patch_pypy():
"""
Monkey patch PyPy so SubDaap works.
"""
# Check if running under PyPY
try:
import __pypy__ # noqa
except ImportError:
return
# Patch for missing py3k acquire.
# See https://github.com/gevent/gevent/issues/248 for more information.
from gevent.... | 47,181 |
def readFlat4D(fn,interp=None):
"""
Load in data from 4D measurement of flat mirror.
Scale to microns, remove misalignments,
strip NaNs.
Distortion is bump positive looking at surface from 4D.
Imshow will present distortion in proper orientation as if
viewing the surface.
"""
#Get xp... | 47,182 |
def inner_product(D1, D2):
"""
Take the inner product of the frequency maps.
"""
result = 0.
for key in D1:
if key in D2:
result += D1[key] * D2[key]
return result | 47,183 |
def download_raw_from_s3(
file: str=None,
local_path: str=None,
) -> None:
"""Downloads the raw expression matrices from s3
:param file: _description_, defaults to None
:type file: str, optional
:param local_path: _description_, defaults to None
:type local_path: str, optional
"""
... | 47,184 |
def list_launch_daemons():
"""
Return an array of the files that are present in /Library/LaunchDaemons/
and /System/Library/LaunchDaemons/
"""
files = list_files_in_dir("/Library/LaunchDaemons/")
files += list_files_in_dir("/System/Library/LaunchDaemons/")
return files | 47,185 |
def decode(input, errors='strict'):
""" convert from wtf-8 encoded bytes to unicode text.
If this is a python narrow build this will actually
produce UTF-16 encoded unicode text (e.g. with surrogates).
"""
buf = []
try:
it = six.iterbytes(input)
c = None
while Tr... | 47,186 |
def us_varchar_encode(text):
"""
encode with utf-16-le
UShort *Varchar
:param str text:
:return:
"""
if not text:
return '\x00\x00'
length = len(text)
return struct.pack('<H', length) + text.encode('utf-16-le') | 47,187 |
def test_invalid_verbose(verbose: Any) -> None:
"""Test that invalid verboses raise errors."""
with pytest.raises(ValueError, match=r".*Invalid verbose argument.*"):
check_verbose(verbose) | 47,188 |
def print_debug(input_str, opt, functions=None):
"""
Simple debugging print statements that can be turned off or on with the debug variable.
inputs:
str, a string to output
functions, a list of string function names you want to debug (this program uses debug_functions to get these from cm... | 47,189 |
def graph_to_diagonal_h(n: int, nodes: List[int]) -> np.ndarray:
"""Construct diag(H)."""
h = [0.0] * 2**n
for node in nodes:
diag = tensor_diag(n, node[0], node[1], node[2])
for idx, val in enumerate(diag):
h[idx] += val
return h | 47,190 |
def write_to_hdf5(group, data, name):
"""Add data to HDF5 handler
"""
try:
group.create_dataset(name, data=data, compression="gzip")
except TypeError:
group.create_dataset(name, data=data)
except ValueError:
raise ValueError(f"Could not write {data}") | 47,191 |
def set_debug(ev):
"""Set Brython debug mode."""
if ev.target.checked:
__BRYTHON__.debug = 1
else:
__BRYTHON__.debug = 0 | 47,192 |
def condensational_heating(dQ2):
"""
Args:
dQ2: rate of change in moisture in kg/kg/s, negative corresponds
to condensation
Returns:
heating rate in degK/s
"""
return tf.math.scalar_mul(tf.constant(-LV / CPD, dtype=dQ2.dtype), dQ2) | 47,193 |
def collect_stats(cube, store, datasets=None):
"""
Collect statistics for given cube.
Parameters
----------
cube: Cube
Cube specification.
store: simplekv.KeyValueStore
KV store that preserves the cube.
datasets: Union[None, Iterable[str], Dict[str, kartothek.core.dataset.Da... | 47,194 |
def post_move_subject(subject_uuid: SubjectId, target_report_uuid: ReportId, database: Database):
"""Move the subject to another report."""
data_model = latest_datamodel(database)
reports = latest_reports(database)
source = SubjectData(data_model, reports, subject_uuid)
target = ReportData(data_mode... | 47,195 |
def _close_std_streams():
"""Close all our stdin/stdout/stderr streams."""
sys.stdin.close()
sys.stdout.close()
sys.stderr.close()
os.close(0)
os.close(1)
os.close(2) | 47,196 |
def makefunction(exprs, assignto, funcname='func', returncodestr=False, usenumba=True):
"""
Given sympy expressions list `expr` and a list of variable names
`assignto`, it creates a function. It returns a function object if
`returncodestr` = False. Otherwise, it returns a formatted function code
as ... | 47,197 |
def open_instrument(instr_type):
"""open_visa_instrument implements the public api for each of the drivers for discovering and opening a connection
:param instr_type:
The abstract base class to implement
A dictionary containing the technical specifications of the required equipment
:return:
A i... | 47,198 |
def thisyear():
"""The current year."""
return jinja2.Markup(datetime.date.today().year) | 47,199 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.