content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def piece_together_fourth(Dp, Wp):
"""
Take the skew and symmetric parts of a algorithmic tangent and piece them back together
"""
sym_id = 0.5*(np.einsum('ik,jl', np.eye(3), np.eye(3)) + np.einsum('jk,il', np.eye(3), np.eye(3)))
skew_id = 0.5*(np.einsum('ik,jl', np.eye(3), np.eye(3)) - np.einsum('jk,il', n... | 5,308,300 |
def test_get_name_from_metadata_bad_content_garbage(tmp_path, monkeypatch):
"""The metadata file is broken."""
monkeypatch.chdir(tmp_path)
# put a broken metadata
metadata_file = tmp_path / "metadata.yaml"
with metadata_file.open("wb") as fh:
fh.write(b"\b00\bff -- not a really yaml stuff")... | 5,308,301 |
def to_ragged_seq_set(data):
"""Convert dataset from mapping/array of sequences
to lists of mappings of sequences."""
# data is a dict
if is_mapping(data):
new_data = {}
for name, datum in data.items():
if not is_sequence_set(datum):
# all sequences must at le... | 5,308,302 |
def drawSelectMarkers(image, dragObj):
"""
Draw markers on the dragged rectangle
"""
# Top-Left
cv2.rectangle(image, (dragObj.outRect.x - dragObj.sBlk,
dragObj.outRect.y - dragObj.sBlk),
(dragObj.outRect.x - dragObj.sBlk + dragObj.sBlk * 2,
... | 5,308,303 |
def _SyncConferenceRooms(run_id, start_offset, batch_size):
"""StartRoomsSync work flow implementation.
Args:
run_id: Unique str id representing the workflow.
start_offset: int, zero indexed start offset of the rooms to sync.
batch_size: int number of rooms to fetch at a time starting at start_offset.
... | 5,308,304 |
def get_atoms_list(mmtf_dict):
"""Creates a list of atom dictionaries from a .mmtf dictionary by zipping
together some of its fields.
:param dict mmtf_dict: the .mmtf dictionary to read.
:rtype: ``list``"""
return [{
"x": x, "y": y, "z": z, "alt_loc": a or None, "bvalue": b, "occupancy": o,
... | 5,308,305 |
def register_augmentation(name):
"""Registers an augmentation.
This decorator allows vertview to instantiate an augmentation
from a configuration file. To use it, apply this decorator to an
AugmentationBase2D subclass, like this:
.. code-block:: python
@register_augmentation("my_augmentation")
... | 5,308,306 |
def get_os_fingerprint(data):
"""
Get the most accurate OS fingerprint for the given Data object, if any.
:param data: Data object to query.
:type data: Data
:returns: Most accurate OS fingerprint.
If no fingerprint is found, returns None.
:rtype: OSFingerprint | None
"""
# Ge... | 5,308,307 |
def debug():
"""server debug"""
"""
http://devo.ps/blog/2013/03/06/troubleshooting-5minutes-on-a-yet-unknown-box.html
"""
# TODO: FS read actions last
last()
history()
ps_aux()
free()
uptime()
htop()
lspci()
dmidecode()
netlink()
# IO
iostat()
vmsta... | 5,308,308 |
def ring(symbols, domain, order=lex):
"""Construct a polynomial ring returning ``(ring, x_1, ..., x_n)``.
Parameters
==========
symbols : str, Symbol/Expr or sequence of str, Symbol/Expr (non-empty)
domain : :class:`~diofant.domains.domain.Domain` or coercible
order : :class:`~diofant.polys.po... | 5,308,309 |
def test_bad_parameter():
"""Correct error when given nonexistent parameter name"""
with pytest.raises(Exception):
hapi(server,'dataset1','scalarx') | 5,308,310 |
def trimesh_swap_edge(mesh, u, v, allow_boundary=True):
"""Replace an edge of the mesh by an edge connecting the opposite
vertices of the adjacent faces.
Parameters
----------
mesh : :class:`compas.datastructures.Mesh`
Instance of mesh.
u : int
The key of one of the vertices of ... | 5,308,311 |
def perc_col_nans(col):
"""
Returns the percent of NaNs of a specific column in the dataset.
Parameters:
col (pandas Series): Column in the dataset
Returns:
col_perc_nans (float): Percent of NaNs in col
"""
col_perc_nans = count_col_nans(col) / len(col)
return... | 5,308,312 |
def run_asyncio_serial(callbacks: List[WaveCallback], serial_port: str = None) -> None:
"""Runs an async `consumer-producer` loop using user supplied callbacks for a serial device
Args:
callbacks: A list/tuple of callbacks that handle the data passed from the wave ring
serial_port: The serial p... | 5,308,313 |
def set_up_directory(day):
"""Make a new directory for working on an advent of code problem
Args:
day: int
day of the month to work on
Returns:
new_dir: str
path to the directory for that day
"""
this_dir = os.path.dirname(__file__)
new_dir = os.path.joi... | 5,308,314 |
def get_string(key):
"""
Get localized string. First, try language as set in config. Then, try English locale. Else - raise an exception.
:param key: string name
:return: localized string
"""
lang = strings.get(Config.BOT_LANGUAGE)
if not lang:
if not strings.get("en"):
... | 5,308,315 |
def prompt_vial_range():
"""Prompt user for first and last vial of run"""
first_ic_vial = int(input('First IC vial? '))
last_ic_vial = int(input('Last IC vial? '))
return first_ic_vial, last_ic_vial | 5,308,316 |
def precision_k_curve(y_true, y_pred, max_k=0):
"""
Calculate precision@k for various values of k.
y_true indicates the products that the user actually interacted with. it must be a 'multilabel-indicator'.
If max_k is zero, precision@k is calculated for all values of k from 1 to number of items. Other... | 5,308,317 |
def getFollowupPhotometry(candidate, djangoRawObject = None, conn = None):
"""Use the query followupPhotometryQuery but organise the data for plotting"""
# We need to create a dictionary of filters which contain arrays of the data.
# It's messy to do this from scratch, so defaultdict to the rescue...
f... | 5,308,318 |
def generate_random_map(
size=6, p=0.7, num_pseudo_rewards=0, only_optimal_pseudo_rewards=True
):
"""Generates a random valid map (one that has a path from start to goal)
:param size: size of each side of the grid
:param p: probability that a tile is empty
:param num_pseudo_rewards: number of tiles ... | 5,308,319 |
def approx_count_distinct(col, rsd=None):
"""Returns a new :class:`Column` for approximate distinct count of ``col``.
>>> df.agg(approx_count_distinct(df.age).alias('c')).collect()
[Row(c=2)]
"""
sc = SparkContext._active_spark_context
if rsd is None:
jc = sc._jvm.functions.approx_count... | 5,308,320 |
def VLBAGetSumCC(image, err, CCver=1,
logfile='', check=False, debug=False):
"""
Sum fluxes in a CC table
Sums the flux densities in a CC Table on an image
Returns sum
Returns with err set on error
* image = Image with CC table
* err = Python Obit Error/mes... | 5,308,321 |
def private_mean(x, epsilon, sum_sensitivity):
"""
Computes a private mean with privacy budget epsilon using the given
sensitivity.
:param x: Vector over which the mean will be computed.
:param epsilon: The privacy budget.
:param sum_sensitivity: The sensitivity of the sum calculation.
:ret... | 5,308,322 |
def make_child_dataset(dataobject):
"""Creates a child dataset with the same size as the reference_dataset.
"""
from vtk import vtkImageData
new_child = vtkImageData()
new_child.CopyStructure(dataobject)
input_spacing = dataobject.GetSpacing()
# For a reconstruction we copy the X spacing fro... | 5,308,323 |
def calc_residuals(Amat,Bvec,coeffs,perconf=False):
"""Calculate residuals and other performance metrics"""
residuals = []
matmul = Bvec - Amat*coeffs
residuals = matmul*627.51
r2 = 1-sum(residuals**2)/sum((Bvec*627.51)**2)
rel_MAE = sum(abs(residuals))/sum(abs(Bvec*627.51))
if perconf:
... | 5,308,324 |
def enterNewAnnotation(sql, db, cursor, sentences, textid, annotatorName="parser", notenter=["order"], sentencefeatures={}, tokname="t"):
"""
takes a list of nodedics (sentences) and puts them into the database erasing an existing annotation
sql, db, cursor of open database
sentences: nodedics to enter
textid: t... | 5,308,325 |
def bucket_by_sequence_length(data_reader,
example_length_fn,
bucket_boundaries,
bucket_batch_sizes,
trainer_nums,
trainer_id):
"""Bucket entries in dataset by lengt... | 5,308,326 |
def read_file_quiet(fname=None):
"""This is the main program used for reading in a new circuit. The global file name is stored (f_name)
Sometimes we want to know the initial starting name. The file name can have the .aig extension left off
and it will assume that the .aig extension is implied. This should n... | 5,308,327 |
def delete_delivery_channel(DeliveryChannelName=None):
"""
Deletes the delivery channel.
Before you can delete the delivery channel, you must stop the configuration recorder by using the StopConfigurationRecorder action.
See also: AWS API Documentation
Exceptions
:example: response = ... | 5,308,328 |
def get_overridable_parameters(config: Any) -> Dict[str, param.Parameter]:
"""
Get properties that are not constant, readonly or private (eg: prefixed with an underscore).
:param config: The model configuration
:return: A dictionary of parameter names and their definitions.
"""
assert isinstanc... | 5,308,329 |
def compute_score(sent, sents):
"""Computes the average score of sent vs the other sentences (the result of
sent vs itself isn't counted because it's 1, and that's above
UPPER_BOUND)"""
if not len(sent):
return 0
return sum(compare_sents_bounded(sent, sent1) for sent1 in sents) / float(
... | 5,308,330 |
def get_average_rate(custId, itemId):
""" get avarage rate """ | 5,308,331 |
def computeCentroids(X, idx, K):
"""
returns the new centroids by
computing the means of the data points assigned to each centroid. It is
given a dataset X where each row is a single data point, a vector
idx of centroid assignments (i.e. each entry in range [1..K]) for each
example, and K, the n... | 5,308,332 |
def async_track_time_interval_backoff(hass, action, intervals) -> CALLBACK_TYPE:
"""Add a listener that fires repetitively at every timedelta interval."""
if not iscoroutinefunction:
_LOGGER.error("Action needs to be a coroutine and return True/False")
return
if not isinstance(intervals, (l... | 5,308,333 |
def grr_grep(line):
"""Greps for a given content of a specified file.
Args:
line: A string representing arguments passed to the magic command.
Returns:
A list of buffer references to the matched content.
Raises:
NoClientSelectedError: Client is not selected to perform this operation.
"""
args... | 5,308,334 |
def convertMCFOSTdataToJy(data, wavelength, spatialUnit = 'arcsec', spatialResolution = None):
"""Convert data in MCFOST units into Jansky/pixel or Jansky/arcsec^2:
Input: data: 2D array, MCFOST-generated data.
wavelength: float, wavelength of the data to be converted in micron.
spatial... | 5,308,335 |
def echo_process_results(node):
"""Display a formatted table of the outputs registered for the given process node.
:param node: the `ProcessNode` of a terminated process
"""
from aiida.common.links import LinkType
class_name = node.process_class.__name__
outputs = node.get_outgoing(link_type=(... | 5,308,336 |
def _save_python_script(results_dir, parser):
"""
When using a Python script to run the
diags via the API, dump a copy of the script.
"""
args = parser.view_args()
# If running the legacy way, there's
# nothing to be saved.
if args.parameters:
return
# Get the last argument ... | 5,308,337 |
def defaults(dict=None):
"""
Adds a set of default values to the settings registry. These can and will be updated
by any settings modules in effect, such as the Settings Manager.
If dict is None, it'll return the current defaults.
"""
if dict:
_defaults.update(dict)
else:
re... | 5,308,338 |
def test_g_day_min_inclusive003_1266_g_day_min_inclusive003_1266_v(mode, save_output, output_format):
"""
TEST :Facet Schemas for string : facet=minInclusive and value=- - -01
and document value=- - -15
"""
assert_bindings(
schema="msData/datatypes/Facets/gDay/gDay_minInclusive003.xsd",
... | 5,308,339 |
def test_gdeploy_error(testdir, broken_gdeploy_config, marker_type):
"""
Make sure that test cases ends in ERROR state when ``gdeploy_config``
fixture fails (because of ansible reported error).
"""
# create a temporary pytest test module
testdir.makepyfile(textwrap.dedent("""\
import pyt... | 5,308,340 |
def init(path=None, ipython=None):
"""Initiate noWorkflow extension.
Load D3, IPython magics, and connect to database
Keyword Arguments:
path -- database path (default=current directory)
ipython -- IPython object (default=None)
"""
import os
from .magics import register_magics
try... | 5,308,341 |
def import_col_from_kolibri_channel(col, kolibri_tree, options):
"""
Load the data contained in `kolibri_tree` (JSON) into the collection `col`.
Nodes that already exist will be updated
"""
print('in import_col_from_kolibri_channel', col.name, 'titled', col.title)
# 1. Set content collection at... | 5,308,342 |
def send_email(email_subject, recipient, message, config = None):
"""Send an email using SendGrid."""
try:
config = current_app.config
except:
config = config
sender = sendgrid.SendGridClient(config['SENDGRID_API_KEY'])
email = sendgrid.Mail()
email.set_subject(email_subjec... | 5,308,343 |
def redirect_stdout(func):
"""temporarily redirect stdout to new Unicode output stream"""
@wraps(func)
def wrapper(*args, **kwargs):
original_stdout = sys.stdout
out = StringIO()
try:
sys.stdout = out
return func(out, *args, **kwargs)
finally:
... | 5,308,344 |
def simulate_request(app, method='GET', path='/', query_string=None,
headers=None, content_type=None, body=None, json=None,
file_wrapper=None, wsgierrors=None, params=None,
params_csv=False, protocol='http', host=helpers.DEFAULT_HOST,
r... | 5,308,345 |
def rcnn_encode(bboxes, targets):
"""
:param bboxes: (N, 4) bounding boxes of [x0, y0, x1, y1]
:param targets: (N, 4) target ground truth boxes of [x0, y0, x1, y1]
:return: deltas
"""
bw = bboxes[:, 2] - bboxes[:, 0] + 1.0
bh = bboxes[:, 3] - bboxes[:, 1] + 1.0
bx = bboxes[:, 0] + 0.5 *... | 5,308,346 |
def argparse_setup():
"""Initialize the argument parser.
Parameters:
None
Return:
None
"""
parser = argparse.ArgumentParser()
subparsers = parser.add_subparsers()
# Subparser for implementation listing
info_parser = subparsers.add_parser("info",
... | 5,308,347 |
def is_alloc_promotable(alloc_inst: ir.Alloc):
""" Check if alloc value is only used by load and store operations. """
assert isinstance(alloc_inst, ir.Alloc)
if len(alloc_inst.used_by) != 1:
return False
addr_inst = list(alloc_inst.used_by)[0]
if not isinstance(addr_inst, ir.AddressOf):
... | 5,308,348 |
def mera_ansatz_parameters(num_qubits, depth, value):
"""Returns a Parameters object for the MERA Tensor network ansatz.
Args:
num_qubits : int
Number of qubits in the parameterized circuit.
depth : int [must equal log2(num_qubits)]
Number of "hyperlayers" in MERA netwo... | 5,308,349 |
def gaussianfilter(N, alpha, Ts, Fs):
"""
Generates a gaussian filter (FIR) impulse response.
Parameters
----------
N : int
Length of the filter in samples.
alpha: float
Roll off factor (Valid values are [0, 1]).
Ts : float
Symbol period in seconds.
... | 5,308,350 |
def assert_array(arr: Array, ndim: int, size: int, # pylint: disable=R0913
lower_bound: float = -np.inf,
upper_bound: float = np.inf,
name: str = 'arr'):
"""Raise an error if shape of `arr` does not match given arguments.
Args:
arr: Array to tes... | 5,308,351 |
def minimal_copy(ds: Dataset) -> Dataset:
"""Make reduced copy with only the attributes needed for a QueryResult"""
res = Dataset()
for attr in chain.from_iterable(chain(req_elems.values(), opt_elems.values())):
val = getattr(ds, attr, None)
if val is not None:
setattr(res, attr,... | 5,308,352 |
def test_main_two_args():
"""
If there are two arguments passed into main, then it should pass them onto
the flash() function.
"""
with mock.patch('uflash.flash', return_value=None) as mock_flash:
uflash.main(argv=['foo.py', '/media/foo/bar'])
mock_flash.assert_called_once_with(
... | 5,308,353 |
def restore_knowledge_bank(config: de_config_pb2.DynamicEmbeddingConfig,
var_name: Text,
saved_path: Text,
service_address: Text = '',
timeout_ms: int = -1) -> None:
"""Restores knowledge bank data (`config`, `... | 5,308,354 |
def read_txt_embeddings(logger, path):
"""
Reload pretrained embeddings from a text file.
"""
import numpy as np
word2id = {}
vectors = []
# load pretrained embeddings
# _emb_dim_file = params.emb_dim
_emb_dim_file = 0
with io.open(path, 'r', encoding='utf-8', newline='\n', errors='ignore') as f:
... | 5,308,355 |
def corrected_chance(clustering1, clustering2, measure='jaccard_index',
random_model='perm', norm_type='sum', n_samples=100):
"""
This function calculates the adjusted Similarity for one of six random
models.
.. note:: Clustering 2 is considered the gold-standard clustering for one... | 5,308,356 |
def update_account():
"""Update account settings."""
form = AccountSettingsForm(request.form)
if form.validate():
if 'user_id' not in request.form:
return jsonify({'success': False,
'error': 'ID not found in edit!'})
edit_id = paranoid_clean(request.fo... | 5,308,357 |
def make_weighted_loss(loss_fn, weight=1.0):
""" Adapts the given loss function by multiplying by a given constant.
Parameters
----------
loss_fn: a function to create the loss
weight: the value by which to weigh the loss.
Returns
-------
fn: The adapted loss
"""
def fn(*args, ... | 5,308,358 |
def create_differences_matrix(rows, cols):
"""
Creates the central differences matrix A for an n by m shaped grid
"""
n = rows*cols
M = np.zeros((n,n))
for r in range(rows):
for c in range(cols):
i = r*cols + c
# Two inner diagonals
if c > 0: M[i-1,i] ... | 5,308,359 |
def isvalid_corr(corrmat):
"""
Check if
1. corrmat is symmetric
2. off-diagonal values in [-1, 1]
3. diagonal values = 1
4. the matrix is positive semidefinite.
@param corrmat: numpy nxn ndarray
@return: CorrDiagnostics object ---> evaluates to True if corrmat is valid and False otherwi... | 5,308,360 |
def multi_JMI(X, y, is_disc, cost_vec, cost_param_vec,
num_features_to_select = None, random_seed = 123, num_cores = 1):
""" Cost-based JMI feature ranking with multiple penalization parameters.
Function to obtain the rankings associated to different cost parameters,
with the filter featu... | 5,308,361 |
def sparse_to_adjlist(sp_matrix, filename):
"""
Transfer sparse matrix to adjacency list
:param sp_matrix: the sparse matrix
:param filename: the filename of adjlist
"""
# add self loop
homo_adj = sp_matrix + sp.eye(sp_matrix.shape[0])
# create adj_list
adj_lists = defaultdict(set)
... | 5,308,362 |
def _load_seg(parent, filename=None, image=None, image_file=None):
""" load *_seg.npy with filename; if None, open QFileDialog """
if filename is None:
name = QFileDialog.getOpenFileName(
parent, "Load labelled data", filter="*.npy"
)
filename = name[0]
try:
d... | 5,308,363 |
async def websocket_connected(websocket):
"""
Sends a `success` message to the websocket client
on connect.
"""
websocket.send_str(
json.dumps({"subject": Subject.websocket.value, "event": Event.connected.value})
)
logger.info(
"new authenticated connection, user: %s",
... | 5,308,364 |
def arcsin(x):
"""
Compute the inverse sine of x.
Return the "principal value" (for a description of this, see
`numpy.arcsin`) of the inverse sine of `x`. For real `x` such that
`abs(x) <= 1`, this is a real number in the closed interval
:math:`[-\\pi/2, \\pi/2]`. Otherwise, the complex princi... | 5,308,365 |
def _dihedral_types_from_gmso(top, structure, dihedral_map):
"""Helper function to convert Topology DihedralType to Structure DihedralType
This function will first check the DihedralType expression of Topology and
make sure it match with the one default in Parmed.
After that, it would start atomtyping ... | 5,308,366 |
def run_queued(fn, params, processes=1, queued_params=None, logging_level=None):
"""
Same as run_function, but the function should be such that it accepts a
parameter queue and reads its inputs from there; params still contains
options for the function.
If logging_level is not None, a QueueHandler ... | 5,308,367 |
def ExtractFrequencyTime(data, bands):
"""Computes the spectrogram of data, and the takes the sum of frequencies inside the band range.
"""
bands_results = {'all_spec':[], 'alpha':[], 'beta1':[], 'beta2':[], 'beta3':[]}
f, t, Sxx = signal.spectrogram(data,window = 'hamming', fs = 500,nperseg = 256, no... | 5,308,368 |
def ensure_list(data: Any) -> List:
"""Ensure input is a list.
Parameters
----------
data: object
Returns
-------
list
"""
if data is None:
return []
if not isinstance(data, (list, tuple)):
return [data]
return list(data) | 5,308,369 |
def _inform_newer_version(force_check=False) -> None:
"""
Compares installed SAM CLI version with the up to date version from PyPi,
and print information if up to date version is different then what is installed now
It will store last version check time into GlobalConfig, so that it won't be running al... | 5,308,370 |
def decode_logistic_mixture(
targets, means, log_scales, logit_probs_softmax, # CDF
input_string):
"""
NOTE: This function uses either the CUDA or CPU backend, depending on the device of the input tensors.
NOTE: targets, means, log_scales, logit_probs_softmax must all be on the same device ... | 5,308,371 |
def _match_up_provided_args_with_field_defs(field_defs, args, kwargs):
"""
Returns a list of provided values, aligned with the field definitions. Missing values are represented using the NVP
(No Value Provided) token (as None can be a valid provided value).
"""
values = [NVP] * len(field_defs)
... | 5,308,372 |
def var_recode(TEDS_A_Imputed, user_target, TEDS_Af):
"""Recodes categorical variables present in the data.
Returns
A recoded data frame."""
# Identify the variable types
col_list = list(TEDS_A_Imputed.columns)
col_list_cat = [s for s in col_list if s != 'CASEID' and s != 'ADMY... | 5,308,373 |
def get_cannonical(group):
"""
For each variant, that is unique combination of #CHROM, POS, REF, ALT, it keeps CANONICAL transcript annotations.
If more than consequence type is annotated, it keeps the most damaging or severe either if there is more than one
entry (row) per variant or either is coma-sep... | 5,308,374 |
def get(blob_key):
"""Gets a `BlobInfo` record from blobstore.
Does the same as `BlobInfo.get`.
Args:
blob_key: The `BlobKey` of the record you want to retrieve.
Returns:
A `BlobInfo` instance that is associated with the provided key or a list
of `BlobInfo` instances if a list of keys was pro... | 5,308,375 |
def go_struct_variables(variables: List[Dict]) -> str:
"""Generate Go code containing struct field definitions."""
lines = []
for var in variables:
if var["description"]:
description = (
var["description"]
.replace("e.g. ", "e.g.")
.replace... | 5,308,376 |
def init_split(df, featname, init_bins=100):
"""
对df下的featname特征进行分割, 最后返回中间的分割点刻度
为了保证所有值都有对应的区间, 取两个值之间的中值作为分割刻度
注意这里的分割方式不是等频等常用的方法, 仅仅是简单地找出分割点再进行融合最终进行分割
注意, 分出的箱刻度与是否闭区间无关, 这个点取决于用户,这个函数仅考虑分箱的个数
同时, 分箱多余的部分会进入最后一个箱, 如101个分100箱, 则最后一个箱有两个样本
Parameters:
----------
df: dataframe,... | 5,308,377 |
def read_image(point_file):
"""Read the corresponding image."""
head, tail = os.path.split(point_file)
image_file = tail.split('.')[-2]
img_jpg = os.path.join(head, image_file + ".jpg")
img_png = os.path.join(head, image_file + ".png")
if os.path.exists(img_jpg):
img = cv2.imread(img_jpg... | 5,308,378 |
def dist_of_entity_k(adjacency_dict: dict, levels_dict: dict, c_k: dict, c_notk: dict) -> int:
"""
Performs the final iterations of the algorithm proposed in the Alternative Geographic Spine document to find
the "off spine entity distance" (OSED), which is the number of geounits that must be added or subtra... | 5,308,379 |
def repr_content_and_tags(text_widget: tkinter.Text) -> str:
"""Represent the content, indices and the tag starts and ends as a text table."""
tbl = prettytable.PrettyTable()
tbl.field_names = ["Index", "Char", "Tag starts", "Tag ends"]
for index, character, tag_starts, tag_ends in enumerate_with_inde... | 5,308,380 |
def build_dataset_reduce_fn(
simulation_flag: bool = True
) -> Callable[[_ReduceFnCallable, Union[tf.data.Dataset, Iterable]], tf.Tensor]: # pylint: disable=g-bare-generic
# TODO(b/162683412): remove `Iterable` after pytype fix.
"""Retruns a reduce loop function on input dataset."""
if simulation_flag:
r... | 5,308,381 |
def isotropic_twirl_state(X, d):
"""
Applies the twirling channel
X -> ∫ (U ⊗ conj(U))*X*(U ⊗ conj(U)).H dU
to the input operator X acting on two d-dimensional systems.
For d=2, this is equivalent to
X -> (1/24)*sum_i (c_i ⊗ conj(c_i))*X*(c_i ⊗ conj(c_i)).H
where the unitaries c... | 5,308,382 |
def flatten_index(builder, index, const_shape):
"""Converts N-dimensional index into 1-dimensional one.
index is of a form ``(i0, i1, ... iN)``, where *i* is ValueRefs
holding individual dimension indices.
First dimension is considered to be variable. Given array shape
``(d0, d1, ... dN)``, *const... | 5,308,383 |
def init_conds(MdiscI, P):
"""
Function to convert a disc mass from solar masses to grams and an initial spin
period in milliseconds into an angular frequency.
:param MdiscI: disc mass - solar masses
:param P: initial spin period - milliseconds
:return: an array containing the disc mass in grams and th... | 5,308,384 |
def fetch_feed() -> list[RenjiData]:
"""
Get news feed from renji.com
"""
logger.info("Start fetching info from renji.com ...")
res = urlopen("https://www.renji.com/default.php?mod=article&fid=38")
logger.info("Info fetched. Parsing ...")
soup = BeautifulSoup(res.read(), 'lxml')
datas =... | 5,308,385 |
def _assert_sframe_equal(sf1,
sf2,
check_column_names=True,
check_column_order=True,
check_row_order=True,
float_column_delta=None):
"""
Assert the two SFrames are equal.
The default... | 5,308,386 |
def get_me_ssh_key(key_name: Optional[str] = None,
opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetMeSSHKeyResult:
"""
Use this data source to retrieve information about an SSH key.
## Example Usage
```python
import pulumi
import pulumi_ovh as ovh
mykey = ov... | 5,308,387 |
def gower_distance_numpy(point1, point2, max_range):
"""!
@brief Calculate Gower distance between two vectors using numpy.
@param[in] point1 (array_like): The first vector.
@param[in] point2 (array_like): The second vector.
@param[in] max_range (array_like): Max range in each data dimension.
... | 5,308,388 |
def test_invalid_bounds():
"""Test that invalid bounds throw the appropriate error."""
with pytest.raises(ValueError):
SampleAttributeTemplate(name="name") # Must have a bounds
with pytest.raises(TypeError):
SampleAttributeTemplate(name="name", bounds=UniformReal(0, 1, '')) | 5,308,389 |
def is_fix_only_distro(distro_name: str) -> bool:
"""
Does the given distro's security feed/db support vulnerability records before a fix is available?
:param distro_name:
:return: bool
"""
return distro_name in FIX_ONLY_DISTROS | 5,308,390 |
def step_f(z: np.ndarray, scale: float, loc: float) -> np.ndarray:
"""
:param z: z-dimension
:param scale: width of step function, always 0
:param loc: position of step
:return: positioned step function
"""
new_z = z - loc
f = np.ones_like(new_z) * 0.5
f[new_z <= -scale] = 0
... | 5,308,391 |
def build_SVM(X_train, y_train, kernel_):
"""
The function builds SVM
"""
scaler = StandardScaler()
X_train_std = scaler.fit_transform(X_train)
""" for i in range(1, 5):
svc = SVC(kernel=kernel_, random_state=0, gamma=i)
model = svc.fit(X_train_std, y_train.values.ravel())
... | 5,308,392 |
def status(args: tuple[str]) -> list[res.Response]:
"""Batch `git status` command."""
return _call_git_use_case("status", args) | 5,308,393 |
def get_worker(project, object_id=None, global_id=None, user_id=None):
""" Gets the identified worker. Exactly one form of identification should be provided.
:param project:
:param object_id: The worker's OBJECTID.
:param global_id: The worker's GlobalID.
:param user_id: The worker'... | 5,308,394 |
def xml_to_string(elem, pretty=False):
"""
Returns a string from an xml tree.
"""
try:
if elem is not None:
if PY2:
xml_str = ElementTree.tostring(elem, encoding='utf-8')
else:
xml_str = ElementTree.tostring(elem, encoding='unicode')
... | 5,308,395 |
def add_volatile_sources(table_collection, nodes):
"""
Parameters
----------
table_collection
nodes
Returns
-------
"""
logging.debug("Add volatile sources to nodes dictionary.")
vs = table_collection["volatile plants"]
for region in vs.index.get_level_values(0).unique():... | 5,308,396 |
def build_config(
config_file: str,
task_cls: Type[GeneralizedRCNNTask],
opts: Optional[List[str]] = None,
) -> CfgNode:
"""Build config node from config file
Args:
config_file: Path to a D2go config file
output_dir: When given, this will override the OUTPUT_DIR in the config
... | 5,308,397 |
def exception(msg, *args, exc_info=True, **kwargs):
"""Log a message with severity 'ERROR' on the root logger, with exception
information.
"""
error(msg, *args, exc_info=exc_info, **kwargs) | 5,308,398 |
def flatten_list(nested_list):
"""
Flatten an arbitrarily nested list, without recursion (to avoid
stack overflows). Returns a new list, the original list is unchanged.
Example:
>> list(flatten_list([1, 2, 3, [4], [], [[[[[[[[[5]]]]]]]]]]))
[1, 2, 3, 4, 5]
>> list(flatten_list([... | 5,308,399 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.