content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def kmeanspp(matrix, k, *, msr=2, prior=0., seed=0, ntimes=1, lspp=0, expskips=0, n_local_trials=1, weights=None):
"""
Compute kmeans++ over the input matrix for given parameters.
Inputs:
Input matrix: sp.csr_matrix, minicore.CSparseMatrix, or numpy.ndarray
Second argument (k=) can... | 9728889b7a27412963685253d4c40b98235d3863 | 3,617,300 |
def find_constant_lengths(feature, tol=1e-6):
"""
Find lengths of all constant periods in feature data.
Parameters
----------
feature: Numpy array (shape: N)
Vector with feature data for all time
tol: Float (default=1e-2)
What scale factor is applied to variance to determine va... | deed394a7be9a33a8a1dbeedaeb5a52ee7a17f47 | 3,617,301 |
def endpoint_from_flag(flag):
"""The object used for interacting with relations tied to a flag, or None.
"""
relation_name = None
value = _get_flag_value(flag)
if isinstance(value, dict) and 'relation' in value:
# old-style RelationBase
relation_name = value['relation']
elif flag... | 6b48e9b4307f04a99067397e931ec65f4a73f10b | 3,617,302 |
import signal
def eliminate_stim_artifact(raw, events, event_id, tmin=-0.005,
tmax=0.01, mode='linear'):
"""Eliminates stimulations artifacts from raw data
The raw object will be modified in place (no copy)
Parameters
----------
raw : Raw object
raw data objec... | b10a7f61ce186b4d2bd6100980accd489905be9c | 3,617,303 |
import torch
def fast_nms(multi_bboxes,
multi_scores,
multi_coeffs,
score_thr,
iou_thr,
top_k,
max_num=-1):
"""Fast NMS in `YOLACT <https://arxiv.org/abs/1904.02689>`_.
Fast NMS allows already-removed detections to suppress other d... | f9f027fdb3ff09dc2ffa76689e5ca2107d595eb6 | 3,617,304 |
import os
def get_abs_path(in_path):
"""
Given a relative or absolute path, return the absolute path.
:param in_path:
:return:
"""
if os.path.isabs(in_path):
return in_path
else:
return os.path.abspath(in_path) | 6d732d563bef61dbde058110addc5fa91fea4a5d | 3,617,305 |
def is_(a: object, b: object) -> bool:
"""
Return `a is b`, for _a_ and _b_.
Example:
>>> is_(object())(object())
False
Args:
a: left element of is expression
b: right element of is expression
Return:
`True` if `a is b`, `False` otherwise
"""
return... | 6edda9af046f6a45f37578c073ed0e21e3320778 | 3,617,306 |
def recurse_sigfig(per_offset_data, num_digits):
"""
Recurse through a dictionary of offset data. Any impacts to ecosystem
services will be rounded to `num_digits` significant figures.
Parameters:
per_offset_data(dict): A dictionary of values, mapping string parcel
IDs to dictionar... | 765168e2e99d8c7dc5742f7db7ff4548e69c46c7 | 3,617,307 |
def generate_vpt_title(radar, field):
"""
Generate a title for a VPT plot.
Parameters
----------
radar : Radar
Radar structure.
field : str
Field plotted.
Returns
-------
title : str
Plot title.
"""
time_str = generate_radar_time_begin(radar).isofor... | bac41da795a261a17a6a543df3a53897a636722e | 3,617,308 |
from typing import Optional
def get_event_bus_policy(id: Optional[str] = None,
opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetEventBusPolicyResult:
"""
Resource Type definition for AWS::Events::EventBusPolicy
"""
__args__ = dict()
__args__['id'] = id
if op... | 91e6c4d701a86197fab77bb9143498999ddf84bb | 3,617,309 |
import logging
import os
import sys
def get_logger(name, path, fname):
"""create a logger and return
"""
logger = logging.getLogger(name)
file_log_handler = logging.FileHandler(os.path.join(path, fname))
stderr_log_handler = logging.StreamHandler(sys.stdout)
logger.addHandler(file_log_handler... | 4f2b99074944b73e4d4f43620f2f0d933a845dbf | 3,617,310 |
def scan_list(request):
"""
The function listing all ZAP Web scans.
:param request:
:return:
"""
all_scans = zap_scans_db.objects.filter(rescan='No')
rescan_all_scans = zap_scans_db.objects.filter(rescan='Yes')
return render(request,
'scan_list.html',
... | 0fa7745879031e45c8ad02b6e0bc60d36d543847 | 3,617,311 |
def _set_default_contact_rating(contact_rating_id: int, type_id: int) -> int:
"""Set the default contact rating for mechanical relays.
:param contact_form_id: the current contact rating ID.
:param type_id: the type ID of the relay with missing defaults.
:return: _contact_rating_id
:rtype: int
"... | e39f5f9701d4314cd19109ce08c599b3737cd064 | 3,617,312 |
def get_vector_info(vector_path, layer_id=0):
"""Get information about an GDAL vector.
Args:
vector_path (str): a path to a GDAL vector.
layer_id (str/int): name or index of underlying layer to analyze.
Defaults to 0.
Raises:
ValueError if ``vector_path`` does not exist... | adaf6eac80a6d816ef306d5a546494d2e7462b07 | 3,617,313 |
def create_report(user_options: UserOptions) -> Report:
"""
Analyse whether a Python package follows a set of contracts, returning a report on the results.
Raises:
InvalidUserOptions: if the report could not be run due to invalid user configuration,
such as a module that... | e2d4912100fdbca8e3f6e5b252bf68ca6d6156dd | 3,617,314 |
def calc_rms(data, channel, num_channels, num_samples_per_channel):
""" Calculate RMS value from a block of samples. """
value = 0.0
index = channel
for _i in range(num_samples_per_channel):
value += (data[index] * data[index]) / num_samples_per_channel
index += num_channels
return ... | ee5a8e00aed046dffc552a89253edf9c49f5857c | 3,617,315 |
import json
def _read_color_map(path, object_hook=None):
"""
Read a color map as json.
:param path (str): The path to read the map from.
:param object_hook (func): A Function to manipulate the json.
:return: A dictionary of color map.
"""
with open(path) as f:
return json.load(f, o... | 34c627443cd418d84b19bd54b3e79427d8168b1e | 3,617,316 |
def train_forward_parameters(args, net, predictions, targets, loss_function,
forward_optimizer):
""" Train the forward parameters on the current mini-batch."""
if predictions.requires_grad == False:
# we need the gradient of the loss with respect to the network
# out... | c0376e8ddc059864700ffe68492dc8b6226aac66 | 3,617,317 |
def device_of_devicendarray(devicendarray):
"""
Returns the device that backs memory allocated on the given
deviceNDArray
:param devicendarray: devicendarray array to check
:return: int device id
"""
dev = device_of_gpu_matrix(devicendarray)
return get_visible_devices()[dev] | bf2ba4c54dd0bcd5e51561cfdae35aebf3a6ff33 | 3,617,318 |
def create_warehouse() -> Warehouse:
"""Create a ware house."""
warehouse_yml = create_warehouse_yml()
warehouse = Warehouse(warehouse_yml)
return warehouse | 6bcbca3d4d08bca628525f0bd6f53f26b8932b26 | 3,617,319 |
def transformer(model: str = 'xlnet', **kwargs):
"""
Load Transformer emotion model.
Parameters
----------
model : str, optional (default='bert')
Model architecture supported. Allowed values:
* ``'bert'`` - BERT architecture from google.
* ``'tiny-bert'`` - BERT architectur... | 10b59175bba04dec90aa21554246349d05f50adc | 3,617,320 |
import asyncio
async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
"""Unload a config entry."""
unload = await hass.config_entries.async_unload_platforms(entry, PLATFORMS)
await asyncio.gather(
*[
hass.async_add_executor_job(gateway.websocket_disconnect)
... | f6c7ccdace7f2f7d6d53a0aadcc4e591df0ac4c9 | 3,617,321 |
def convertd2b(amount, x_pow, y_pow):
"""Apply the equation to get the result. Decimal to binary."""
res = amount * (10 ** x_pow / 2 ** y_pow)
return res | 8a6c7ca98a351b9a6f6c499954f7d8a533559122 | 3,617,322 |
def revtranslate(aa, dna, check=False):
"""Reverse translates aminoacids (with gaps) into DNA
Must supply original ungapped DNA.
"""
# trim stop codon
#if aa[-1] in "*X" and CODON_TABLE.get(dna[-3:], "") == "*":
# aa = aa[:-3]
# dna = dna[:-3]
a = len(aa.replace("-", "")) * 3... | 6de38c790fde63abaf27dcf632b81ef976ee66a0 | 3,617,323 |
def plot_season_avg(
poll_df,
pollutant,
ax,
plot_error=True,
roll=True,
agg='max',
color='blue',
linestyle='solid',
linewidth=2, label=None, offset=182, draw=True, ci=95):
"""Plot the average by date of year. Good for looking seasonal pattern.... | f00eed1f793d65f8acdaea9c64c8ff3a38596dcb | 3,617,324 |
def task_3_list_customers_in_germany(cur) -> list:
"""
List the customers in Germany
Args:
cur: psycopg cursor
Returns: 11 records
"""
cur.execute("""SELECT * FROM Customers WHERE country='Germany'""")
return cur.fetchall() | bf6465cc590cfe7d45817eff02e0dbaacb02e195 | 3,617,325 |
def split_numpy_array(array, portion=None, size=None, shuffle=True):
"""Split NumPy array into two halves, by portion or by size.
Parameters
----------
array : np.ndarray
A NumPy array to be splitted.
portion : float
Portion of the second half. Ignored if `size` is specified.
... | 3914131e3cfd4afe6292a6f401be0040a6aedb59 | 3,617,326 |
def two_agents_three_actions() -> MACID:
"""This macim is a representation of a
game where two players must decide between
threee different actions simultaneously
- the row player is agent 1 and the
column player is agent 2 - the normal form
representation of the payoffs is as follows:
+... | 04de1be6c09d26afe829c9b34a275fcdc9290cc0 | 3,617,327 |
def volume_unit_to_litres(symbol):
"""Convenience function that returns the factor one must multiply to convert a physical quantity with the specified
unit of volume into litres."""
return volume_units.get_scale_factor(symbol) | fafb42a085392cbf0a073e847718c2f2d5cc3410 | 3,617,328 |
def state_task_result_update(task_result, task_result_reason, task_work_result,
task_work_result_reason):
"""
Update State Task Result given a state task work result
"""
if STATE_TASK_WORK_RESULT.WAIT == task_result:
# Nothing to update
return task_result, ta... | d22424788d0488f7352f63f3e41f41149b8e62a8 | 3,617,329 |
def im_detect(net, im, _t, idx):
"""Detect object classes in an image given object proposals.
Arguments:
net (caffe.Net): Fast R-CNN network to use
im (ndarray): color image to test (in BGR order)
boxes (ndarray): R x 4 array of object proposals or None (for RPN)
Returns:
s... | fcca9d2548e1a52f7cf9049913d9beb64ccf9feb | 3,617,330 |
def find_page(pages, limit, value):
"""
Function to calculate and return the current page of a paginated result.
:param pages:
:param limit:
:param value:
:return:
"""
page_range = [limit * page for page in range(1, pages + 1)]
for index, my_range in enumerate(page_range):
if... | d1b97fb0c6c54c85b748922fb6df3d96121ea3c7 | 3,617,331 |
def get_gcloud_config_value(monkeypatch):
"""Returns predictable gcloud config values for testing.
Args:
monkeypatch: Fixture helper.
"""
def get_gcloud_config_value_for_tests(key, default=None):
"""Returns predictable gcloud config values for testing.
Args:
key: Config key to retrieve, e.g.... | 77eb1734a2cf459d7235fecfeefb665b311509dc | 3,617,332 |
def dict_to_str(d):
"""Represent dictionary as string.
Represents a dictionary as a string. This is useful when
a representation for a filename is desired. The function
will unroll all keys and join their parameters with '_',
yielding a single string for the dictionary.
Parameters
--------... | 4279cbc08dde9ef4e513cd562c66f63f09c866fa | 3,617,333 |
def compare(guess, answer):
"""
Compare guess and answer
Arguments:
guess -- a 4-digital number string of the guess.
answer -- a 4-digital number string of right answer.
Returns:
cow -- a number of the user guessed correctly in the correct place.
bull -- a number of the user gu... | f615f4ebd555c0c4119d0fcbf9ae581146fe7816 | 3,617,334 |
def discordance(CRITERIA, ACTIONS, PERFORMANCES, THRESHOLDS, CATEGORIES):
"""
Calculates the discordance matrix for a given reference profile.
:param CRITERIA: List containing the names of the criteria as strings.
:param ACTIONS: List containing the names of the actions as strings.
:param PERFORM... | 301977c3ef0089c55be12e534253fc4ed5a9aabb | 3,617,335 |
def mkid():
"""Generates a uuid4 (Example: 'f50ec0b7-f960-400d-91f0-c42a6d44e3d0') using the Python
uuid module
Returns:
string: a unique universal ID of type 4. (Example: 'f50ec0b7-f960-400d-91f0-c42a6d44e3d0')
"""
return str(uuid4()) | 8c65dd190f1837b967a2ab4edcfe101749e94668 | 3,617,336 |
def colinterp(a, x):
"""Interpolates colors"""
l = len(a) - 1
i = min(l, max(0, int(x * l)))
(u, v) = a[i:i + 2, :]
return u - (u - v) * ((x * l) % 1.0) | 6e1ad7b020d2aaf58f95129551fd720c20f751ef | 3,617,337 |
import time
def neural_network_2_layers(X, Y, n_1, num_iterations=10, learning_rate=0.01,
early_stop_cost=0., msg_interval=1, print_interval=100):
"""
X: [n_x, m] train data set
Y: [n_y, m] n_y=1 in this case
n_1: first hidden layer dimension
num_i... | 3bf4db64778e142d4503b5d15097c5ea1320607b | 3,617,338 |
def _get_parent_node_by_pred(node, pred, search_current=False):
"""Find the first parent node that satisfies a predicate function."""
if not search_current:
node = node.parent
while node is not None:
if pred(node):
return node
node = node.parent
return None | a69be92c468758ea1faf366c2881588e8f6fd688 | 3,617,339 |
def hdf5_read(f,h,p):
"""Main driver for reading HDF5 files"""
if h.reading == 'metallicity':
arr = hdf5_readmetals(f,h,p)
elif h.reading == 'metalarray':
arr = hdf5_readmetals(f,h,p,single=0)
elif h.reading == 'mass':
arr = hdf5_readmass(f,h,p)
else:
arr = hdf5_gener... | be649e18ce086e4dcf2ca045d601350ce87956d8 | 3,617,340 |
def scale_0to1(image_in,
exclude_outliers_below=False,
exclude_outliers_above=False
, multiply_factor=1.0):
"""Scale the two images to [0, 1] based on min/max."""
# making a copy to ensure no side-effects
out_image = image_in.copy()
min_value = np.percentil... | 0ed0b373eb134e69cb0be4d4f7d631281b5ab141 | 3,617,341 |
def xmlvalue(self, value):
"""Patch for xmlvalue"""
if value.startswith(FILETAG):
return value
return b64encode(value) | 80a270f3045a260a7bc33155d8108974dc81fa01 | 3,617,342 |
def can_write(path):
"""Test ability to write a file in 'path'.
Assume the path is a temporary directory, so don't bother cleaning up.
"""
if not path.exists():
_log.debug(f"can_write: Creating parent directory '{path}'")
try:
path.mkdir()
except Exception as err:
... | 2f3c99519b4211387ac52fe83cda108cb4803b4f | 3,617,343 |
def print_device_info(nodemap):
"""
This function prints the device information of the camera from the transport
layer; please see NodeMapInfo example for more in-depth comments on printing
device information from the nodemap.
:param nodemap: Transport layer device nodemap.
:type nodemap: INode... | ad091059edfffa5e8fcd5207e95d0d3752c8ab93 | 3,617,344 |
def compute_roc_from_sparse_glm_smpls(data, x_smpls):
""" Compute the ROC curve given samples from a sparse weighted model
We can estimate p(A_{k,k'} | data) from our samples
"""
# Compute the inferred connectivity matrix
p_A = np.zeros_like(x_smpls[0]['net']['graph']['A'])
for smpl in x_smp... | 1dedd9fc312368d549da7c724c347a9ff1b56ee1 | 3,617,345 |
def column_check(lst):
"""
Function check's whether columns have right numbers, according to the given rows
>>> column_check(['***', ' * 1', '123', '111'])
False
"""
var1 = rebuilding(lst)
var2 = number_row_check(var1)
if var2 is True:
return True
return False | 076481e5d3758f411828af7f44740d6fa37fbf92 | 3,617,346 |
def accuracy(W, x, t):
"""computes the accuracy of the model with the weights W (shape (dim_phi, N_classes))
for a test set x (shape (N_examples, dim_x)) and t (shape (N_examples, K_classes)).
"""
phi = features(x)
y = activity(W, phi)
correct = np.equal(np.argmax(y, axis=1), np.argmax(t, axis=... | 05bab6c93d63c3c199ac4ef74af60232665eb62c | 3,617,347 |
def plot_gottselig(n, datatype='calcs'):
""" plot gottselig normalization for all channels
Parameters
----------
datatype: str (default: 'calcs')
which data to plot [options: 'calcs', 'normed_pwr']
"""
exclude = ['EKG', 'EOG_L', 'EOG_R']
eeg_chans = [x for ... | 867ca393deb4d889290e01eea29d60c90baf263c | 3,617,348 |
def find_val_in_lid_shotlog(shotno):
"""
seigyo.lid_shotlog から対応するショット番号のlidデータを取得する。
LID計算機とのファイル共有の問題が解決されないままとなっているため、現状ではデータを取得できない。
しばらく舟場データを使用する)2013.10.21
Parameters
----------
shotno : int
shot number
Returns
-------
dict
"""
vals = {}
db = get_conn... | 2886f804f89f5808e18afd2439768fed0b381d05 | 3,617,349 |
def SB_oxy_eq(coef,oxyvolts,pressure,temp,dvdt,os,cc=[1.92634e-4,-4.64803e-2]):
"""
Oxygen (ml/l) = Soc * (V + Voffset) * (1.0 + A * T + B * T^2 + C * T^3 ) * OxSol(T,S) * exp(E * P / K)
Original equation from calib sheet dated 2014:
coef[0] = Soc
coef[1] = Voffset
coef[2] = A
coef[3] = B
... | a5db733c9aad88a53c3287c93d9fa66af1c7944e | 3,617,350 |
def make_pipeline_short(pipeline_type):
"""Make a short pipeline."""
pipeline = pipeline_type(
ChunkedStreamLink(),
EventLink(),
)
assert isinstance(pipeline.bottom, ChunkedStreamLink)
assert isinstance(pipeline.top, EventLink)
return pipeline | dbfef9d6fa2bb2f15b2cb48fc4b07d2b9dbfcb49 | 3,617,351 |
import os
def find_best_weight(w_path: str, best: str = "min", ext: str = ".hdf5", epoch_identifier: int = None):
"""Given weights in w_path, find the best weight.
if epoch_identifier is given, it will be given priority to find best_weights
The file_names are supposed in following format FileName_Epoch_Er... | 4058051f96293101bd71de4fed03010fc075e3f7 | 3,617,352 |
def get_task_by_user_id():
"""
{
"page": "Long",
"size": "Long",
"user_id": "Long"
}
"""
domain = request.args.to_dict()
return task_service.get_task_by_user_id(domain) | 7c51402af0b472f4acfb2d56c1e3a9bfcc2054dc | 3,617,353 |
import sys
from HTMLParser import HTMLParser
import html
def unescape_html(chatbot, statement):
"""
Convert escaped html characters into unescaped html characters.
For example: "<b>" becomes "<b>".
"""
# Replace HTML escape characters
if sys.version_info[0] < 3:
html = HTMLParse... | 5e7bc331e426be34314a98c15430add15f3f1ef3 | 3,617,354 |
from operator import index
def return_suffix(kind=kind,index=index,dimkeys=dimkeys,copula_string=None,marginal_string = None,marginal_data=None,segment_marginal=None):
"""
:return: a coherent string that permits to give a suffix in the name of our files.
"""
if kind == 'diagonal':
diago = dia... | f429552623e3cb38914eaec7c75c57f5a45b1c2d | 3,617,355 |
def collect_metrics(manager: 'TxMiningManager') -> MetricData:
"""Collect data from TxMiningManager."""
return MetricData(
miners_count=len(manager.miners),
total_hashrate_ghs=manager.get_total_hashrate_ghs(),
txs_solved=manager.txs_solved,
txs_timeout=manager.txs_timeout,
... | dfba9378d03e58e243fb2716f4508b0b36c69216 | 3,617,356 |
def normalize_response(response, request=None):
"""
Given a response, normalize it to the internal Response class. This also
involves normalizing the associated request object.
"""
if isinstance(response, Response):
return response
if request is not None and not isinstance(request, Requ... | a92feb1e0fc83b62297567e44c0cbb65ea327ec9 | 3,617,357 |
def _get_user():
"""Get the user object or create it based on the token in the session
If there is no access token abort with 401 message
"""
if 'Access-Token' not in request.headers:
abort(401, message='Access Denied!')
token = request.headers['Access-Token']
user_data = github.get('u... | d08e55e8566de348869a1790067e0a231b49c982 | 3,617,358 |
import typing
def get_notifications_by_type(user_id: int, notification_type: NotificationType, unread_only: bool = False) -> typing.List[Notification]:
"""
Get all (unread) notifications of a given type for a given user.
:param user_id: the ID of an existing user
:param notification_type: the type of... | 1cf14a53a483fe945ae010dea394d0b4185e7f96 | 3,617,359 |
def get_processing_unit_config(unit_config):
"""Returns the :class:`.ProcessingUnitConfig` corresponding to
*unit_config*"""
if isinstance(unit_config, ProcessingUnitConfig):
return unit_config
elif isinstance(unit_config, dict):
unit_name = unit_config["unit_name"]
processin... | c9e73c6f0fd64540c982fdde50e63ed690665655 | 3,617,360 |
from re import S
def partscore_pairs(part,score=S):
"""Scores the partition for student groupings accoring to the provided score class,
by performing the groupscore function for every group in the partition
returns: a number (lower scores mean the partition is more novel)
"""
ss = 0
for group... | e6de1780327f4bf1f3e9ff500a9bb60c9ed364df | 3,617,361 |
import pandas
def get_gedi02_b_beam_as_gdf(input_file, gedi_beam_name, valid_only=True, out_epsg_code=4326):
"""
A function which gets a geopandas dataframe for a beam. Note the parameters with multiple
values in the z axis are not included in the dataframe.
:param input_file: input file path.
:p... | 47c714b981583bc67bc3bdd263463e0a005e0db6 | 3,617,362 |
def save_tag(n_clicks_timestamp, input_values):
"""Saves the corresponding tag from the input field to the tag list.
Ideally, we would like to use the MATCH function to determine which button was clicked.
However, since we only have one save tag toast for all the tags, we can't use MATCH in the Output fiel... | fa397a038e3087591d4f5d928028d951addbce45 | 3,617,363 |
import json
import click
def maybe_print_as_json(opts, data, page_info=None):
"""Maybe print data as JSON."""
if opts.output not in ("json", "pretty_json"):
return False
root = {"data": data}
if page_info is not None and page_info.is_valid:
meta = root["meta"] = {}
meta["pagi... | 5c84deb086001e0406dc8df9df4510ddc301e0e8 | 3,617,364 |
def float_like(x, /) -> bool:
"""
Tests if an object could be converted to a float.
Args:
x (Any): object to test
Returns:
bool: Whether the object can be converted to a float.
"""
try:
float(x)
return True
except ValueError:
return False | ed34d52e34bc7c09242fde6cd0890381df297325 | 3,617,365 |
import sys
def open_file(path):
"""
Opens a given file. Returns an error if the current file type is not supported.
"""
try:
file = mediafile.MediaFile(path)
return { 'success': True, 'file': file }
except mediafile.UnreadableFileError:
return { 'error': 'the given file cou... | 7287e724911a14bc674c594e5074ebf91fd94f88 | 3,617,366 |
def schur_comp(M,idx_set):
"""
computes the schur complement/the pieces of the schur complement for a matrix M
"""
comp_idx = [i for i in range(len(M)) if i not in idx_set]
A = M[np.ix_(idx_set,idx_set)]
B = M[np.ix_(idx_set,comp_idx)]
C = M[np.ix_(comp_idx,idx_set)]
D = M[np.ix_(comp_id... | a651692e410d43711a19ba17496d081c52d235c4 | 3,617,367 |
def noise_db(a, snr):
"""
Takes an array of seismic amplitudes and SNR in dB.
Args:
a (ndarray): seismic amplitude array.
snr (int): signal to noise ratio.
Returns: Noise array, the same shape as the input.
Note: it does *not* return the input array with the noise added.
... | e3f8c7d8623b95226be46bf8b5c32ebc29ac3114 | 3,617,368 |
def get_structure_numbers(structure, momenta_dict):
"""Return the number of the parent and children of a given structure
according to some momenta dictionary.
"""
legs = structure.get_all_legs()
children = frozenset((leg.n for leg in legs))
if structure.name() == "S":
return None, child... | db9548b1e26402bb38e9c33741ca38aa866fd217 | 3,617,369 |
def purchase_number(request):
"""Purchases a new phone number using the Twilio API"""
form = PurchaseNumberForm(request.POST)
if form.is_valid():
# Purchase the phone number
phone_number = form.cleaned_data['phone_number']
twilio_number = purchase_phone_number(phone_number.as_e164)
... | e95455b88119486a6b2de3a128d10960f61eed2c | 3,617,370 |
def oneshot_behavior(behaviour, name=None):
"""
This is taken from py_trees.idiom.oneshot. However, we use a different
clearing policy to work around some issues for setting up StartConditions
of OpenSCENARIO
"""
if not name:
name = behaviour.name
variable_name = get_py_tree_path(beh... | 4840ba86e40c5040f8c31223b2370176819c9a5c | 3,617,371 |
import math
def font_render_multiline(font, text, antialias, color, background=None, justify='left', line_spacing=0):
""" Returns a Surface containing the text in the given font.
The first five parameters are the ones used to render single line text.
justify can be 'left', 'right', or 'center'.
line_... | d18720d585fdd49773335bd2d4218ab974b4826b | 3,617,372 |
def user_conversion():
"""
Best pipeline: GaussianNB(ExtraTreesClassifier(XGBClassifier(input_matrix, learning_rate=0.001, max_depth=10, min_child_weight=10, n_estimators=100, n_jobs=1, subsample=0.7500000000000001, verbosity=0), bootstrap=True, criterion=entropy, max_features=0.55, min_samples_leaf=10, min_sam... | 5a7c2b709976f8e51932737eccbcf82563421c3e | 3,617,373 |
from typing import List
def get_files_names_from_dir(directory: str, ext: str) -> List[str]:
"""Return list of file's names with extension `ext` from `directory`."""
files_names = [
file_name
for file_name in listdir(directory) if file_name.endswith(ext)
]
files_names.sort()
return... | 3bbc66146e67596532593214ed8c12592e1d0101 | 3,617,374 |
def check_bin(number, index):
"""
用于某些二进制标志位的场景
返回一个 int 类型变量的某一二进制位的值,index 从 1 开始,即
>>> check_bin(2, 1)
0
>>> check_bin(2, 2)
1
"""
try:
return int(bin(number)[2:][-index])
except IndexError:
return 0 | d5c54f3121f56c028fb20e6bfcd51395cd58aa05 | 3,617,375 |
import sys
import os
import subprocess
def run_command(cmd):
"""Run a command in a sub-process.
Returns the exit status code and the combined stdout and stderr.
"""
if env.PY2 and isinstance(cmd, unicode):
cmd = cmd.encode(sys.getfilesystemencoding())
# In some strange cases (PyPy3 in a... | 0c522a765fc6a0153e2988a5208774440d5f7f8d | 3,617,376 |
def parse_exclusion_file(exclusion_file, exclusion_column):
"""
Reads in the specified column of the specified file into a set.
"""
exclusion_list = set()
with open(exclusion_file) as infile:
for line in infile:
to_exclude = line.split('\t')[exclusion_column]
exclus... | 3ae8430a96ed1883691cd63b86cd26d24c6f7652 | 3,617,377 |
def unstack(*args, **kwargs):
""" See https://www.tensorflow.org/api_docs/python/tf/unstack .
"""
return tensorflow.unstack(*args, **kwargs) | dedb75c147cefb792ea8d3242bb6f45c606952ab | 3,617,378 |
from typing import Callable
from typing import Sequence
from typing import Hashable
def map_operations_and_unroll(
circuit: CIRCUIT_TYPE,
map_func: Callable[[ops.Operation, int], ops.OP_TREE],
*,
deep: bool = False,
raise_if_add_qubits=True,
tags_to_ignore: Sequence[Hashable] = (),
) -> CIRCUI... | b7c6c67e8b74c4e6e1feadb305a7d830018c189f | 3,617,379 |
def min_sum_space_improved(arr):
"""
A method that calculates the minimum difference of the sums of 2 arrays consisting of all the elements from the input array.
Wrong problem description (as it talks about sets): https://practice.geeksforgeeks.org/problems/minimum-sum-partition/0
Correct problem descri... | b8eb4f22e44d2d5104b2f4436908aa85ee07ac2d | 3,617,380 |
def full_extraction(url):
"""
Runs a complete end-to-end extraction using all other functions.
:param url: The url to extract the HTML from
:return: An object that contain the HTML from the article
"""
full_html = get_html(url)
pattern_extraction = pattern_article_extraction(url)
retur... | b2133613e30c1f416adbf9d686fbedca7ad05132 | 3,617,381 |
def auth_enabled(controller):
"""Decorator for if an auth plugin is enabled"""
@wraps(controller)
def wrapper(request, *args, **kwargs):
if not mgg.app.auth:
messages.add_message(
request,
messages.WARNING,
_('Sorry, authentication is disab... | 4e781c509414e67e9571a0860b8f9962488429a5 | 3,617,382 |
from typing import Dict
def encode_token_tx(token_tx: Dict) -> bytes:
"""
Creates bytes representation of token transaction data.
args:
token_tx: Dictionary containing the token transaction data.
returns:
Bytes to be saved as token value in DB.
"""
token_tx_str = ''
token... | 4100d4dacdeea4a588906151a02f9adef874aaec | 3,617,383 |
def from_base32(number):
"""Convert a BASE32 representation of an AIC to a BASE10 one."""
number = compact(number)
if not all(x in _base32_alphabet for x in number):
raise InvalidFormat()
s = sum(_base32_alphabet.index(n) * 32 ** i
for i, n in enumerate(reversed(number)))
return ... | 54a493544214edae5414f49c2e3645cfda287768 | 3,617,384 |
def distance(strand_a, strand_b):
"""
Compare two strings and count the differences.
:param strand_a string - String representing a strand of DNA.
:param strand_b string - String representing a different strand of DNA.
:return int - number of differences between 2 strands.
"""
if len(stran... | 012e0b1640e738b17dc6a4fb4a01c1f53e0e7639 | 3,617,385 |
import sys
def unzscore(im_norm, zscore_median, zscore_iqr):
"""
Revert z-score normalization applied during preprocessing. Necessary
before computing SSIM
:param im_norm: Normalized image for un-zscore
:param zscore_median: Image median
:param zscore_iqr: Image interquartile range
:retur... | aa74e5a2b8e757d569003b4a4f21675e97875a01 | 3,617,386 |
def _straight_line_vertices(adjacency_mat, node_coords, directed=False):
"""
Generate the vertices for straight lines between nodes.
If it is a directed graph, it also generates the vertices which can be
passed to an :class:`ArrowVisual`.
Parameters
----------
adjacency_mat : array
... | 999bb38d67412abdf84078b8026088f5bebae7a5 | 3,617,387 |
import argparse
def parse_command_line():
"""
Parse command line.
It uses argparse to parse thoraxe' command line arguments and returns
the argparse parser.
"""
parser = argparse.ArgumentParser(
prog="thoraxe",
description="""
thoraxe is a tool to identify orthologous ... | 6591b215759ebec85aab49ea1645a79e64b80f5f | 3,617,388 |
import traceback
def set_artist(track_title, track_genre, track_location, track_artist,language):
"""
Function to set only artist details
Returns boolean True if set else False
gets invoked in the get song function
"""
try:
if(Check_artist(track_artist)):
pass
else:
collection = db.collection(u'artis... | 04d5a3940e1f227b4e700788603aca91417e359b | 3,617,389 |
def get_latest_status_from_database(session: Session) -> Status:
"""Get latest status from database"""
latest_status = get_latest_status(session)
# convert to PyDantic object
latest_status = Status.from_orm(latest_status)
return latest_status | 54c88126c3ebb94a68c95d7b82e55a1137b50e21 | 3,617,390 |
def values_to_rgb(ranges, values):
""" Converts a three dimensional tuple to a RGB map
@param ranges The mininum and maximum of each dimension
@param values The value to transform
"""
r_color = (float(values[0]) - float(ranges[0][0])) / float(ranges[0][1])
g_color = (float(values[1]) - float(ran... | 2dabe98b78e873e1aaff91577461e0991402ec64 | 3,617,391 |
def requires_auth(f):
""" Decoretorn to check user auth """
@wraps(f)
def decorated(*args, **kwargs):
""" Check user auth """
auth = request.authorization
if not auth or not check_auth(auth.username, auth.password):
raise Unauthorized('Could not verify your access level f... | 49bb9a335d413cd3e476e580e99e517d56a9ce23 | 3,617,392 |
def algorithm_m_clean(n):
"""
Knuth's Algorithm M for permutation generation,
cleaned up to remove duplicate rotations.
This generates the rotations:
constructs a map of each sequence
to its captain.
"""
sequence_to_captain = {}
captains = set()
for perm in algorithm_m(n):
... | b2d6228a5872c0cd15a9d3986c0f507aac982306 | 3,617,393 |
import time
from datetime import datetime
import re
def _archive_url_parser(
header, url, latest_version=__version__, instance=None, response=None
):
"""Returns the archive after parsing it from the response header.
Parameters
----------
header : str
The response header of WayBack Machine... | 83980923036b27e15d11a3eccaf790d93acf8fcd | 3,617,394 |
import mmap
def fasta_records(filepath):
"""Count the number of records in a FASTA file."""
count = 0
next_pos = 0
angle_bracket = bytes(">", "utf-8")
memory_map = TrimmableMemoryMap(filepath, access=mmap.ACCESS_READ)
with memory_map.map() as mem_map:
size = memory_map.size
nex... | 1262b730f00dff1dbb866b4044b9d22b535de090 | 3,617,395 |
def cifar_iid(dataset, num_users):
"""
Sample I.I.D. client data from CIFAR10 dataset
:param dataset:
:param num_users:
:return: dict of image index
"""
num_items = int(len(dataset) / num_users)
dict_users, all_idxs = {}, [i for i in range(len(dataset))]
for i in range(num_users):
dict_users[i] = ... | 3a79a354b57783ae06297ef870aa4ce4e001394a | 3,617,396 |
def get_area_filter(point_cloud, extents):
"""
Args:
point_cloud: (3, N) point cloud
extents: 3D area in the form [[min_x, max_x], [min_y, max_y], [min_z, max_z]]
Returns:
"""
if not isinstance(point_cloud, np.ndarray) and isinstance(extents, np.ndarray):
raise TypeError('... | 149c520f51f2df0a7d8987247bc4a53126813b26 | 3,617,397 |
def meat2segment(meat):
"""Convert into a list of points."""
asos = load_geodf("sfstns")
tokens = meat.split()
sz = len(tokens)
i = 0
pts = []
gc = "geometry"
while i < sz:
token = tokens[i]
if token.isdigit() and (i + 2) < sz:
miles = float(token)
... | 9908d32f89b009099a17eb99c637885d85eda45b | 3,617,398 |
def ensure_shape(x, y):
"""Util to broadcast on var to another but only when shape is different.
This way we don't convert scalar into array type unnecessarily.
"""
shape_y = np.shape(y)
if np.shape(x) == shape_y:
return x
return np.broadcast_to(x, shape_y) | d389c9cfd553b732ee554267a40cd51771ca0160 | 3,617,399 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.