content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def _fit_and_predict(estimator, X, X_for_test, y, train, test, verbose, fit_params,
method):
"""Fit estimator and predict values for a given dataset split.
Read more in the :ref:`User Guide <cross_validation>`.
Parameters
----------
estimator : estimator object implementing 'f... | 5,299,900 |
def make_surf_graph(vertices, faces, mask=None):
"""
Constructs adjacency graph from `surf`
Parameters
----------
vertices : (N, 3) array_like
Coordinates of `vertices` comprising mesh with `faces`
faces : (F, 3) array_like
Indices of `vertices` that compose triangular faces of ... | 5,299,901 |
def options_parse():
"""
Command line option parser
"""
parser = argparse.ArgumentParser()
# Options for model parameters setup (only change if model training was changed)
parser.add_argument('--num_filters', type=int, default=64,
help='Filter dimensions for DenseNet (al... | 5,299,902 |
def clahe(
image,
clip_limit: float = 0.01,
tile_size: Tuple[int, int] = (8, 8),
use_signed_negative: bool = False,
):
"""
Applies CLAHE equalization to input image. Works on color images by
converting to Lab space, performing clahe on the L channel, and converting
back to RGB. Note that... | 5,299,903 |
def ResolvConfigDir(config_dir, sys_only=False):
"""Checks for a user config directory and if it is not
found it then resolves the absolute path of the executables
directory from the relative execution path. This is then used
to find the location of the specified directory as it relates
to the execu... | 5,299,904 |
def test_setting_initial_amount():
"""Testing constructor initial balance"""
wallet = Wallet(100)
assert wallet.balance == 100 | 5,299,905 |
def train_model(learning_rate, steps, batch_size, input_feature="total_rooms"):
"""Trains a linear regression model of one feature.
Args:
learning_rate: A `float`, the learning rate.
steps: A non-zero `int`, the total number of training steps. A training step consists of a forward and backwar... | 5,299,906 |
def test_that_deleted_files_are_handled_gracefully_under_cleanup(
create_temp_files,
):
"""When creations have been deleted they should be skipped."""
content, target = create_temp_files(2)
created_files = CreatedFiles()
created_files.insert(
module='name',
creation_method=CreationM... | 5,299,907 |
def getLogger(options):
"""
Set up logger based on options
and store the instance in options.logger
"""
LEVELS = {'debug': logging.DEBUG,
'info': logging.INFO,
'warning': logging.WARNING,
'error': logging.ERROR,
'critical': logging.CRITICAL}
level = LEVE... | 5,299,908 |
def rnn(node: NodeWrapper,
params: Dict[str, np.ndarray],
xmap: Dict[str, XLayer]):
""" ONNX RNN to XLayer AnyOp conversion function """
logger.info("ONNX RNN -> XLayer AnyOp")
raise NotImplementedError("ONNX RNN operator conversion not supported") | 5,299,909 |
def scantree(path):
"""Recursively yield DirEntry objects for given directory.
Courtesy: https://stackoverflow.com/a/33135143
:returns generator: A generator for ``DirEntry`` objects.
"""
for entry in os.scandir(path):
if entry.is_dir(follow_symlinks=False):
yield from scantre... | 5,299,910 |
def jsonify_dict(d):
"""Turns python booleans into strings so hps dict can be written in json.
Creates a shallow-copied dictionary first, then accomplishes string
conversion.
Args:
d: hyperparameter dictionary
Returns: hyperparameter dictionary with bool's as strings
"""
d2 = d.copy() # shallow c... | 5,299,911 |
def test_default_value_client():
"""Test port default value if no settings.ini is found."""
server_port = nss_client.NetworkAddresses().port
assert server_port == 54321 | 5,299,912 |
def pods(
needle: str,
haystack: SearchablePods,
parse: None = None,
*,
type: None = None,
allow_mismatch: Literal[True],
) -> Optional[Any]:
"""
If `allow_mismatch` is True and `type` is None, we return an `object`, or None
""" | 5,299,913 |
def delete_floating_ips(request):
"""The deleting floating ips view."""
result = {}
project_id = request.POST['project_id']
user_token = request.POST['user_token']
region = request.POST['region']
floating_ips_dict = remove_project_resource(
region,
project_id,
'floating_... | 5,299,914 |
def concat(funcname, args):
"""Return args spliced by sql concat operator."""
return " || ".join(args) | 5,299,915 |
def parse_args():
"""Parses the arguments from the command line."""
parser = argparse.ArgumentParser()
parser.add_argument(
"--version", help="Print the version and path to this script.",
action="store_true"
)
parser.add_argument(
"--empty", help="creates an empty modeling f... | 5,299,916 |
def generate_fe_entry(entry, name):
"""add function
"""
java_output = ""
java_output += "\"" + name + "\""
java_output += ", \"" + entry["symbol"] + "\""
if entry["user_visible"]:
java_output += ", true"
else:
java_output += ", false"
if 'prepare' in entry:
java_o... | 5,299,917 |
def seg_file2tensor_4band(f, fir, resize):
"""
"seg_file2tensor(f)"
This function reads a jpeg image from file into a cropped and resized tensor,
for use in prediction with a trained segmentation model
INPUTS:
* f [string] file name of jpeg
OPTIONAL INPUTS: None
OUTPUTS:
* im... | 5,299,918 |
def get_pyshp_field_dtypes(code):
"""Returns a numpy dtype for a pyshp field type."""
dtypes = {'N': np.int,
'F': np.float,
'L': np.bool,
'C': np.object}
return dtypes.get(code, np.object) | 5,299,919 |
def totient(num):
"""
Counts the numbers that are relative prime to the number.
This means that if a number 'x' has common divisors with another number 'a' lower than itself,
it is, 'a' is not relative prime to 'x'.
This means that if a number is prime, its totient function is its value - 1, as
... | 5,299,920 |
def change_to_task():
"""
Change a line to a task. The line must not start with - [ ],
it can only be a list item or a simple line.
"""
(row, _) = vim.current.window.cursor
# To index from 0 to N-1, not from 1, avoid row-1 everywhere in the script
row = row - 1
line = vim.current.buffer... | 5,299,921 |
def upload_artifacts_s3(component_name, component_version):
"""
Uploads all the artifacts from component artifacts build folder to s3 bucket.
Raises an exception when the request is not successful.
Parameters
----------
component_name(string): Name of the component to use in the s3 file pa... | 5,299,922 |
def _load_requirements(requirements_file, folder="requirements"):
"""Load requirements from a file."""
requirements = []
with open(Path(folder) / Path(requirements_file), "r") as f:
for line in f:
line = line.strip()
if line and not line.startswith("#"):
requi... | 5,299,923 |
def img_preprocess(img):
"""
preprocessing on the input image
first crops the image then resizes it
"""
return resize_img(crop_img(img)) | 5,299,924 |
def test_timing(dset_size=10000, num_write=20000,
num_samples=1000, sample_size=32):
""" Speed test for replay dataset storage scheme. """
import matplotlib.pyplot as plt
if os.path.exists("test.hdf5"):
os.remove("test.hdf5")
if not os.path.isdir("evaluation"):
os.makedi... | 5,299,925 |
def sampled_dropout_average(mlp, inputs, num_masks,
default_input_include_prob=0.5,
input_include_probs=None,
default_input_scale=2.,
input_scales=None,
rng=(2013, 5, 17),
... | 5,299,926 |
def urljoin(url1: str, url2: str) -> str:
""" Custom function to join two url paths
Uses `~urllib.parse.urlparse` and `~urllib.parse.urlunparse`
to join relevant segments of two urls. Does not use `~urllib.parse.urljoin`
as that replaces existing url path with a new path.
Parameters
---------... | 5,299,927 |
def getEvoBibAsBibtex(*keys, **kw):
"""Download bibtex format and parse it from EvoBib"""
res = []
for key in keys:
bib = get_url(
"http://bibliography.lingpy.org/raw.php?key=" + key,
log=kw.get('log')).text
try:
res.append('@' + bib.split('@')[1].split('<... | 5,299,928 |
def _parse_list(values: Any, message) -> None:
"""Parse list to protobuf message."""
if len(values) > 0 and isinstance(values[0], dict): # value needs to be further parsed
for v in values:
cmd = message.add()
_parse_dict(v, cmd)
else: # value can be set
message.exte... | 5,299,929 |
def image_distance(x: IMAGE_HASH, y: IMAGE_HASH) -> int:
"""Calculates the distance between to image hashes
Arguments:
x {IMAGE_HASH} -- IMAGE_HASH object for image 1
y {IMAGE_HASH} -- IMAGE_HASH object for image 2
Returns:
int -- hamming distance of two image hashes
"""
r... | 5,299,930 |
def random_date(start_date: str, end_date: str):
"""
This function will return a random datetime between two datetime
objects.
"""
dt_start = datetime.strptime(start_date, "%Y-%m-%d")
dt_end = datetime.strptime(end_date, "%Y-%m-%d")
delta = dt_end - dt_start
int_delta = (delta.days * 24... | 5,299,931 |
def oauth2_get_token():
"""Get an oauth2 auth_token for the app to work. May need app approval
"""
params = load_config_file(OAUTH_CONFIG_FILE)
oauth = OAuth2Session(params["client_id"], scope=params["scope"])
token_expires = datetime.utcfromtimestamp(params.get("expires_at", 0))
refresh = (toke... | 5,299,932 |
def get_emails(notification_rec):
"""
Get list of emails for users listed in the specified notification
"""
# Use a set instead of list as there could be duplicates.
ret = []
for recipient in notification_rec.recipients.all():
ret.append(recipient.email)
return ret | 5,299,933 |
def generate_docstring(executable: Type[job_blocks.ExecutableSpec]) -> str:
"""Returns a docstring for a ExecutableSpec factory method."""
docstring = executable.__doc__
if _ATTRIBUTES_SECTION_HEADER not in docstring:
raise Exception(
f'Please add Attributes: section to {executable.__name__} docstring... | 5,299,934 |
def _validate_min_max(wave, indep_min, indep_max):
"""Validate min and max bounds are within waveform's independent variable vector."""
imin, imax = False, False
if indep_min is None:
indep_min = wave._indep_vector[0]
imin = True
if indep_max is None:
indep_max = wave._indep_vect... | 5,299,935 |
def get_actions_with_permissions(user_id: int, permissions: Permissions, action_type_id: typing.Optional[int] = None) -> typing.List[Action]:
"""
Get all actions which a user has the given permissions for.
Return an empty list if called with Permissions.NONE.
:param user_id: the ID of an existing user... | 5,299,936 |
def format_mqc(lane, info):
"""Format the data structure as wanted by MultiQC. This will be turned
directly into the mqc.yaml to make the Yield Summary table. I'm using
summarize_lane_contents as a basis, but note that script also sucks some of
the info from here into the Overview/Lane Summary ... | 5,299,937 |
def list2xml(datalist, roottag, elementname, pretty=False):
"""Converts a list to an UTF-8 encoded XML string.
See also dict2et()
"""
root = list2et(datalist, roottag, elementname)
return to_string(root, pretty=pretty) | 5,299,938 |
def test_get_full_name(user_factory):
"""
A user's full name should be composed of their first and last name.
"""
user = user_factory()
expected = "{first} {last}".format(
first=user.first_name, last=user.last_name
)
assert user.get_full_name() == expected | 5,299,939 |
def createNode(*args, **kwargs):
"""
This command creates a new node in the dependency graph of the specified type.
Flags:
- name : n (unicode) [create]
Sets the name of the newly-created node. If it contains namespace path, the new node will be created under... | 5,299,940 |
def text_type(string, encoding='utf-8'):
"""
Given text, or bytes as input, return text in both python 2/3
This is needed because the arguments to six.binary_type and six.text_type change based on
if you are passing it text or bytes, and if you simply pass bytes to
six.text_type without ... | 5,299,941 |
def setup(verbose=False):
"""
setup the application if it has not been setup yet
"""
if verbose:
logger.debug(set_color(
"checking if the application has been run before", level=10
))
bin.unzip_gecko.main(verbose=verbose) | 5,299,942 |
def intercom_user_hash(data):
"""
Return a SHA-256 HMAC `user_hash` as expected by Intercom, if configured.
Return None if the `INTERCOM_HMAC_SECRET_KEY` setting is not configured.
"""
if getattr(settings, 'INTERCOM_HMAC_SECRET_KEY', None):
return hmac.new(
key=_hashable_bytes(s... | 5,299,943 |
def create_yolox_dataset(image_dir, anno_path, batch_size, device_num, rank,
data_aug=True, is_training=True):
""" create yolox dataset """
from model_utils.config import config
cv2.setNumThreads(0)
if is_training:
filter_crowd = False
remove_empty_anno = False
... | 5,299,944 |
def quote_value(value: str) -> str:
"""
Ensures values with ";" are quoted.
>>> quote_value("foo")
'foo'
>>> quote_value("foo;bar")
'"foo;bar"'
"""
if value.find(";") != -1:
return f'"{value}"'
return value | 5,299,945 |
def parse_stories(lines, only_supporting=False):
"""Parse stories provided in the bAbi tasks format. If only_supporting is
true, only the sentences that support the answer are kept.
"""
data = []
story = []
for line in lines:
line = line.decode('utf-8').strip()
nid, line = line.s... | 5,299,946 |
def check_datetime_timetz(dt: datetime) -> ResultComparison:
""" post: _ """
return compare_results(_invoker("timetz"), dt) | 5,299,947 |
def process_string(logger, content, ignore_unsuitable, old_platform,
new_platform):
"""Add a configuration for a new platform to the modulemd document string.
It returns an error code and a string.
In case of no error, code will be 0 and the string will be the processed,
output docum... | 5,299,948 |
def get_temporal_entropy(y: np.ndarray, fs: int, config: dict) -> float:
"""
Temporal entropy is a measure of the temporal dispersal of acoustic energy within a recording,
has been shown to reflect the number of avian calls in a recording (Sueur, Pavoine et al. 2008).
:param y: mono audio
:param fs... | 5,299,949 |
def test_property_persistence(orca_session):
"""
Test persistence of properties across registration, saving, and reloading.
"""
t = SaveTable()
t.table = 'buildings'
t.columns = ['window_panes', 'number_of_chimneys']
t.filters = 'number_of_chimneys > 15'
t.output_type = 'csv'
t.... | 5,299,950 |
def partitions_query(addr):
"""
Query the worker at the given address for its partition routing
information.
"""
stdout = external_sender_query(addr, 'partition-query')
try:
return json.loads(stdout)
except Exception as err:
e = ObservabilityResponseError("Failed to deseriali... | 5,299,951 |
def config_server_status(ctx):
"""
Show the server ElasticSearch status connection.
"""
hes = HoruzES("", ctx)
if hes.is_connected():
ctx.log("ElasticSearch is connected to {} successfully!".format(
ctx.config.get("elasticsearch_address")))
else:
ctx.log("ElasticSearc... | 5,299,952 |
def metrics(output_softmax, labels, num_classes):
"""
Builds the metrics for the model, including IoU and accuracy
:param output_softmax: TF Tensor containing the sofmax operation on the last layer in the neural network
before the decoder
:param labels: TF Placeholder for th... | 5,299,953 |
def update_config(config: dict):
"""Update the passed config dictionary."""
version_classes = _get_version_classes()
if 'version' not in config:
config_version = (0, 1, 0)
else:
config_version = _version_value(config['version'])
apply_classes = [x[1] for x in version_classes if confi... | 5,299,954 |
def join_docs(sep: Callable[[], Doc], docs: list[Doc]) -> list[Doc]:
"""Join a sequence of tokens with a separator"""
list_vals = []
for i, doc in enumerate(docs):
if i != 0:
list_vals.append(sep())
list_vals.append(doc)
return list_vals | 5,299,955 |
def make_literal_parser(*args: t.Any) -> comb.Parser:
"""Return parser for t.Literal[args]."""
return comb.Or(*map(comb.Lit, args)) | 5,299,956 |
def xyz(date, velocity=False, equinox=1950.0):
"""
Calculate geocentric X,Y, and Z and velocity coordinates of the Sun.
Parameters
----------
date : float
Julian date
equinox : float
Equinox of output. If None, Equinox will be 1950.
velocity : boolean
If False, the ... | 5,299,957 |
def estimation_formula_bg(growth, eps):
"""
The stock price estimation formula suggested by Benjamin Graham
According to "The Intelligent Investor"
"""
return (2*growth+8.5)*eps | 5,299,958 |
def grid3d2Order(unaries,regularizer,order='numpy',operator='adder'):
"""
returns a 2d-order model on a 3d grid (volume).
The regularizer is the same for all 2.-order functions.
Keyword arguments:
unaries -- unaries as 4d numpy array where the last dimension iterates over the labels
regularizer -- s... | 5,299,959 |
def run(zmatName, cgen, opt, charge, molname, workdir, debug, checkrun = True):
"""
Run BOSS different times to generate Bonds, Angles, Dihedrals, Charges and VdW OPLSAA parameters
Parameters
----------
zmatName : str
Name of the Zmat file of the molecule
cgen : str
Charge method selec... | 5,299,960 |
def parse_arguments(args=None) -> None:
"""Returns the parsed arguments.
Parameters
----------
args: List of strings to be parsed by argparse.
The default None results in argparse using the values passed into
sys.args.
"""
parser = argparse.ArgumentParser(
descriptio... | 5,299,961 |
def makeTestSuiteV201111():
"""Set up test suite using v201111.
Returns:
TestSuite test suite using v201111.
"""
suite = unittest.TestSuite()
suite.addTests(unittest.makeSuite(DfpWebServiceTestV201111))
return suite | 5,299,962 |
def print_information(information: str) -> None:
"""
Prints the information with a colored font
"""
exec_colored(INFORMATION_COLOR, print, information) | 5,299,963 |
def refresh_handler(unused_addr, args):
"""
Refresh text
"""
logger.info("Refreshing text")
send_questions_to_line_editor()
return None | 5,299,964 |
async def huobi_spot_tickers(api_key: str, secret_key: str, symbol: str = None):
"""
获取行情数据
:param api_key:
:param secret_key:
:param symbol:
:return:
"""
huobi = HuobiAPI(api_key, secret_key)
return await huobi.tickers(symbol=symbol) | 5,299,965 |
def make_quality_step(env, run_time, route_to, transit_time=1, **kwargs):
"""
"""
return {
'location': env['quality_bench'],
'worker': env['qual_inspector'],
'manned': True,
'setup_time': 0,
'run_time': run_time,
'teardown_time': 0,
'transit_time': tr... | 5,299,966 |
def reverse_sorting_order(str_name):
"""Return False if str_name ends with one of the err_strings suffixes. Otherwise, return True.
Negation was introduced as the function is used to determine the order of the sorting depending on scoring
function name: if scoring ends with "_error" or "_loss", it means th... | 5,299,967 |
def parse_keyval(line: str, valsplit: str = ':', csvsplit=',') -> List[Tuple[str, str]]:
"""
Parses a csv with key:value pairs such as::
John Alex:Doe,Jane Sarah:Doe
Into a list with tuple pairs (can be easily converted to a dict)::
[
('John Alex', 'Doe'),
('... | 5,299,968 |
def run_it(input_file, input_pattern, output_style):
"""
docstring
"""
# Read input file, convert each sequence in line to a sequence object,
# return objects in list
contents_of_file = read_file(input_file)
seq_obj_lst = gen_seq_obj_lst(contents_of_file)
# Send first sequence obj in li... | 5,299,969 |
def most_active():
"""Finds the most active station based on count of temp records"""
session=Session(engine)
# same as above but with station ID , aslo trying subquery method
active_station_id=session.query(\
Station.id,Station.station,\
func.count(Station.station).label('activity_c... | 5,299,970 |
def getUserInput():
"""
Purpose: to validate user Input
Parameters: None
Returns: x - validated user input
"""
x = input("Recursion Depth: ")
try:
x = int(x)
except ValueError:
x = getUserInput()
return x | 5,299,971 |
def attr_subresource(raml_resource, route_name):
""" Determine if :raml_resource: is an attribute subresource.
:param raml_resource: Instance of ramlfications.raml.ResourceNode.
:param route_name: Name of the :raml_resource:.
"""
static_parent = get_static_parent(raml_resource, method='POST')
i... | 5,299,972 |
def test_layabout_can_handle_all_events_with_a_splat_handler(events, run_once,
monkeypatch):
"""
Test that layabout can handle all events with a splat handler.
"""
layabout = Layabout()
SlackClient, slack = mock_slack(connections=(True,), ... | 5,299,973 |
def bicoherence( da,
nperseg,
plot=False,
windowFunc='hann',
title='',
mask='A',
drawRedLines=[],
f_units='Hz',
verbose=True,
fft_scale='log',
precondition_signal=True):
"""
Bicoherence and bispectrum analysis. This algorithm is based on [Kim1979].
This code appea... | 5,299,974 |
def irregular_grouper(seq, sizes):
"""
Yield irregularly sized chunks of a sequence.
@param seq: a sequence
@param sizes: an iterable of sizes
"""
i = 0
for k in sizes:
yield seq[i:i+k]
i += k | 5,299,975 |
def test_aggregate_resources_sas_scheduled_backup_job(only_nginx_simulation_fixture: conftest.DSA):
"""
This test verifies that all resources which comprise the sas-scheduled-backup-job component are correctly aggregated
to create the component definition.
:param only_nginx_simulation_fixture: test fix... | 5,299,976 |
def erall(interp):
"""
ERALL
command. Erases all unburied procedures, variables, and property
lists from the workspace. Abbreviates ERASE CONTENTS.
"""
# @@: No buried makes this dangerous
erase(interp, names(interp))
erase(interp, procedures(interp)) | 5,299,977 |
def translate_path_into_actions(rail_env, pathways, time_step):
"""Translates the solution paths of the CBS algorithm into an action for a given time step.
:param rail_env: The Flatland environment.
:param pathways: The solution paths of the CBS algorithm.
:param time_step: The time step for which an a... | 5,299,978 |
def test_module(client: Client) -> str:
"""
Tests API connectivity and authentication'
Returning 'ok' indicates that connection to the service is successful.
Raises exceptions if something goes wrong.
"""
try:
response = client.translate('I have the high ground!')
success = de... | 5,299,979 |
def plot_confusion_matrix(cm, label):
"""
Keyword Arguments:
correct_labels -- These are your true classification categories.
predict_labels -- These are you predicted classification categories
label -- This is a list of string labels corresponding labels
Returns: Figure
"""
fi... | 5,299,980 |
def _compare_numeric(src_num, dst_num):
"""Compare numerical values. You can use '<%d','>%d'."""
dst_num = float(dst_num)
match = numeric_compare_regex.match(src_num)
if not match:
error = "Failed numeric comparison. Collected: {}. Expected: {}".format(dst_num, src_num)
raise ValueError... | 5,299,981 |
def run_pd_rpc(cmd_or_code, no_print=False):
"""
This function invokes run_pd_rpc.py tool. It has a single string argument
cmd_or_code that works as follows:
If it is a string:
* if the string starts with os.sep, then it is a filename
* otherwise it is a piece of code (passed ... | 5,299,982 |
def actionlstm_cell(x, h, a, num_units, action_dim,
initializer=tf.contrib.layers.xavier_initializer(),
bias_initializer=tf.constant_initializer(0.0),
activation=tf.tanh, scope='action_lstm'):
"""
:param x: state input
:param h: hidden state tuple... | 5,299,983 |
def last_capture():
"""Get the most recent capture
It's probably worth checking this a bit.
The last item in the list might not be the latest.
Best to check for the largest number.
Do these loop over to the begining?
"""
capture_files = list_captures()
print 'File: %s' % capture_files[-... | 5,299,984 |
def test_alt_id():
"""Ensure that alternate GO IDs."""
obo_dag = get_godag("go-basic.obo")
alt_ids = get_altids(obo_dag)
obo_goids = obo_dag.keys()
obo_goids_set = set(obo_goids)
assert len(alt_ids.intersection(obo_goids_set)) == len(alt_ids) | 5,299,985 |
def get_config():
"""Gets config from command line and console, returns config"""
# config = {
# 'overwrite': True or False
# 'server': String
# 'port': Integer
# 'user': String
# 'pass': String
# 'usessl': True or False
# 'keyfilename': String or None
# 'certfile... | 5,299,986 |
def extrapolate_accel_data_testing(filename):
"""Extrapolate data from a txt file
data will have format:
x1,y1,z1;
x2,y2,z2;
..
xn,yn,zn;
:param filename: file to read from
:return: datax, datay, dataz vectors (np.array)
"""
x = []
y = []
z = []
import numpy as np
... | 5,299,987 |
def get_loss_obj(cfg: Config) -> loss.BaseLoss:
"""Get loss object, depending on the run configuration.
Currently supported are 'MSE', 'NSE', 'RMSE', 'GMMLoss', 'CMALLoss', and 'UMALLoss'.
Parameters
----------
cfg : Config
The run configuration.
Returns
-------
loss.B... | 5,299,988 |
def _melspecgrams_to_specgrams(melspecgrams: tf.Tensor, mel2l) -> tf.Tensor:
"""Converts melspecgrams to specgrams.
Args:
melspecgrams: Tensor of log magnitudes and instantaneous frequencies,
shape [..., channels, time, freq, 2], mel scaling of frequencies.
mel2l: Mel to linear matrix
Re... | 5,299,989 |
def benchmark_descending_operator(rhoab, rhoba, w, v, u, num_layers):
"""
run benchmark for descending super operator
Args:
rhoab (tf.Tensor): reduced densit matrix on a-b lattice
rhoba (tf.Tensor): reduced densit matrix on b-a lattice
w (tf.Tensor): isometry
v (tf.Te... | 5,299,990 |
def extract_sun_angles(xml):
"""Extract Sentinel-2 solar angle bands values from MTD_TL.xml.
Parameters:
xml (str): path to MTD_TL.xml.
Returns:
str, str: sz_path, sa_path: path to solar zenith image, path to solar azimuth image, respectively.
"""
solar_zenith_values = numpy.empty((23,... | 5,299,991 |
def get_citation_ids(semantic_results, direction: str = "citations", cit_n: int = 1):
"""Returns ids for AI paper citations and
references below a threshold and above a citation threshold"""
cit_df = pd.DataFrame(
chain(*[get_citation_meta(art, direction) for art in semantic_results])
)[["arxiv... | 5,299,992 |
async def test_async(c, s, a, b):
"""Test asynchronous operations."""
da = dask.array.arange(0, 25, chunks=5, dtype=float).reshape((5, 5))
q = ureg.Quantity(da, units_)
x = q + ureg.Quantity(5, units_)
y = x.persist()
assert str(y)
assert dask.is_dask_collection(y)
assert len(x.__dask_... | 5,299,993 |
def spiral_grating(medium_groove=mp.Medium(epsilon=2),
D=0.4, d=None, DBR_period=0.2, FF=0.5, N_rings=10,
N_arms=2, thickness=0, center=mp.Vector3(0, 0, 0)):
"""
Elliptic DBR cavity created as a sequence of concentric cylinders.
Parameters
----------
medium_gro... | 5,299,994 |
def turn_off(hass, activity=None, entity_id=ENTITY_MATCH_ALL):
"""Turn all or specified remote off."""
data = {}
if activity:
data[ATTR_ACTIVITY] = activity
if entity_id:
data[ATTR_ENTITY_ID] = entity_id
hass.services.call(DOMAIN, SERVICE_TURN_OFF, data) | 5,299,995 |
def update_alarm_instance_comment(alarm_instance_id, comment,
step_name="", level=20, cover=True):
"""add alarm instance log"""
logger.info(
"$%s [%s][%s][%s]: %s",
alarm_instance_id, step_name, level, cover, comment)
if cover:
session.query(FtaSolut... | 5,299,996 |
def getDailyData(word: str,
start_year: int = 2007,
stop_year: int = 2018,
geo: str = 'US',
tz: int = 240,
verbose: bool = True,
wait_time: float = 5.0) -> pd.DataFrame:
"""Given a word, fetches daily search volume... | 5,299,997 |
def delete_unwanted_fields(obj, eng):
"""Delete unwanted fields"""
keys_to_delete = (
"curated",
"citeable",
"files",
)
for key in keys_to_delete:
obj.data.pop(key, None) | 5,299,998 |
def compare_xml(xml1, xml2, output_file=False, sorted_json=True,
remove_namespaces=False, tag_list=[], attrib_list=[]):
"""
This will compare two xml files or strings by converting to json
and then sorting and by default giving the sorted files
and writing the difference to a diff file.
... | 5,299,999 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.