content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def neighborhood(index, npoints, maxdist=1):
"""
Returns the neighbourhood of the current index,
= all points of the grid separated by up to
*maxdist* from current point.
@type index: int
@type npoints: int
@type maxdist int
@rtype: list of int
"""
return [index + i for i in ran... | 2,800 |
def insert_node_before_node(graph: Graph,
node_to_insert: BaseNode,
last_node: BaseNode):
"""
Insert a new node to a graph before an existing node in the graph.
Check before insertion that the node (that we add the new node before) has
only a singl... | 2,801 |
def test_book_id_get_correct_auth_not_users_book_gets_404_status_code(testapp, testapp_session, one_user):
"""Test that GET to book-id route gets 404 status code for book that does not beling to user."""
book = testapp_session.query(Book).filter(Book.user_id != one_user.id).first()
data = {
'email'... | 2,802 |
def data_check(data):
"""Check the data in [0,1]."""
return 0 <= float(data) <= 1 | 2,803 |
def tokenize(text):
"""
Tokenization function to process text data
Args:
text: String. disaster message.
Returns:
clean_tokens: list. token list from text message.
"""
url_regex = 'http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+'
# get list of a... | 2,804 |
def log(msg, level=xbmc.LOGDEBUG, **kwargs):
"""InputStream Helper log method"""
xbmc.log(msg=from_unicode('[{addon}] {msg}'.format(addon=addon_id(), msg=msg.format(**kwargs))), level=level) | 2,805 |
def get_symbol_historical(symbol_name):
"""Returns the available historical data for a symbol as a dictionary."""
# Get the data
symbol_data = get_symbol_data(symbol_name)
# Build the response
response = symbol_data.to_dict(orient="records")
return response | 2,806 |
def create_topology1():
"""
1. Create a data center network object (DCNetwork) with monitoring enabled
"""
net = DCNetwork(monitor=True, enable_learning=False)
"""
1b. Add endpoint APIs for the whole DCNetwork,
to access and control the networking from outside.
e.g., to setup fo... | 2,807 |
def guesses(word):
"""
return all of the first and second order guesses for this word
"""
result = list(known(*first_order_variants(word)))
result.sort()
return result | 2,808 |
def Pmf(pmf, **options):
"""Plots a Pmf or Hist as a line.
Args:
pmf: Hist or Pmf object
options: keyword args passed to pyplot.plot
"""
xs, ps = pmf.Render()
if pmf.name:
options = Underride(options, label=pmf.name)
Plot(xs, ps, **options) | 2,809 |
def em(X, sf, inits, K, L, n_iter=100, n_inner_iter=50, tol=1e-5, zero_inflated=True):
"""
run EM algorithm on the given init centers
return the clustering labels with the highest log likelihood
"""
# add prepare reduced data here
print("start em algorithm")
res = _em(X, sf, inits, K, L, ... | 2,810 |
def is_disaggregate(data, raw_fuel_sectors_enduses):
"""TODO: Disaggregate fuel for sector and enduses with floor
area and GVA for sectors and enduses (IMPROVE)
#TODO: DISAGGREGATE WITH OTHER DATA
"""
is_fueldata_disagg = {}
national_floorarea_sector = 0
for region_name in data['lu_reg']:
... | 2,811 |
def update_logger(evo_logger, x, fitness, memory, top_k, verbose=False):
""" Helper function to keep track of top solutions. """
# Check if there are solutions better than current archive
vals = jnp.hstack([evo_logger["top_values"], fitness])
params = jnp.vstack([evo_logger["top_params"], x])
concat... | 2,812 |
def do_open(args, _):
"""usage: open cluster[/role[/env/job]]
Opens the scheduler page for a cluster, role or job in the default web browser.
"""
cluster_name = role = env = job = None
if len(args) == 0:
print('Open command requires a jobkey parameter.')
exit(1)
v1_deprecation_warning("open", ["job... | 2,813 |
def ae(nb_features,
input_shape,
nb_levels,
conv_size,
nb_labels,
enc_size,
name='ae',
prefix=None,
feat_mult=1,
pool_size=2,
padding='same',
activation='elu',
use_residuals=False,
nb_conv_per_level=1,
batch_norm=None,
... | 2,814 |
def read_authorized_keys(username=None):
"""Read public keys from specified user's authorized_keys file.
args:
username (str): username.
returns:
list: Authorised keys for the specified user.
"""
authorized_keys_path = '{0}/.ssh/authorized_keys'.format(os.path.expanduser('~{0}'.for... | 2,815 |
def get_fprime_version():
""" Gets the fprime version using setuptools_scm """
# First try to read the SCM version
try:
return get_version(root=os.sep.join([".."] * ROOT_PARENT_COUNT), relative_to=__file__)
# Fallback to a specified version when SCM is unavailable
except LookupError:
... | 2,816 |
def push(player, dealer):
"""
Functions to handle end of game scenarios.
:param player:
:param dealer:
:return:
"""
print('Dealer and Player tie! It is a push.') | 2,817 |
def parser_config(p):
"""JLS file info."""
p.add_argument('--verbose', '-v',
action='store_true',
help='Display verbose information.')
p.add_argument('filename',
help='JLS filename')
return on_cmd | 2,818 |
def preprocess_raw_data():
"""
Reads raw data from local and makes pre-processing necessary to use dataset with ARIMA.
Function assumes that the date column is named as 'Date'. It saves prep-processed dataset
the local.
"""
raw_df = read_data('raw_data')
raw_df['Date'] = list(map(lambda x:... | 2,819 |
def error_by_error_scatterplot(output_directory, file_prefix, df,
reference_series_index, x_series_index, y_series_index,
x_color, y_color,
x_series_name = None, y_series_name = None,
plot_title = '', x_a... | 2,820 |
def decentralized_training_strategy(communication_rounds, epoch_samples, batch_size, total_epochs):
"""
Split one epoch into r rounds and perform model aggregation
:param communication_rounds: the communication rounds in training process
:param epoch_samples: the samples for each epoch
:param batch_... | 2,821 |
def create_config_file_lines():
"""Wrapper for creating the initial config file content as lines."""
lines = [
"[default]\n",
"config_folder = ~/.zettelkasten.d\n",
"\n",
"def_author = Ammon, Mathias\n",
"def_title = Config Parsed Test Title\n",
"def_location_spec... | 2,822 |
def delete_snapshots(cluster_name, path, recursive='0'):
"""删除快照数据信息
"""
if recursive == "1":
# monkey patch for delete snapshots recursively
target_path = path.rstrip("/") + "/"
del_snapshot_query = ZdSnapshot.delete().where(
(ZdSnapshot.cluster_name == cluster_name) &
... | 2,823 |
def get_dummies(
data: pandas.core.frame.DataFrame,
prefix: Dict[Literal["B", "A"], Literal["bar", "foo"]],
columns: List[Literal["B", "A"]],
dtype: Type[numpy.int8],
):
"""
usage.koalas: 1
"""
... | 2,824 |
def p_planes_tangent_to_cylinder(base_point, line_vect, ref_point, dist, ):
"""find tangent planes of a cylinder passing through a given point ()
.. image:: ../images/plane_tangent_to_one_cylinder.png
:scale: 80 %
:align: center
Parameters
----------
base_point : point
poin... | 2,825 |
def BOPTools_AlgoTools3D_OrientEdgeOnFace(*args):
"""
* Get the edge <aER> from the face <aF> that is the same as the edge <aE>
:param aE:
:type aE: TopoDS_Edge &
:param aF:
:type aF: TopoDS_Face &
:param aER:
:type aER: TopoDS_Edge &
:rtype: void
"""
return _BOPTools.BOPTools_... | 2,826 |
def create_store_from_creds(access_key, secret_key, region, **kwargs):
"""
Creates a parameter store object from the provided credentials.
Arguments:
access_key {string} -- The access key for your AWS account
secret_key {string} -- The secret key for you AWS account
region {stri... | 2,827 |
def comment_lgtm(pr_handle):
"""
Posts a LGTM (Looks good to me!) comment in the PR, if PR did not produced new clang-tidy warnings or errors.
"""
lgtm = 'This Pull request Passed all of clang-tidy tests. :+1:'
comments = pr_handle.get_issue_comments()
for comment in comments:
if commen... | 2,828 |
def example_manual_j1939():
"""Manually enter a few frames as a list and decode using J1939 rules.
"""
timestamp = datetime.now(timezone.utc)
frames = [
{
"TimeStamp": timestamp.timestamp() * 1E9,
"ID": 0x0CF004FE,
"IDE": True,
"DataBytes": [
... | 2,829 |
def are_objects_equal(object1, object2):
"""
compare two (collections of) arrays or other objects for equality. Ignores nan.
"""
if isinstance(object1, abc.Sequence):
items = zip(object1, object2)
elif isinstance(object1, dict):
items = [(value, object2[key]) for key, value in object... | 2,830 |
def get_recipes_from_dict(input_dict: dict) -> dict:
"""Get recipes from dict
Attributes:
input_dict (dict): ISO_639_1 language code
Returns:
recipes (dict): collection of recipes for input language
"""
if not isinstance(input_dict, dict):
raise TypeError("Input is not typ... | 2,831 |
def tasks_from_wdl(wdl):
"""
Return a dictionary of tasks contained in a .wdl file.
The values are task definitions within the wdl
"""
return scopes_from_wdl("task", wdl) | 2,832 |
def ejobs(args, bjobsargs):
"""Wrapper script with bjobs functionality."""
# handle arguments
if args.pending:
bjobsargs = ["-p"] + bjobsargs
args.groupby = "pend_reason"
for shortcutname, shortcutargs in ejobsshortcuts.items():
if getattr(args, shortcutname):
bjobsar... | 2,833 |
def install_openstack_service_checks():
"""Entry point to start configuring the unit
Triggered if related to the nrpe-external-master relation.
Some relation data can be initialized if the application is related to
keystone.
"""
set_flag('openstack-service-checks.installed')
clear_flag('ope... | 2,834 |
def test_phenomodel_POST_add_hpo_checkbox_to_subpanel(app, user_obj, institute_obj, hpo_checkboxes):
"""Test adding an HPO checkbox with its children to a subpanel of a phenotype model via POST request"""
# GIVEN an institute with a phenotype model
store.create_phenomodel(institute_obj["internal_id"], "Tes... | 2,835 |
def wrap_parse(content, args):
"""
Wraps a call to `parse` in a try/except block so that one can use a Pool
and still get decent error messages.
Arguments
---------
content: segments are strings
args: a namespace, see `parse`
Returns
-------
parse trees and time to parse
""... | 2,836 |
async def get_category_item_route(category_id: CategoryEnum, item_id: ObjectID,
db: AsyncIOMotorClient = Depends(get_database)) -> ItemInResponse:
"""Get the details about a particular item"""
_res = await db[category_id]["data"].find_one({"_id": item_id})
if _res:
... | 2,837 |
def weighted_SVD(matrix, error=None, full_matrices=False):
"""
Finds the most important modes of the given matrix given the weightings
given by the error.
matrix a horizontal rectangular matrix
error weighting applied to the dimension corresponding to the rows
"""
if type(error) is type... | 2,838 |
def ingredients():
"""Route to list all ingredients currently in the database.
"""
query = request.args.get("q")
ingredients = db.get_ingredient_subset_from_db(query)
return jsonify(ingredients) | 2,839 |
def read_h5_particles(particles_file, refpart, real_particles, bucket_length, comm, verbose):
"""Read an array of particles from an HDF-5 file"""
four_momentum = refpart.get_four_momentum()
pmass = four_momentum.get_mass()
E_0 = four_momentum.get_total_energy()
p0c = four_momentum.get_momentum()
... | 2,840 |
def readAndMapFile(path):
"""
Main file breaker - this takes a given file and breaks it into arbitrary
fragments, returning and array of fragments. For simplicity, this is breaking on
newline characters to start with. May have to be altered to work with puncuation
and/or special characters as nee... | 2,841 |
def fetch_git_logs(repo, from_date, to_date, args): # pragma: no cover
"""Fetch all logs from Gitiles for the given date range.
Gitiles does not natively support time ranges, so we just fetch
everything until the range is covered. Assume that logs are ordered
in reverse chronological order.
"""
cursor = '... | 2,842 |
def _gen_bfp_op(op, name, bfp_args):
"""
Do the 'sandwich'
With an original op:
out = op(x, y)
grad_x, grad_y = op_grad(grad_out)
To the following:
x_, y_ = input_op(x, y)
Where input_op(x, y) -> bfp(x), bfp(y)
and input_op_grad(grad_x, grad_y) -> bfp(grad_x), bfp(grad_y)
out_... | 2,843 |
def angleaxis_to_rotation_matrix(aa):
"""Converts the 3 element angle axis representation to a 3x3 rotation matrix
aa: numpy.ndarray with 1 dimension and 3 elements
Returns a 3x3 numpy.ndarray
"""
angle = np.sqrt(aa.dot(aa))
if angle > 1e-6:
c = np.cos(angle);
s = np.sin(a... | 2,844 |
def optimise_csr_matrix(csr_matrix):
"""
Performs **in place** operations to optimise csr matrix data. Returns None.
"""
# xxx todo profile performance using permutations / subsets of these
csr_matrix.sum_duplicates()
csr_matrix.eliminate_zeros()
csr_matrix.sort_indices() | 2,845 |
def test_basic_property_of_random_matrix():
"""Check basic properties of random matrix generation"""
for name, random_matrix in all_random_matrix.items():
print(name)
check_input_size_random_matrix(random_matrix)
check_size_generated(random_matrix)
if name != "random_subsample_n... | 2,846 |
def profilerTool(categoryView: bool = False,collapseSelectedEvents: bool = False,collapseSelectedEventsRepetition: bool = False,cpuView: bool = False,destroy: bool = False,exists: bool = False,expandSelectedEvents: bool = False,expandSelectedEventsRepetition: bool = False,findNext: bool = False,findPrevious: bool = Fal... | 2,847 |
def sendOrderFAK(self, orderType, price, volume, symbol, exchange, stop=False):
"""发送委托"""
if self.trading:
# 如果stop为True,则意味着发本地停止单
req = {}
req['sid'] = self.sid
if orderType == CTAORDER_BUY:
req['direction'] = '0'
req['offset'] = '0'
elif orderT... | 2,848 |
def unique(lst):
"""
:param lst: a list of lists
:return: a unique list of items appearing in those lists
"""
indices = sorted(list(range(len(lst))), key=lst.__getitem__)
indices = set(next(it) for k, it in
itertools.groupby(indices, key=lst.__getitem__))
return [x for i, x... | 2,849 |
def max_frequency(sig, FS):
"""Compute max frequency along the specified axes.
Parameters
----------
sig: ndarray
input from which max frequency is computed.
FS: int
sampling frequency
Returns
-------
f_max: int
0.95 of max_frequency using cumsum.
"""
f, ... | 2,850 |
def split(text):
"""Turns the mobypron.unc file into a dictionary"""
map_word_moby = {}
try:
lines = text.split("\n")
for line in lines:
(word, moby) = line.split(" ", 1)
map_word_moby[word] = moby
except IOError as error:
print(f"Failed due to IOError: {... | 2,851 |
def remove_pos(lst):
"""Takes a list of pairs where the first part of a pair is the PO number and
the second is the result 1 = disproved, 2 = proved, 3 = unresolved. Then removes
the proved and disproved outputs and returns the aig with the unresolved
outputs"""
proved = disproved = unresolved = []
... | 2,852 |
def download_as_temporary(src_path_in_s3: Path, bucket_name: str = "keng000-mlops") -> Path:
"""
This context manager downloads a file from s3 as temporary.
Args:
same as the `download` function.
Returns:
Path: temporary file path.
"""
tmp_file = tempfile.NamedTemporaryFile()
... | 2,853 |
def patch_airflow_config(airflow_config):
"""
Updates provided Airflow configuration file to include defaults for cwl-airflow.
If something went wrong, restores the original airflow.cfg from the backed up copy
"""
# TODO: add cwl section with the following parameters:
# - singularity
# - us... | 2,854 |
def merge(old, new):
"""
Merge two .properties files into 1
For properties that are common between old and new, find the values that
changed, then overwrite values in new file with those from old file
For properties that differ between the two files, just print them out
Write the new properti... | 2,855 |
def report(key_name=None, priority=-1, **formatters):
""" Use this decorator to indicate what returns to include in the report and how to format it """
def tag_with_report_meta_data(cls):
# guard: prevent bad coding by catching bad return key
if key_name and key_name not in cls.return_keys:
... | 2,856 |
def calc_momentum_def(x_loc, X, Y, U):
""" calc_momentum_def() : Calculates the integral momentum deficit of scalar field U stored at \
locations X,Y on a vertical line that runs nearest to x_loc. """
U_line, x_line, x_idx_line = get_line_quantity(x_loc, X, Y, U)
y_line = Y[:,x_idx_line]
r... | 2,857 |
def display_unit_title(unit, app_context):
"""Prepare an internationalized display for the unit title."""
course_properties = app_context.get_environ()
template = get_unit_title_template(app_context)
return template % {'index': unit.index, 'title': unit.title} | 2,858 |
def load_user(user_id):
"""Load the user object from the user ID stored in the session"""
return User.objects(pk=user_id).first() | 2,859 |
def get_complex_replay_list():
"""
For full replays that have crashed or failed to be converted
:return:
"""
return [
'https://cdn.discordapp.com/attachments/493849514680254468/496153554977816576/BOTS_JOINING_AND_LEAVING.replay',
'https://cdn.discordapp.com/attachments/49384951468025... | 2,860 |
def print_stat(label, stat_val, p_val):
"""Helper function to print out statistical tests."""
print(label + ': \t {: 5.4f} \t{: 5.4f}'.format(stat_val, p_val)) | 2,861 |
def parse_registry():
""" Parses the provided registry.dat file and returns a dictionary of chunk
file names and hashes. (The registry file is just a json dictionary containing
a list of file names and hashes.) """
registry = request.values.get("registry", None)
if registry is None:
return ... | 2,862 |
def get_cosine_with_hard_restarts_schedule_with_warmup(optim: Optimizer,
num_warmup_step: float,
num_training_step: int,
num_cycles: float = 1.,
... | 2,863 |
def main():
"""
"""
generator('arch_dependencies', arch_dependencies)
generator('arch_packages', arch_packages)
generator('aur_packages', aur_packages)
generator('yay_packages', yay_packages)
generator('python_packages', python_packages)
generator('ttf_fonts', ttf_fonts)
generator('o... | 2,864 |
def home():
"""
Render Homepage
--------------------------------------------------------------
This site should be cached, because it is the main entry point for many users.
"""
bestseller: typing.List[Device] = get_bestsellers()
specialist_manufacturers = Manufacturer.query.filter(
... | 2,865 |
def reject_call():
"""Ends the call when a user does not want to talk to the caller"""
resp = twilio.twiml.Response()
resp.say("I'm sorry, Mr. Baker doesn't want to talk to you. Goodbye scum.", voice='woman', language='en-GB')
resp.hangup()
return str(resp) | 2,866 |
def table_prep(data, columns=''):
"""
Data processor for table() function.
You can call it separately as well and in
return get a non-prettyfied summary table.
Unless columns are defined, the three first
columns are chosen by default.
SYNTAX EXAMPLE:
df['quality_score'... | 2,867 |
def test_all_find_el_are_wrapped(snapshot):
"""All find_* functions are wrapped."""
el = MockDriver().find_element_by_id("ignored")
result = []
result.append(el.find_element_by_id("ignored"))
result.append(el.find_elements_by_id("ignored"))
result.append(el.find_element_by_xpath("ignored"))
... | 2,868 |
def lerp(a,b,t):
""" Linear interpolation between from @a to @b as @t goes between 0 an 1. """
return (1-t)*a + t*b | 2,869 |
def convert_to_legacy_v3(
game_tick_packet: game_data_struct.GameTickPacket,
field_info_packet: game_data_struct.FieldInfoPacket = None):
"""
Returns a legacy packet from v3
:param game_tick_packet a game tick packet in the v4 struct format.
:param field_info_packet a field info packet i... | 2,870 |
def load_settings():
"""Load settings and set the log level."""
settings.load()
logging.getLogger().setLevel(
logging.DEBUG if settings["debug_logging"] else logging.INFO
) | 2,871 |
def _load_audio(audio_path, sample_rate):
"""Load audio file."""
global counter
global label_names
global start
global end
logging.info("Loading '%s'.", audio_path)
try:
lbl1=Alphabet[audio_path[-6]]
lbl2 = Alphabet[audio_path[-5]]
except:
lbl1=1 + counter
lbl2=2 + counter
label_na... | 2,872 |
def generate_annotation_dict(annotation_file):
""" Creates a dictionary where the key is a file name
and the value is a list containing the
- start time
- end time
- bird class.
for each annotation in that file.
"""
annotation_dict = dict()
for line i... | 2,873 |
def ishom(T, check=False, tol=100):
"""
Test if matrix belongs to SE(3)
:param T: SE(3) matrix to test
:type T: numpy(4,4)
:param check: check validity of rotation submatrix
:type check: bool
:return: whether matrix is an SE(3) homogeneous transformation matrix
:rtype: bool
- ``ish... | 2,874 |
def _get_stp_data(step_order=STEP_ORDER, n=N_PER_STEP):
"""Returns np.array of step-type enums data for sample data.
Parameters
----------
step_order : list of (int, char)
List of (Cycle number, step type code) for steps in sample procedure.
n : int
Number of datapoints per step.
... | 2,875 |
def actor_discrete_loss(actions, advantages, logits):
"""
Adapted from: http://inoryy.com/post/tensorflow2-deep-reinforcement-learning/
"""
# sparse categorical CE loss obj that supports sample_weight arg on call()
# from_logits argument ensures transformation into normalized probabilities
weigh... | 2,876 |
def fuse_stride_arrays(dims: Union[List[int], np.ndarray],
strides: Union[List[int], np.ndarray]) -> np.ndarray:
"""
Compute linear positions of tensor elements
of a tensor with dimensions `dims` according to `strides`.
Args:
dims: An np.ndarray of (original) tensor dimensions.
... | 2,877 |
def extract_jasmine_summary(line):
"""
Example SUCCESS karma summary line:
PhantomJS 2.1.1 (Linux 0.0.0): Executed 1 of 1 SUCCESS (0.205 secs / 0.001 secs)
Exmaple FAIL karma summary line:
PhantomJS 2.1.1 (Linux 0.0.0): Executed 1 of 1 (1 FAILED) ERROR (0.21 secs / 0.001 secs)
"""
# get tota... | 2,878 |
def main( argv ):
"""
Script execution entry point
@param argv Arguments passed to the script
@return Exit code (0 = success)
"""
#-------------------------------------------------------------------------
# BEGIN: Per-script Configuration
#---------------------------... | 2,879 |
def serialize_item(item):
"""
Args:
item: an XBlock
Returns:
fields: a dictionary of an XBlock's field names and values
block_type: the name of the XBlock's type (i.e. 'course'
or 'problem')
"""
from xmodule.modulestore.store_utilities import DETACHED_XBLOCK_TYPES
... | 2,880 |
def gen_outfile_name(args):
"""Generate a name for the output file based on the input args.
Parameters
----------
args : argparse
argparse object to print
"""
return args.outfile + gen_identifier(args) | 2,881 |
def check_vg_tags(game_id):
"""Returns a user's tags."""
if game_id:
user_id = session.get('user_id')
user_query = VgTag.query.join(Tag).filter(Tag.user_id == user_id) # Only display user's tags for a specific game.
vg_tags = user_query.filter(VgTag.game_id == game_id).all()
... | 2,882 |
def mutation_swap(self: MutateMethodCall, chrom: np.array):
"""
swap gene with random n position gene according to prob_mutate
:param self:
:param chrom: 0/1 type chromosome
"""
for i in range(len(chrom)):
if random.random() < self.prob_mutate:
n = np.random.randint(0, len(ch... | 2,883 |
def add_constituency_result_line(line, valid_codes=None, session=None):
"""Add in a result from a constituency. Any previous result is removed. If
there is an error, ValueError is raised with an informative message.
Session is the database session to use. If None, the global db.session is
used.
If... | 2,884 |
def load_fits(path):
"""
load the fits file
Parameters
----------
path: string, location of the fits file
Output
------
data: numpy array, of stokes images in (row, col, wv, pol)
header: hdul header object, header of the fits file
"""
hdul_tmp = fits.open(f'{path}')
data = np.asarray(... | 2,885 |
def get_image_path(cfg,
metadata,
prefix='diag',
suffix='image',
metadata_id_list='default',):
"""
Produce a path to the final location of the image.
The cfg is the opened global config,
metadata is the metadata dictionairy (fo... | 2,886 |
def test_init_airtable(air):
"""Test that Airtable Interface was imported successfully.
"""
assert air | 2,887 |
def ProjectNameToBinding(project_name, tag_value, location=None):
"""Returns the binding name given a project name and tag value.
Requires binding list permission.
Args:
project_name: project name provided, fully qualified resource name
tag_value: tag value to match the binding name to
location: reg... | 2,888 |
def degrees_of_freedom(s1, s2, n1, n2):
"""
Compute the number of degrees of freedom using the Satterhwaite Formula
@param s1 The unbiased sample variance of the first sample
@param s2 The unbiased sample variance of the second sample
@param n1 Thu number of observations in the first sample
@pa... | 2,889 |
async def test_entry_setup_unload(hass, api_factory, gateway_id):
"""Test config entry setup and unload."""
entry = MockConfigEntry(
domain=tradfri.DOMAIN,
data={
tradfri.CONF_HOST: "mock-host",
tradfri.CONF_IDENTITY: "mock-identity",
tradfri.CONF_KEY: "mock-k... | 2,890 |
def get_requires_file(dist):
"""Get the path to the egg-info requires.txt file for a given dist."""
return os.path.join(
os.path.join(dist.location, dist.project_name + ".egg-info"),
"requires.txt",
) | 2,891 |
def get_range_to_list(range_str):
"""
Takes a range string (e.g. 123-125) and return the list
"""
start = int(range_str.split('-')[0])
end = int(range_str.split('-')[1])
if start > end:
print("Your range string is wrong, the start is larger than the end!", range_str)
return range(sta... | 2,892 |
def get_saml_assertion(server, session, access_token, id_token=None):
"""
Exchange access token to saml token to connect to VC
Sample can be found at
https://github.com/vmware/vsphere-automation-sdk-python/blob/master/samples/vsphere/oauth/exchange_access_id_token_for_saml.py
"""
stub_config = S... | 2,893 |
def insert_cluster_metadata(clconn, name, desc, cli, verbose=False):
"""
Insert the cluster metadata information in the SQL table and return its rowid.
This is the information that describes how the clusters were made.
:param clconn: the database connection
:param name: the name of the clustering ap... | 2,894 |
def display_value(id, value):
"""
Display a value in a selector-like style.
Parameters
----------
id: int
Id of the value to be displayed
"""
return html.div(
{
"class": "py-3 pl-3 w-full border-[1px] sm:w-[48%] md:w-[121px] bg-nav rounded-[3px] md:mr-2 my-4 befo... | 2,895 |
def helmholtz_adjoint_double_layer_regular(
test_point, trial_points, test_normal, trial_normals, kernel_parameters
):
"""Helmholtz adjoint double layer for regular kernels."""
wavenumber_real = kernel_parameters[0]
wavenumber_imag = kernel_parameters[1]
npoints = trial_points.shape[1]
dtype = t... | 2,896 |
def compute_vad(wav_rspecifier, feats_wspecifier, opts):
"""This function computes the vad based on ltsv features.
The output is written in the file denoted by feats_wspecifier,
and if the test_plot flaf is set, it produces a plot.
Args:
wav_rspecifier: An ark or scp file as in Kaldi, that contains the i... | 2,897 |
def crt(s):
"""
Solve the system given by x == v (mod k),
where (k, v) goes over all key-value pairs of the dictionary s.
"""
x, n = 0, 1
for q, r in s.items():
x += n * ((r-x) * inverse(n, q) % q)
n *= q
return x | 2,898 |
def create_new_tf_session(**kwargs):
"""Get default session or create one with a given config"""
sess = tf.get_default_session()
if sess is None:
sess = make_session(**kwargs)
sess.__enter__()
assert tf.get_default_session()
return sess | 2,899 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.