content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
import json
def list_clusters(event, context):
"""List clusters"""
clusters = []
cluster_items = storage.get_cluster_table().scan()
for cluster in cluster_items.get('Items', []):
clusters.append(cluster['id'])
return {
"statusCode": 200,
"body": json.dumps(clusters)
... | 5f88ca446e8d07d7584b1dfd12fb64cddefc918c | 14,651 |
def round(data):
"""Compute element-wise round of data.
Parameters
----------
data : relay.Expr
The input data
Returns
-------
result : relay.Expr
The computed result.
"""
return _make.round(data) | e3adfdc29d9cc641ca33fb375649caf176098d75 | 14,652 |
def deserialize(member, class_indexing):
"""
deserialize
"""
class_name = member[0].text
if class_name in class_indexing:
class_num = class_indexing[class_name]
else:
return None
bnx = member.find('bndbox')
box_x_min = float(bnx.find('xmin').text)
box_y_min = floa... | 087102acec79ec5d0ecad91453885579c2395895 | 14,653 |
def interval_weighting(intervals, lower, upper):
"""
Compute a weighting function by finding the proportion
within the dataframe df's lower and upper bounds.
Note: intervals is of the form ((lower, upper, id), ...)
"""
if len(intervals) == 1:
return np.asarray([1])
wts = np.ones(le... | 5eaf974597ad13d2b2204526d84412a22a104bc2 | 14,654 |
def centroid_precursor_frame(mzml_data_struct):
"""
Read and returns a centroid spectrum for a precursor frame
This function uses the SDK to get and return an MS1 centroid spectrum for
the requested frame.
Parameters
----------
mzml_data_struct : dict
structure of the mzml data
... | 24d6f19afeafcd731dd316c36aa4784d60224ee8 | 14,655 |
import random
def createNewForest():
"""Returns a dictionary for a new forest data structure."""
forest = {'width': WIDTH, 'height': HEIGHT}
for x in range(WIDTH):
for y in range(HEIGHT):
if (random.randint(1, 10000) / 100) <= INITIAL_TREE_DENSITY:
forest[(x, y)] = TREE... | 1c58bb3faeba7b866a7b406b742106adccb64a0f | 14,659 |
def test_filter():
"""
Base class filter function
"""
def test():
"""
Test the filter function
"""
try:
for i in _TEST_FRAME_.keys():
for j in range(10):
test = _TEST_FRAME_.filter(i, "<", j)
assert all(map(lambda x: x < j, test[i]))
test = _TEST_FRAME_.filter(i, "<=", j)
assert a... | 5623ba98d8b06b2e2f395bf8387268f7857236e0 | 14,660 |
def exp_moving_average(values, window):
""" Numpy implementation of EMA
"""
if window >= len(values):
if len(values) == 0:
sma = 0.0
else:
sma = np.mean(np.asarray(values))
a = [sma] * len(values)
else:
weights = np.exp(np.linspace(-1., 0., window)... | 1563ac9898296e253c7733d341d30ee36cfb822c | 14,661 |
def parabolic(f, x):
"""
Quadratic interpolation in order to estimate the location of a maximum
https://gist.github.com/endolith/255291
Args:
f (ndarray): a vector a samples
x (int): an index on the vector
Returns:
(vx, vy): the vertex coordinates of a parabola passing... | 4373ee6390f3523d0fd69487c27e05522bd8c230 | 14,662 |
def arith_expr(draw):
"""
arith_expr: term (('+'|'-') term)*
"""
return _expr_builder(draw, term, '+-') | 277361c91c5967b36ec24b87402d2444e40f2a31 | 14,663 |
import glob
def extract_running_speed(module_params):
"""Writes the stimulus and pkl paths to the input json
Parameters
----------
module_params: dict
Session or probe unique information, used by each module
Returns
-------
module_params: dict
Session or probe unique information,... | d04908a9161bebdc74b5a35f14568e50bf4f8559 | 14,664 |
def sliced_transposed_product(
mat,
block_size,
axes=(-1,),
precision=lax.Precision.DEFAULT,
):
"""Returns the blocked slices representing a symmetric contraction.
Specifically, the output is a contraction of the input mat with itself, in the
specified axes.
Args:
mat: The matrix... | 1bb2016dd485b2da9e74d4a70c703e8fefacf8ff | 14,665 |
import re
def _is_ipython_line_magic(line):
"""
Determines if the source line is an IPython magic. e.g.,
%%bash
for i in 1 2 3; do
echo $i
done
"""
return re.match(_IS_IPYTHON_LINE_MAGIC, line) is not None | 90575b556f6f6d62bb82b6fb18b2bc979735e808 | 14,666 |
def osu_to_excel(
osu_path: str,
excel_path: str = '',
n: int = None,
compact_log: bool = False,
display_progress=True,
**kwargs
) -> str:
"""Export metadata and hitobjects in a xlsx file."""
metadata = from_osu(
osu_path,
n=n,
compact_log=compact_log,
display_progress=display_progress
)
mode =... | 5d26d70706ec74febc8be0c0d49eaf7f0c48186d | 14,667 |
def convert_pybites_chars(text):
"""Swap case all characters in the word pybites for the given text.
Return the resulting string."""
return "".join(
char.swapcase() if char.lower() in PYBITES else char for char in text
) | 73dff55cc7cd2f1c85d1f51319c12f8335803dce | 14,669 |
def get_meminfo():
"""
Return the total memory (in MB).
:return: memory (float).
"""
mem = 0.0
with open("/proc/meminfo", "r") as fd:
mems = fd.readline()
while mems:
if mems.upper().find("MEMTOTAL") != -1:
try:
mem = float(mems.s... | 5aaa671d7d407b1593099a2fb7a1f2fcb0a88542 | 14,670 |
def process_inline_semantic_match(placeholder_storage, match_object):
"""
Process a single inline-semantic match object.
"""
delimiter = match_object.group('delimiter')
tag_name = TAG_NAME_FROM_INLINE_SEMANTIC_DELIMITER[delimiter]
attribute_specification = match_object.group('attribute_specification')... | a1f66093ed361f5e7f924061a1c9770d880d4acc | 14,671 |
async def insert_cd_inurl_name(cluster_id: str, iso_name: str):
""" Find SR by Name """
try:
try:
session = create_session(
_id=cluster_id, get_xen_clusters=Settings.get_xen_clusters()
)
except KeyError as key_error:
raise HTTPException(
... | 7c6df12f6de461d559c63adb5e014708e2122760 | 14,672 |
def main_add(args):
"""Start the add-environment command and return exit status code."""
return add_env_spec(args.directory, args.name, args.packages, args.channel) | 6358464086e3fc01553df301514976d04a44b3c4 | 14,673 |
def write(objct, fileoutput, binary=True):
"""
Write 3D object to file. (same as `save()`).
Possile extensions are:
- vtk, vti, npy, npz, ply, obj, stl, byu, vtp, vti, mhd, xyz, tif, png, bmp.
"""
obj = objct
if isinstance(obj, Points): # picks transformation
obj = objct.polydat... | 51e595a83d54a90dd392d09a67289527cb8a4510 | 14,674 |
def instantiate_env_class(builder: IRBuilder) -> Value:
"""Assign an environment class to a register named after the given function definition."""
curr_env_reg = builder.add(
Call(builder.fn_info.env_class.ctor, [], builder.fn_info.fitem.line)
)
if builder.fn_info.is_nested:
builder.fn_... | 14e3113fe6ba3ec107fcd36e36c7dc525bf11cc5 | 14,675 |
import json
def validate_recaptcha(token):
"""
Send recaptcha token to API to check if user response is valid
"""
url = 'https://www.google.com/recaptcha/api/siteverify'
values = {
'secret': settings.RECAPTCHA_PRIVATE_KEY,
'response': token
}
data = urlencode(values).encode... | 7be09a76cbf946edbe8b1d717b2e2e2cdef9a902 | 14,676 |
def aggregate_hts(style="all_modes_combined"):
"""Use the 'processed' version of the HTS table to summarize the flows.
Using the 'style' parameter, you can:
- aggregate by mode using 'by_mode'
- aggregate by mode and o&d location
types using 'by_mode_and_location_type'
- aggre... | b200b312351408e4615a503f56f301c3b775f35a | 14,677 |
def pix2sky(shape, wcs, pix, safe=True, corner=False):
"""Given an array of corner-based pixel coordinates [{y,x},...],
return sky coordinates in the same ordering."""
pix = np.asarray(pix).astype(float)
if corner: pix -= 0.5
pflat = pix.reshape(pix.shape[0], -1)
coords = np.asarray(wcsutils.nobcheck(wcs).wcs_pix... | 288d3f67080611773273aaed950385b19d7aebc8 | 14,678 |
def getRelativeSilenceVideo(videoPath):
"""Function to get relative silence videos before and after each video"""
silVid = ['', '']
vidData = getVideoDataFromPath(videoPath)
videoNameList = videoPath.split('/')
tempVidName = videoNameList[0] + '/' + videoNameList[1] + '/' + videoNameList[2] + '/Sile... | b829915c4cfa7592e394914ba40457200b352ab4 | 14,679 |
def convert_to_xyxy_coordinates(boxes: tf.Tensor) -> tf.Tensor:
"""Convert boxes to their center coordinates
y_cent, x_cent, h, w -> y_min, x_min, y_max, x_max
Arguments:
- *boxes*: A Tensor of shape [N, ..., (y_cent, x_cent, h, w)]
Returns:
A tensor of shape [N, ..., num_boxes, (y_min, x_m... | 2412d3383d4335d707e220a52ac5e5198513d8ab | 14,680 |
import click
def classify(mapper: object,
files: list or dict,
samples: list = None,
fmt: str = None,
demux: bool = None,
trimsub: str = None,
tree: dict = None,
rankdic: dict = None,
na... | 1d1976dcf35617a3860af39d77fb206880071105 | 14,682 |
import re
def get_better_loci(filename, cutoff):
"""
Returns a subset of loci such that each locus includes at least "cutoff"
different species.
:param filename:
:param cutoff:
:return:
"""
f = open(filename)
content = f.read()
f.close()
loci = re.split(r'//.*|', conte... | e2d563c9d0568cef59ea0280aae61a78bf4a6e7b | 14,683 |
import math
def paginate_data(data_list, page=1 ,per_page=10):
"""将数据分页返回"""
pages = int(math.ceil(len(data_list) / per_page))
page = int(page)
per_page = int(per_page)
has_next = True if pages > page else False
has_prev = True if 1 < page <= int(pages) else False
items = data_list[(page-1... | 63a4602462e0c2e38329107b10b5d72b63c3108d | 14,684 |
import torch
def quat_to_rotmat(quat):
"""Convert quaternion coefficients to rotation matrix.
Args:
quat: size = [B, 4] 4 <===>(w, x, y, z)
Returns:
Rotation matrix corresponding to the quaternion -- size = [B, 3, 3]
"""
norm_quat = quat
norm_quat = norm_quat / norm_quat.norm(p... | 6590272c0ed3a97f8f5ef5eacd3605b0c7b91626 | 14,685 |
def has_multimethods(cls):
""" Declare class as one that have multimethods."""
for name, obj in cls.__dict__.items():
if isinstance(obj, MethodDispatcher):
obj.proceed_unbound_rules(cls)
return cls | 4248af44c0ba6b585a80a4eb0d8da1ca5e9f2299 | 14,686 |
def elastic_depth(f, time, method="DP2", lam=0.0, parallel=True):
"""
calculates the elastic depth between functions in matrix f
:param f: matrix of size MxN (M time points for N functions)
:param time: vector of size M describing the sample points
:param method: method to apply optimization (defau... | 574880a5cc3d26d756286a5d7a8959c67141678a | 14,687 |
from typing import Any
def run_coro_thread(func: callable, *args, **kwargs) -> Any:
"""
Run a Python AsyncIO coroutine function within a new event loop using a thread, and return the result / raise any exceptions
as if it were ran normally within an AsyncIO function.
.. Caution:: If you're w... | 078b17d38552aa5d9a30efd1374d8f4e8f7e9b40 | 14,688 |
def get_all_ports(entity):
"""
Recursively descends through the entity hierarchy and collects all ports
defined within the parameter or any of its children.
Parameters
----------
entity : Entity
The root from which to start collecting.
Returns
-------
list of Port
... | a490ba48d647a1d82a2c7ae7d75e61afb089c907 | 14,689 |
def deploy(**kwargs):
"""Deploy a PR into a remote server via Fabric"""
return apply_pr(**kwargs) | 26d11e6d6ab08e1298aa99203925c45b96535df9 | 14,690 |
import torch
def word_list2tensor(word_list, dictionary):
"""
args
word_list: [batch_size, seq_len, token_id]
dictionary: Dictionary
return
source, target [batch_size, seq_len, token_id]
"""
word_list_padded = add_word_padding(word_list, dictionary)
batch = torch.LongTensor(word_l... | 6e484c282779bfd709030735268468f3bacde268 | 14,691 |
import six
def canonicalize_monotonicity(monotonicity, allow_decreasing=True):
"""Converts string constants representing monotonicity into integers.
Args:
monotonicity: The monotonicities hyperparameter of a `tfl.layers` Layer
(e.g. `tfl.layers.PWLCalibration`).
allow_decreasing: If decreasing mono... | a9d0870d03f11d7bdff4c8f673cd78d072fa8478 | 14,692 |
def add_gdp(df, gdp, input_type="raw", drop=True):
"""Adds the `GDP` to the dataset. Assuming that both passed dataframes have a column named `country`.
Parameters
----------
df : pd.DataFrame
Training of test dataframe including the `country` column.
gdp : pd.DataFrame
Mapping betw... | 72e2b5fe839f3dbc71ca2def4be442535a0adb84 | 14,693 |
from scipy.ndimage.filters import maximum_filter
def no_background_patches(threshold=0.4, percentile=99.9):
"""Returns a patch filter to be used by :func:`create_patches` to determine for each image pair which patches
are eligible for sampling. The purpose is to only sample patches from "interesting" regions... | b1ffd8b7bb2023c483da35565044b02f7fd96cd8 | 14,695 |
def start_thread():
"""Start new thread with or without first comment."""
subject = request.form.get('subject') or ''
comment = request.form.get('comment') or ''
if not subject:
return error('start_thread:subject')
storage.start_thread(g.username, subject, comment)
flash('New Thread Sta... | a8fabcddac91cc5cc6d5a63382e1ba433f425c20 | 14,696 |
def get_package_data(name, package=None):
"""Retrieve metadata information for the given package name"""
if not package:
package = models.Package(name=name)
releases = {}
else:
releases = package.get_all_releases()
client = xmlrpclib.ServerProxy('http://pypi.python.org/pypi')
... | 98824594fdd245760387f912192037b2e024aadc | 14,697 |
def feedforward(
inputs,
input_dim,
hidden_dim,
output_dim,
num_hidden_layers,
hidden_activation=None,
output_activation=None):
"""
Creates a dense feedforward network with num_hidden_layers layers where each layer
has hidden_dim number of units except... | bbf6559d27e68ff4642d8842af50ff0d292bd1c8 | 14,700 |
import doctest
def _test():
"""
>>> solve("axyb", "abyxb")
axb
"""
global chr
def chr(x): return x
doctest.testmod() | 1ba052fbf066cee92ad2088b9562443c727292df | 14,701 |
from typing import Optional
def _basic_rebuild_chain(target: database.Target) -> RebuildChain:
"""
Get a rebuild chain based purely on 'rebuild info' from Jam.
"""
chain: RebuildChain = [(target, None)]
current: Optional[database.Target] = target
assert current is not None
while True:
... | 966864ac71eafb982c2dff0f74e383e207127b32 | 14,702 |
def ravel_group_params(parameters_group):
"""Take a dict(group -> {k->p}) and return a dict('group:k'-> p)
"""
return {f'{group_name}:{k}': p
for group_name, group_params in parameters_group.items()
for k, p in group_params.items()} | 4a768e89cd70b39bea4f658600690dcb3992a710 | 14,703 |
def decode_orders(game, power_name, dest_unit_value, factors):
""" Decode orders from computed factors
:param game: An instance of `diplomacy.Game`
:param power_name: The name of the power we are playing
:param dest_unit_value: A dict with unit as key, and unit value as value
:param ... | ac1e9b59d792158bb0b903709344b8535b330e73 | 14,704 |
from typing import Type
def _convert_to_type(se, allow_any=False, allow_implicit_tuple=False):
""" Converts an S-Expression representing a type, like (Vec Float) or (Tuple Float (Vec Float)),
into a Type object, e.g. Type.Tensor(1,Type.Float) or Type.Tuple(Type.Float, Type.Tensor(1,Type.Float)).
... | f615244363fa7fcdc67c4d68580860b3145bd94f | 14,705 |
def index():
"""Returns a 200, that's about it!!!!!!!"""
return 'Wow!!!!!' | f6d8a765556d2d6a1c343bb0ab1a9d4a6c5fd6ba | 14,706 |
def merge_tables(pulse_data, trial_data, merge_keys=TRIAL_GROUPER):
"""Add trial-wise information to the pulse-wise table."""
pulse_data = pulse_data.merge(trial_data, on=merge_keys)
add_kernel_data(pulse_data)
return pulse_data | 1c5eafa44b50d05c8d23af7d290d0b40c2643ef9 | 14,708 |
def eos_deriv(beta, g):
""" compute d E_os(beta)/d beta from polynomial expression"""
x = np.tan(beta/2.0)
y = g[4] + x * g[3] + x*x * g[2] + x*x*x*g[1] + x*x*x*x*g[0]
y = y / ((1.0 + x*x)*(1.0 + x*x)*(1.0 + x*x))
return y | 2e1055bc48364abfe5bb07a1d9eafd32fefb7031 | 14,709 |
def optimizeAngle(angle):
"""
Because any rotation can be expressed within 360 degrees
of any given number, and since negative angles sometimes
are one character longer than corresponding positive angle,
we shorten the number to one in the range to [-90, 270[.
"""
# First, we put the new ang... | 8abcaba2542b59715ced1c0acec94194f6e357d7 | 14,710 |
def process_one_name(stove_name):
"""
Translates a single PokerStove-style name of holecards into an
expanded list of pokertools-style names.
For example:
"AKs" -> ["Ac Kc", "Ad Kd", "Ah Kh", "As Ks"]
"66" -> ["6c 6d", "6c 6h", "6c 6s", "6d 6h", "6d 6s", "6c 6d"]
"""
if len(stov... | 5a824df9ae1a723c350b635a6b3096b795d4c58e | 14,711 |
def job_dispatch(results, job_id, batches):
"""
Process the job batches one at a time
When there is more than one batch to process, a chord is used to delay the
execution of remaining batches.
"""
batch = batches.pop(0)
info('dispatching job_id: {0}, batch: {1}, results: {2}'.format(job_i... | d6107c11bf350aedc1103e0e182f2808041abb5b | 14,712 |
import logging
import sqlite3
def get_temperature():
"""
Serves temperature data from the database, in a simple html format
"""
logger = logging.getLogger("logger")
#sqlite handler
sql_handler = SQLiteHandler()
logger.addHandler(sql_handler)
logger.setLevel(logging.INFO)
con ... | 3f2400c823ff2bc11a2b1910ce6cc39d90614178 | 14,713 |
def command_result_processor_category_empty(command_category):
"""
Command result message processor if a command category is empty.
Parameters
----------
command_category : ``CommandLineCommandCategory``
Respective command category.
Returns
-------
message : `str`
"... | 10da547a922bfd538a4241976385210969bf752a | 14,714 |
def _parse_path(**kw):
"""
Parse leaflet `Path` options.
http://leafletjs.com/reference-1.2.0.html#path
"""
color = kw.pop('color', '#3388ff')
return {
'stroke': kw.pop('stroke', True),
'color': color,
'weight': kw.pop('weight', 3),
'opacity': kw.pop('opacity', 1... | 02d3810ad69a1a0b8f16d61e661e246aea5c09cc | 14,715 |
def random_rotation(x, rg, row_axis=1, col_axis=2, channel_axis=0,
fill_mode='nearest', cval=0., interpolation_order=1):
"""Performs a random rotation of a Numpy image tensor.
# Arguments
x: Input tensor. Must be 3D.
rg: Rotation range, in degrees.
row_axis: Index of... | 57f263f1bee9fb323205543cba9c14c9a86ba431 | 14,716 |
from typing import Optional
import time
from datetime import datetime
def time_struct_2_datetime(
time_struct: Optional[time.struct_time],
) -> Optional[datetime]:
"""Convert struct_time to datetime.
Args:
time_struct (Optional[time.struct_time]): A time struct to convert.
Returns:
O... | 705b09428d218e8a47961e247b62b9dfd631a41f | 14,719 |
def we_are_buying(account_from, account_to):
"""
Are we buying? (not buying == selling)
"""
buy = False
sell = False
for value in TRADING_ACCOUNTS:
if (value.lower() in account_from):
buy = True
sell = False
elif (value.lower() in account_to):
... | a5748ad756f472e0e2c39b5dc5239265fbf3d1f4 | 14,722 |
import time
def wait_for_compute_jobs(nevermined, account, jobs):
"""Monitor and wait for compute jobs to finish.
Args:
nevermined (:py:class:`nevermined_sdk_py.Nevermined`): A nevermined instance.
account (:py:class:`contracts_lib_py.account.Account`): Account that published
the ... | 98370b8d596f304630199578a360a639507ae3c3 | 14,725 |
def f1_score_loss(predicted_probs: tf.Tensor, labels: tf.Tensor) -> tf.Tensor:
"""
Computes a loss function based on F1 scores (harmonic mean of precision an recall).
Args:
predicted_probs: A [B, L] tensor of predicted probabilities
labels: A [B, 1] tensor of expected labels
Returns:
... | df4f35516230a7c57b0c6b3e8b7e958feae900f8 | 14,726 |
def get_alarm_historys_logic(starttime, endtime, page, limit):
"""
GET 请求历史告警记录信息
:return: resp, status
resp: json格式的响应数据
status: 响应码
"""
data = {'alarm_total': 0, "alarms": []}
status = ''
message = ''
resp = {"status": status, "data": data, "message": messag... | bc273cf8e6d022374f92b7c3da86552a9dbbed2a | 14,727 |
def showCities():
"""
Shows all cities in the database
"""
if 'access_token' not in login_session:
return redirect(url_for('showLogin'))
cities = session.query(City).order_by(City.id)
return render_template('cities.html', cities=cities) | 558b2a8639f810cf105777ce89acc368e4441bbd | 14,728 |
def symb_to_num(symbolic):
"""
Convert symbolic permission notation to numeric notation.
"""
if len(symbolic) == 9:
group = (symbolic[:-6], symbolic[3:-3], symbolic[6:])
try:
numeric = notation[group[0]] + notation[group[1]] + notation[group[2]]
except:
n... | c2c11697658322ad972e87ec1eb55d08eaa91e0e | 14,729 |
def round_vector(v, fraction):
""" ベクトルの各要素をそれぞれ round する
Args:
v (list[float, float, float]):
Returns:
list[float, float, float]:
"""
v = [round(x, fraction) for x in v]
return v | 47c10d23d9f2caa319f4f3fa97c85cf226752bab | 14,730 |
def accept(model):
"""Return True if more than 20% of the validation data is being
correctly classified. Used to avoid including nets which haven't
learnt anything in the ensemble.
"""
accuracy = 0
for data, target in validation_data[:(500/100)]:
if use_gpu:
data, target = ... | c2921fb6dc0226b88fe7dd8219264cb5908feb6b | 14,731 |
import struct
def parse_tcp_packet(tcp_packet):
"""read tcp data.http only build on tcp, so we do not need to support other protocols."""
tcp_base_header_len = 20
# tcp header
tcp_header = tcp_packet[0:tcp_base_header_len]
source_port, dest_port, seq, ack_seq, t_f, flags = struct.unpack(b'!HHIIBB6... | fa1b1050609cce8ca23ca5bac6276a681f560659 | 14,732 |
def find_balanced(text, start=0, start_sep='(', end_sep=')'):
""" Finds balanced ``start_sep`` with ``end_sep`` assuming
that ``start`` is pointing to ``start_sep`` in ``text``.
"""
if start >= len(text) or start_sep != text[start]:
return start
balanced = 1
pos = start + 1
while... | 15c17a216405028b480efa9d12846905a1eb56d4 | 14,733 |
from datetime import datetime
import requests
import io
import re
def get_jhu_counts():
"""
Get latest case count .csv from JHU.
Return aggregated counts by country as Series.
"""
now = datetime.datetime.now().strftime("%m-%d-%Y")
url = f"https://raw.githubusercontent.com/CSSEGISandData/COVI... | 6a3fb69cce6f8976178afd3ff81ab2381b89abc5 | 14,734 |
def sectionsToMarkdown(root):
"""
Converts a list of Demisto JSON tables to markdown string of tables
:type root: ``dict`` or ``list``
:param root: The JSON table - List of dictionaries with the same keys or a single dictionary (required)
:return: A string representation of the markdow... | 3f916544cc5a9dc7e4d094d82834382d377948f1 | 14,735 |
import numpy
def VonMisesFisher_sample(phi0, theta0, sigma0, size=None):
""" Draw a sample from the Von-Mises Fisher distribution.
Parameters
----------
phi0, theta0 : float or array-like
Spherical-polar coordinates of the center of the distribution.
sigma0 : float
Width of the d... | 440029bb9c3455dce22ff2d078068f9b7c404a7b | 14,736 |
from typing import Optional
from typing import Dict
from typing import Any
from unittest.mock import patch
async def async_init_flow(
hass: HomeAssistantType,
handler: str = DOMAIN,
context: Optional[Dict] = None,
data: Any = None,
) -> Any:
"""Set up mock Roku integration flow."""
with patch(... | 2147f18b6b26e57e84d21aff321e8464710de653 | 14,737 |
import inspect
def create_cell(cell_classname, cell_params):
""" Creates RNN cell.
Args:
cell_classname: The name of the cell class,
e.g. "LSTMCell", "GRUCell" and so on.
cell_params: A dictionary of parameters to pass
to the cell constructor.
Returns:
A `tf.c... | 64eed878f950499b599f992dbb50f2f05e8fbff9 | 14,739 |
def get_myia_tag(rtag):
"""Return the myia tag for a constructor.
This will fail if you haven't properly called fill_reverse_tag_map().
"""
return rev_tag_map[rtag] | 95e7afb73ce15bbfe7a75c4708f5c81a9c9e22df | 14,740 |
def get_priority(gene, phenotype):
"""
Get matched priority from the phenotype table.
Parameters
----------
gene : str
Gene name.
phenotype : str
Phenotype name.
Returns
-------
str
EHR priority.
Examples
--------
>>> import pypgx
>>> pypgx... | 5520d8df0b79834227f059e98d66109134e84439 | 14,741 |
import tqdm
from datetime import datetime
def _generator3(path):
"""
Args:
path: path of the dataframe
Returns:
yield outputs of X and Y pairs
"""
args = init_args()
catalog = load_catalog(path)
def preprocess(x, y=None):
zero = False
if not np.any(x):
... | 3d26d9cab1777b3b72d85584c6ff95b39c725e47 | 14,742 |
def _extract_gsi(name):
"""
Extract a normalised groundstation if available.
:param name:
:rtype: str
>>> _extract_gsi('LANDSAT-7.76773.S3A1C2D2R2')
>>> _extract_gsi('AQUA.60724.S1A1C2D2R2')
>>> _extract_gsi('TERRA.73100.S1A2C2D4R4')
>>> _extract_gsi('LANDSAT-8.3108')
>>> _extract_g... | b101b79df21b9d0bbb633dbca14ff6a5b207b91d | 14,743 |
def array_at_verts_basic2d(a):
"""
Computes values at cell vertices on 2d array using neighbor averaging.
Parameters
----------
a : ndarray
Array values at cell centers, could be a slice in any orientation.
Returns
-------
averts : ndarray
Array values at cell vertices,... | e1f9ab5abbed6d4837daec01b8cd865d15cddde6 | 14,744 |
def get_subquestion_answer(response, questions, subquestion):
"""
Return the answer to a subquestion from ``response``.
"""
question_id = subquestion[0]
answers = response[question_id]
dim = len(subquestion) - 1
for answer in answers:
matched = True
if subquestion[1] != answe... | e0b89db06570e35d1fb9eba7b762ed96bf7c16b8 | 14,745 |
def uniform_centroids(dist_map, n_centroids):
"""
Uniformly space `n_centroids` seeds in a naive way
:param dist_map: sparse distance map
:param n_centroids: number of seeds to place
:return: (n_centroids, ) integer arrays with the indices of the seeds
"""
def get_dist(idx_vertex):
... | 437eaf8b70b56379d5529ea30026176fda9049a9 | 14,746 |
import collections
import itertools
def collate_custom(batch,key=None):
""" Custom collate function for the Dataset class
* It doesn't convert numpy arrays to stacked-tensors, but rather combines them in a list
* This is useful for processing annotations of different sizes
"""
# this ca... | b692252cb27aed68cb5af6cd5644913216a8dde7 | 14,747 |
def get_articles(language, no_words, max_no_articles, search, **kwargs):
""" Retrieve articles from Wikipedia """
wikipedia.set_rate_limiting(True) # be polite
wikipedia.set_lang(language)
if search is not None:
titles = wikipedia.search(search, results = max_no_articles)
else:
titl... | d6f2216a0800f6d9627d47ae1acda9e327583841 | 14,749 |
def gen_urdf_material(color_rgba):
"""
:param color_rgba: Four element sequence (0 to 1) encoding an rgba colour tuple, ``seq(float)``
:returns: urdf element sequence for an anonymous material definition containing just a color element, ``str``
"""
return '<material name=""><color rgba="{0} {1} {2} ... | d0fe1a706c932ad1a6f14aa3a9d9471de70650b9 | 14,750 |
def roll_timeseries(arr, timezones):
"""
Roll timeseries from UTC to local time. Automatically compute time-shift
from UTC offset (timezone) and time-series length.
Parameters
----------
arr : ndarray
Input timeseries array of form (time, sites)
timezones : ndarray | list
Ve... | 4715425ea048a1ccb9c5fe2a1dc9e2ea1ecea085 | 14,752 |
def is_linear(a, eps=1e-3):
"""Check if array of numbers is approximately linear."""
x = np.diff(a[1:-1]).std() / np.diff(a[1:-1]).mean()
return x < eps | 0efa5c923012527d4973d24d67871a41ee2e3e91 | 14,753 |
def faces_sphere(src, show_path):
"""
Compute vertices and faces of Sphere input for plotting.
Parameters
----------
- src (source object)
- show_path (bool or int)
Returns
-------
vert, faces (returns all faces when show_path=int)
"""
# pylint: disable=protected-access
... | eb454e55a932aae2f6b0f15587d1aa0be6da80f7 | 14,754 |
import itertools
def pronto_signals_to_iguana_signals(carrier_frequency, signals):
"""Convert the pronto format into iguana format, where the pulses and spaces
are represented in number of microseconds.
"""
return [carrier_cycles_to_microseconds(carrier_frequency, signal) | command
for signal,... | b8ddaf9f573abfe207d2ca2009904a3d93e360a4 | 14,755 |
import collections
import itertools
import pandas
def stack_xarray_repdim(da, **dims):
"""Like xarrays stack, but with partial support for repeated dimensions
The xarray.DataArray.stack method fails when any dimension occurs
multiple times, as repeated dimensions are not currently very well
supported... | 5f0617ccd054c6d11573b00f659308780db4d0d7 | 14,756 |
import math
def compute_pnorm(model: nn.Module) -> float:
"""
Computes the norm of the parameters of a model.
:param model: A PyTorch model.
:return: The norm of the parameters of the model.
"""
return math.sqrt(sum([p.norm().item() ** 2 for p in model.parameters()])) | 610c640902f411221f90c5c7b48d3b3246a60124 | 14,757 |
def atomic_brute_cast(tree: Element) -> Element:
"""
Cast every node's text into an atomic string to prevent further processing on it.
Since we generate the final HTML with Jinja templates, we do not want other inline or tree processors
to keep modifying the data, so this function is used to mark the c... | 57d13b5e97b7f94593f925f745bdf833b15e03a1 | 14,758 |
def rsa_keys(p: int = None, q: int = None, e: int = 3) -> RSA_Keys:
"""
Generate a new set of RSA keys.
If p and q are not provided (<= 1),
then they will be generated.
:param p: A big prime.
:param q: A big prime.
:param e: The default public key.
:return: The RSA private and public ke... | b09fea8b6c23e4709c0f49faf2cb9b20463a2db9 | 14,759 |
def _get_closest_station_by_zcta_ranked(zcta):
""" Selects the nth ranked station from a list of ranked stations
Parameters
----------
zcta : string
ZIP Code Tabulation Area (ZCTA)
Returns
-------
station : string
Station that was found
warnings : list
List of w... | b9cbd7ccc4a22c3069e11bc0542700b8ee087a1c | 14,761 |
def label_matrix(y_true, y_pred, classes,
normalize=False,
title=None,
cmap=plt.cm.Blues):
"""
This function prints and plots the confusion matrix.
Normalization can be applied by setting `normalize=True`.
"""
if not title:
... | 0a1dc4665de4c2b876a0a40d5aa1fcfb1a9113d9 | 14,762 |
import warnings
def lowpass(data,in_t=None,cutoff=None,order=4,dt=None,axis=-1,causal=False):
"""
data: vector of data
in_t: sample times
cutoff: cutoff period in the same units as in_t
returns vector same as data, but with high frequencies removed
"""
# Step 1: Determine dt from dat... | f182fdb912be827d0d8e4fd788cc2cadca453b5a | 14,763 |
def gather_along_dim_with_dim_single(x, target_dim, source_dim, indices):
"""
This function indexes out a target dimension of a tensor in a structured way,
by allowing a different value to be selected for each member of a flat index
tensor (@indices) corresponding to a source dimension. This can be int... | 06fbba5478ddb21cda9a555c41c94c809244537c | 14,764 |
def get_queue(launcher=None):
"""Get the name of the queue used in an allocation.
:param launcher: Name of the WLM to use to collect allocation info. If no launcher
is provided ``detect_launcher`` is used to select a launcher.
:type launcher: str | None
:returns: Name of the queue
... | 56fd4e59877363fd6e889bae52a9b5abf77230f6 | 14,766 |
def get_openmc_geometry(openmoc_geometry):
"""Return an OpenMC geometry corresponding to an OpenMOC geometry.
Parameters
----------
openmoc_geometry : openmoc.Geometry
OpenMOC geometry
Returns
-------
openmc_geometry : openmc.Geometry
Equivalent OpenMC geometry
"""
... | af1eb3cbbcdb4122b28b544bc252f754758ababf | 14,767 |
def distinct(xs):
"""Get the list of distinct values with preserving order."""
# don't use collections.OrderedDict because we do support Python 2.6
seen = set()
return [x for x in xs if x not in seen and not seen.add(x)] | e5dafd942c8aa0314b7e9aa2ec09795796cac34a | 14,768 |
import copy
def _parse_train_configs(train_config):
"""
check if user's train configs are valid.
Args:
train_config(dict): user's train config.
Return:
configs(dict): final configs will be used.
"""
configs = copy.deepcopy(_train_config_default)
configs.update(train_config... | 339539eac9a0463f4fd11d471cfa3f4971010969 | 14,770 |
def as_region(region):
"""
Convert string to :class:`~GenomicRegion`.
This function attempts to convert any string passed to it
to a :class:`~GenomicRegion`. Strings are expected to be
of the form <chromosome>[:<start>-<end>[:[strand]], e.g.
chr1:1-1000, 2:2mb-5mb:-, chrX:1.5kb-3mb, ...
Nu... | 863b1f982e9b411a023ab876661123b5565fae91 | 14,771 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.