content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def get_config(client, config_type, basefolder="/config"):
"""
Return an object that can be used to push/pull configurations inside
an etcd database.
Examples:
import etcd3
import etcdgo
client = etcd3.Etcd3Client()
# push a json configuration inside database
... | db0eabbe025a924a18188cbc02c0fe934531986a | 35,035 |
def get_file_attribute_dtypes(filename):
# type: (str) -> Dict[str, str]
"""
Get the dtypes of the attributes of the file
:param filename:
:return:
"""
with h5py.File(filename, 'r') as infile:
return {key: type(value).__name__ for key, value in infile.attrs.items()} | ae03efa9210f898cf3fc120a87e313c1edbeae6e | 35,036 |
def default_input_format(content_type='application/json', apply_globally=False, api=None):
"""A decorator that allows you to override the default output format for an API"""
def decorator(formatter):
formatter = hug.output_format.content_type(content_type)(formatter)
if apply_globally:
... | 1bbfb2cb23dbb2353804e701938d005aea941e86 | 35,037 |
import inspect
def popargs(*args, **kwargs):
"""A decorator for _cp_dispatch
(cherrypy.dispatch.Dispatcher.dispatch_method_name).
Optional keyword argument: handler=(Object or Function)
Provides a _cp_dispatch function that pops off path segments into
cherrypy.request.params under the names spec... | 9139de9770e5e295656331a31d44ca38d4dcecbc | 35,038 |
def to_pass(line):
"""
Replace a line of code with a pass statement, with
the correct number of leading spaces
Arguments
----------
line : str, line of code
Returns
----------
passed : str, line of code with same leading spaces
but code replaced with pass statemen... | f8444ecc38523aaef13d535258974881956e30b9 | 35,039 |
import numpy
def reverse_sort_C(C, sorted_index):
"""
Perform the reverse of sort described in sort_by_sorted_index, on rows in a numpy array.
Args:
C (numpy.array): array with C.shape[0] = len(sorted_index)
sorted_index (list of ints): desired order for rows of C
"""
m,n = C.shape
C_new = numpy.zeros(C.s... | a0865dba6479104bb1442ea185ec7913ed8cb53c | 35,040 |
def auto_reconnect_connection(func):
"""
Attempt to safely reconnect when an error is hit that resembles the
bouncer disconnecting the client due to a timeout/etc.
"""
@wraps(func)
def inner(self, *args, **kwargs):
try:
return func(self, *args, **kwargs)
except Except... | 88d69a885004d4c683aa653d8c79d43fb9408476 | 35,041 |
def windices_of_references(string, sen_dict):
"""
returns a list of word/sentence indices for all coreferences to
the given string in sen_dict.
returns [(0,0,0)] if there were no coreferences found.
"""
indices = []
coreferences = coreferences_for(string, sen_dict)
if not coreferences:
... | 2bf13beb67aa3e519fb40c06d59a018f89037890 | 35,042 |
def radius(x,y,z,xa,ya) :
"""
Compute distances between the control points (x,y) and a potential center (xa, ya)
in UTM coord, and sort the results depending on the elevation
of the control points (z)
Parameters
----------
x,y,z : UTM coordinates and Elevation of the control point
... | 3bbe20677dfd921c6c6d561f34b76ed54a12d266 | 35,043 |
def remove_labels(data):
"""
Keep only sqrt(n) of the real labels. To find the others, use k=sqrt(sqrt(n))
nearest neighbors from the labels we know, and use the mode.
"""
# "Remove" labels
# lost_idx = np.random.choice(
# len(data.y_train), size=int(len(data.y_train) - np.sqrt(len(data.y... | 4a13ab58309c7ca104375f47c4cdb6dee076fa19 | 35,044 |
import asyncio
async def async_setup(hass, config):
"""Set up the Ais Files platform."""
# register services
@asyncio.coroutine
async def async_transfer_file(call):
if "path" not in call.data or "name" not in call.data:
return
await _async_transfer_file(hass, call.data["pa... | 22bec0569edf73774100b5f8a70dcbd6d6d65de3 | 35,045 |
from typing import Iterable
import itertools
def expand(curr_state: State, params: FindPathParams) -> Iterable[Identifier]:
"""
Expand a state into it's children states
"""
per_agent_expansion = []
for agent in curr_state.identifier.actual:
agent: Agent
# if an agent is colliding... | 1aebb5701b22d26a250aded9ee1e8aede0a87eac | 35,046 |
import time
def SSDR(poses, rest_pose, num_bones, sparseness=4, max_iterations=20):
"""
Computes the Smooth Skinning Decomposition with Rigid bones
inputs: poses |num_poses| x |num_verts| x 3 matrix representing coordinates of vertices of each pose
rest_pose |num_verts| x ... | b4bf6b7d4a6c184b79ad0dcf2122ba31e1faef4f | 35,047 |
import itertools
def string_permutations(test_list, list_to_permutate):
"""Takes a list and a set, and returns a list of all the permutations as strings"""
str_perms = [list(permutation) for permutation in itertools.permutations(list_to_permutate)]
return [str(test_list + str_perm) for str_perm in str_pe... | b4cee2f34e0382a7cd2b49f5b5f22bc85712731a | 35,048 |
def to_cols(d):
"""Make a square matrix with columns equal to 'd'.
>>> print ker.to_cols(np.array([1,2,3,4]))
[[1 1 1 1]
[2 2 2 2]
[3 3 3 3]
[4 4 4 4]]
"""
return np.tile(d.reshape(len(d), -1), (1, len(d))) | 1a5dc76a86d3b5d83b6ac5360af3df041237dbce | 35,049 |
def captured_sensor(hass):
"""Create a captured today ArloSensor."""
data = _get_named_tuple({"captured_today": [0, 0, 0, 0, 0]})
return _get_sensor(hass, "Captured Today", "captured_today", data) | 045b78cf8929517b4f15f479503ed82814182cce | 35,050 |
def create_icon_axes(fig, ax_position, lw_bars, lw_grid, lw_border, rgrid):
"""
Create a polar axes containing the matplotlib radar plot.
Parameters
----------
fig : matplotlib.figure.Figure
The figure to draw into.
ax_position : (float, float, float, float)
The position of the ... | 1ea5e6248ab6b9053afe543d4ed3d8d31ec02d57 | 35,051 |
import time
def baseline_multiclass(train_data, train_labels, test_data, test_labels, args):
"""Train various classifiers to get a baseline."""
clf, train_accuracy, test_accuracy, train_f1, test_f1, exec_time = [], [], [], [], [], []
clf.append(sklearn.neighbors.KNeighborsClassifier(n_neighbors=15, n_jobs... | eb1a63b1921d54faa1141becdcc5d13716b08b7c | 35,052 |
def zeno_data(word: str)->[str]:
"""returns all available zeno data"""
result = [None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None]
for pos in range(zeno.nrows):
if (word == zeno.cell(pos,0).value):
result[0] = zeno.cell(pos,1).value #sfi
... | 12981f05acfe9c7d272f7f907ec0ec51ddcf0d6a | 35,053 |
from operator import index
def transfer():
"""Logic for transferring $$"""
data = decode_url(request.get_data().decode())
otheruser = data.get("name", None)
amount = data.get("amount", None)
if not (otheruser and get_user(otheruser)):
return index(f"Other user is not found")
if not req... | 9afbda60cfb193a2d2852dfdc1accebe6d4fb845 | 35,054 |
from typing import Optional
def get_object_detection_by_id(odid: int) -> Optional[ObjectDetection]:
"""
Gets an object detection by id.
:param odid: The object detection's id.
:return: An object detection or None.
"""
try:
return ObjectDetection.objects.get(id=odid)
except ObjectD... | 3d3605326aa507d856c055edda787d2d407ac673 | 35,055 |
from cacao_accounting.contabilidad.registros.entidad import RegistroEntidad
from cacao_accounting.database import Entidad
def activar_entidad(id_entidad):
"""Estable una entidad como inactiva."""
REGISTRO = RegistroEntidad()
TRANSACCION = obtener_registro_desde_uuid(tabla=Entidad, uuid=id_entidad)
TR... | 10d9da05b464c924471cb316b4b2dbd9e778a79a | 35,056 |
import warnings
def trans_expected(clr, chromosomes, chunksize=1000000, use_dask=False):
"""
Aggregate the signal in intrachromosomal blocks.
Can be used as abackground for contact frequencies between chromosomes.
Parameters
----------
clr : cooler.Cooler
Cooler object
chromosomes... | 809d03501f6d6018da5133b65665f5046be36ca7 | 35,057 |
def exp_trans(base=None, **kwargs):
"""
Create a exponential transform class for *base*
This is inverse of the log transform.
Parameters
----------
base : float
Base of the logarithm
kwargs : dict
Keyword arguments passed onto
:func:`trans_new`. Should not include
... | fbd7ef154be3675d8b7010ae700e5b34d0f398c2 | 35,058 |
def broadcastable_to_str(b):
"""Return string representation of broadcastable."""
named_broadcastable = {
(): "scalar",
(False,): "vector",
(False, True): "col",
(True, False): "row",
(False, False): "matrix",
}
if b in named_broadcastable:
bcast = named_b... | 35dbe968a8341d076a264333c68fb597212439bc | 35,059 |
def avg_weapon_count_character(db):
"""Returns the average number of weapons per character from MongoDB
database.
Args:
db (pymongo.database.Database): MongoDB database
Returns:
(float) Average number of weapons per character
"""
agg_dict = [
{
"$lookup":
... | 0f65cad267d7b1d52730134e98e738dda56b2430 | 35,060 |
def partition(sort_list, low, high):
"""
All the elements smaller than the pivot
will be on the left side of the list
and all the elements on the right side
will be greater than the pivot.
"""
i = (low - 1)
pivot = sort_list[high]
for j in range(low, high):
if sort_list[j] ... | 3ae3a569fc5c3968ae047bf20df7a7a59bdfb0cf | 35,061 |
from argo.workflows.client import ApiClient
from typing import Dict
from typing import Any
def sanitize_for_serialization(obj: Dict[str, Any]) -> Dict[str, Any]:
"""Return object sanitized for serialization.
May be used with a V1alpha1Workflow to sanitize it
back to the original state (i.e. per manifest)... | 5a975e347ee529ac4db7777a0bc31750092f5442 | 35,062 |
def is_valid_degree_sequence(deg_sequence, method='hh'):
"""Returns True if deg_sequence is a valid degree sequence.
A degree sequence is valid if some graph can realize it.
Parameters
----------
deg_sequence : list
A list of integers where each element specifies the degree of a no... | 0ce013847902b002dcde32fbc0e818a5a506028c | 35,063 |
def get_vpc_id(ec2, subnet_id: str = None) -> str:
"""Returns VPC ID that should be used for deployment."""
if subnet_id:
vpc_id = Subnet.get_by_id(ec2, subnet_id).vpc_id
else:
default_vpc = Vpc.get_default_vpc(ec2)
if not default_vpc:
raise ValueError('Default VPC not fo... | b345b840b0efadec62c68f74f4a69fc06c45b81e | 35,066 |
from datetime import datetime
def _get_dates(request):
"""Obtain the start and end dates."""
today = date.today()
date_start = request.POST.get('date_start')
if not date_start:
date_start = today - timedelta(days=1)
else:
date_start = datetime.strptime(date_start, '%Y-%m-%d').date(... | d6313e9175de5e91965d162d066fbbbebe797914 | 35,067 |
import numpy
def detect_model(items: numpy.ndarray) -> int:
"""Detects which logistic model an item matrix fits into.
:param items: an item matrix
:return: an int between 1 and 4 denoting the logistic model of the given item matrix
"""
a, b, c, d = _split_params(items)
if any(d != 1):
... | f24881dd125638bf559e129e2871863ce24fdb91 | 35,069 |
import typing
def split_value(input_val) -> (typing.Union[dict, list], typing.Union[dict, list]):
"""Split input_val into data for params.yaml and zntrack.json
Parameters
----------
input_val: dict
A dictionary of shape {_type: str, value: any} from ZnJSON
Returns
-------
params_... | be858fbfe5e65f02b79d37a54f7fd4d8123d1fc2 | 35,070 |
def assert_http_ok(resp, msg=None):
"""
Ensures the response is returning a HTTP 200.
"""
return assert_equal(resp.status_code, 200, resp.content if msg is None else msg) | 8758d78ed248aa39c92c5aacdda02d9cf3df3fbe | 35,071 |
def segnet_vgg13_bn(pretrained=False, progress=True, **kwargs):
"""Constructs a DeepLabV3+ model with a mobilenet backbone.
"""
model = SegNet(arch='segnet_vgg13_bn', **kwargs)
if pretrained:
state_dict = load_state_dict_from_url(model_urls['segnet_vgg13_bn'], progress=progress)
model.lo... | 512f03e3e24bcfd143caacb77a6619c868738da0 | 35,072 |
def New_Dataframe(old_df,indicator_name):
""" create a new dataframe that is composed of only one indicator
Args:
old_df (dataframe): general dataframe from which we extract the new one
indicator_name (string): Name onf the indicator that will composed the new dataframe
Re... | 5ccd394a01a70b39b64d2a12ed0aac6f39296a0a | 35,073 |
def get_long_description():
"""Compose a long description for PyPI."""
long_description = None
try:
long_description = read_file('README.rst').decode('utf-8')
changelog = read_file('CHANGES.rst').decode('utf-8')
changelog = "\n".join(first_sections(changelog, '=', 4)) + """
Older ver... | 52352c9515f6e04aba2bb85f24a146ca25a42128 | 35,074 |
import re
def _create_matcher(utterance):
"""Create a regex that matches the utterance."""
# Split utterance into parts that are type: NORMAL, GROUP or OPTIONAL
# Pattern matches (GROUP|OPTIONAL): Change light to [the color] {item}
parts = re.split(r'({\w+}|\[[\w\s]+\] *)', utterance)
# Pattern to... | 78b1fc8b2096d5dcc2c2b6dc4112d562b1e365de | 35,075 |
def change_video_state(player_name, state):
"""
:param player_name: video_player or topic_player or live or vr_live or pic_player or local_player
:param state: play or pause
:return:
"""
response = context.agent.call('ChangeVideoState', player_name, state)
if response.name == 'Fail':
... | d0f64b8e1266eed6df31db9ca2b072877f8e3ba9 | 35,076 |
import codecs
def generate(converter, input_file, format='xml', encoding='utf8'):
"""
Given a converter (as returned by compile()), this function reads
the given input file and converts it to the requested output format.
Supported output formats are 'xml', 'yaml', 'json', or 'none'.
:type conve... | 41a0c12387453b2e58972abe3c0f7d505036bb57 | 35,077 |
def compute_SS_TAS(df, cpds_median_score, num_L1000_feats = n_L1000_feats):
"""
Computes both Transcriptional activity score (TAS) and
signature strength per compound based on its replicates across all doses"""
dose_list = list(set(df['dose'].unique().tolist()))[1:7]
for dose in dose_list... | 451fce4e361ac8a6144d2d9aefed949d236f0db2 | 35,078 |
def check_args(args):
"""
Checks validity of command line arguments and, in some cases
modifies them a little bit.
:param args: The command-line arguments.
:type args: argparse.ArgumentParser Namespace
:returns: argparse.ArgumentParser Namespace -- The updated command-line
argumen... | 04270a50fce1003ee3960576b60bdcdc21f69767 | 35,079 |
from aiida.engine import Process
from aiida.orm.utils.node import is_valid_node_type_string
from typing import Tuple
def _get_ormclass_from_cls(cls: EntityClsType) -> Tuple[EntityTypes, Classifier]:
"""
Return the correct classifiers for the QueryBuilder from an ORM class.
:param cls: an AiiDA ORM class ... | c0471544887f614e6d98b90d38c595e0eb3fe5ad | 35,082 |
import warnings
def norm_diff(a):
"""Calculate average of (a[i] - a[i+1]) / (a[i] + a[i+1])."""
if len(a) <= 1:
return np.nan
a = a.astype(float)
if np.allclose((a[1:] + a[:-1]), 0.):
return 0.
norm_diffs = (a[1:] - a[:-1]) / (a[1:] + a[:-1])
norm_diffs[(a[1:] == 0) & (a[:-1]... | 1755b357ad9b84e742e0c432db420df9161d8dc5 | 35,083 |
def expand_batch_dims(structure, batch_sizes):
"""Expands the first dimension of each tensor in structure to be batch_sizes.
Args:
structure: A structure (tuple, namedtuple, list, dictionary, ...).
batch_sizes: A 1-D tensor of shapes describing the batch dims.
Returns:
A structure matching the input ... | 1c72fc555b42d4dbc0f066ba399dc8f4c96b7245 | 35,084 |
def VLBAAIPSName( project, session):
"""
Derive AIPS Name. AIPS file name will be project+session with project
truncated to fit in 12 characters.
* project = project name
* session = session code
"""
################################################################
Aname = Aname=projec... | 1a9009c01f00fbb47d7355fa1b8513177dbd3784 | 35,085 |
import torch
def test_unbalanced_logging_with_multiple_optimizers(tmpdir):
"""This tests ensures reduction works in unbalanced logging settings."""
class TestModel(MultiOptModel):
actual = {0: [], 1: []}
def training_step(self, batch, batch_idx, optimizer_idx):
out = super().tra... | b1c85a2ddba18af5c0e16c35e67a7b1757616805 | 35,086 |
from typing import Optional
def dot_general(lhs: Array, rhs: Array, dimension_numbers: DotDimensionNumbers,
precision: PrecisionLike = None,
preferred_element_type: Optional[DType] = None) -> Array:
"""More general contraction operator.
Wraps XLA's `DotGeneral
<https://www.tenso... | 824edf24f3130de598652e03da3aa2269f9e9b60 | 35,087 |
from typing import Tuple
def random(n: int, area: Tuple[float, float]):
"""
Generate random lines.
By default, 10 lines are randomly placed in a square with corners at (0, 0) and
(10mm, 10mm). Use the `--area` option to specify the destination area.
"""
lines = np.random.rand(n, 2) + 1j * np... | c3cfda6d9ccf133adf494b30d626d55fbb354b6a | 35,088 |
from pathlib import Path
def check_path_in_dir(file_path, directory_path):
"""
Check if a file path is in a directory
:param file_path: Full path to a file
:param directory_path: Full path to a directory the file may be in
:return: True if the file is in the directory
"""
directory = Path(... | 5e96abd89c72ea39a944e75b4548fc20b67892cd | 35,089 |
def trace_eyes(im, wnd_pos, wnd_dim, threshold, image_scale, filter_size, color_invert):
"""
Parameters
----------
im :
image (numpy array);
win_pos :
position of the window on the eyes (x, y);
win_dim :
dimension of the window on the eyes (w, h);
threshold :
... | 651c3a219d9e69d8e261659272f05e6ef9dc2519 | 35,090 |
def get() -> DslContextRegistry:
"""Gets the current active registry that observes DSL definitions."""
return _registry_holder.current | 31029f0996716266e0f14b5155eadf21c3fbd8ad | 35,091 |
def scalebar(length,slon='auto',slat='auto',az=90,label=True,ax=None,**kwargs):
"""
Plot scalebar of given length in meters.
Parameters:
length: Length of scalebar in meters
slon: Starting longitude (decimal degrees) for scalebar
slat: Starting latitude (decimal degrees) for sca... | 1981816449291cf8cf2ffe7a8afef1ea638dac47 | 35,092 |
def to_str(bytes_or_str):
"""
Return Instance of str
"""
if isinstance(bytes_or_str, bytes):
value = bytes_or_str.decode('utf-8')
else:
value = bytes_or_str
return value | 5578e52f72fa5ee5d629748e0388cde4dffe62ee | 35,093 |
def flat_out(f, *a, **kw):
"""Flatten the output of target function."""
return f(*a, **kw).flatten() | ffe09ffbaae93657fde818de8a03cc17fee962f1 | 35,094 |
def delete_question(id):
""" Delete question. """
question = Question.query.get(id)
if question is not None:
question.delete()
response = {"message": "Object deleted."}
return make_response(jsonify(response), 200)
abort(404) | fd826877712efad3ea1344188f4571fd7e6bd9f3 | 35,095 |
def vgg16_cinic10_bn(pretrained=False, progress=True, **kwargs):
"""
VGG 16-layer model (configuration "D") with batch normalization
Inspired by: https://github.com/geifmany/cifar-vgg/blob/master/cifar100vgg.py to follow
https://ieeexplore.ieee.org/stamp/stamp.jsp?arnumber=7486599 and then gave up on Dr... | f7c86108208352dd89b34fb64c7a9875e594e470 | 35,096 |
from .apiv1 import blueprint as api1
def create_app(config_name):
"""
初始化Flask的应用对象,并初始化数据库等内容
:param config_name: str 配置模式的模式的名字 ("develop", "product")
:return:
"""
# 创建app
app = Flask(__name__)
@app.after_request
def after_request(response):
response.headers.add('Acces... | 79288b830a2ec8809253ecf98c1b610e1dce3c52 | 35,098 |
def add_vote_and_redirect(event, _):
"""
Handle add vote requests and redirect to a info page
:param event: event
:return: redirect to a page explaining that the vote was added
"""
# Save the vote
do_vote(event, None)
redirect_url = "/voted"
# Find the user and determine the redire... | 7db963fb8a0f17f7e8221038f70e06f14dd931fd | 35,099 |
import json
def read_json_vectors(filename):
"""Return np array of vectors from json sources"""
vectors = []
with open(filename) as json_file:
json_data = json.load(json_file)
for v in json_data:
vectors.append(v)
print("Read {} vectors from {}".format(len(vectors), filename))
... | 04010096dda8b210fad260ef955ce3c5c393e51a | 35,100 |
from lmfit import Parameters, minimize
from typing import Pattern
def optimize_density_and_bkg_scaling(data_pattern, bkg_pattern, composition,
initial_density, initial_bkg_scaling, r_cutoff, iterations=2,
use_modification_fcn=False):
"""
... | 281c1ec6c57854fcc703ca9d4f1b364cea9ccf98 | 35,101 |
def detail(root, name, my, request, actie="", msg=""):
"""bouw het scherm met actiegegevens op.
de soort user wordt meegegeven aan het scherm om indien nodig wijzigen onmogelijk te
maken en diverse knoppen te verbergen.
"""
## msg = request.GET.get("msg", "")
if not msg:
if request.u... | fd53b4ed2bb860ce20d8c7a6474c6effe5b33a71 | 35,103 |
def define_areas(
pixel_filtered_map: np.ndarray, district_heating_zone_threshold: float
):
"""
This function defines areas where the sum of the pixel values for a given
area exceeds a certain threshold.
Inputs :
* pixel_filtered_map : pixel filtered map (MWh).
* district_heating_zo... | 67d4f4418e5fd456f12454a6de81840da5e8cb39 | 35,104 |
def get_relation(filename):
"""read relation file, return rel2idx"""
rel2idx = {}
f = open(filename, 'r')
lines = f.readlines()
for (n, rel) in enumerate(lines):
rel = rel.strip().lower()
rel2idx[rel] = n
f.close()
return rel2idx | 1c239ec3343cf63e502bf9de485171c9a346e240 | 35,105 |
def id_for_base(val):
"""Return an id for a param set."""
if val is None:
return "No base params"
if "editor-command" in val:
return "Long base params"
if "ecmd" in val:
return "Short base params"
return "Unknown base params" | ecf54fa40195ba4de7db13874e44388a04527bed | 35,106 |
import math
def __bilinear(lat, lon, table):
"""Return bilinear interpolated data from table"""
try:
lat = float(lat)
lon = float(lon)
except ValueError:
return ''
if _non_finite(lat) or _non_finite(lon):
return ''
if math.fabs(lat) > 90 or math.fabs(lon) > 180:
... | 83a665437e4391fd44c87aa8b4631c63c0da4756 | 35,107 |
def serialize_serializable(obj, spec, ctx):
""" Serialize any class that defines a ``serialize`` method. """
return obj.serafin_serialize(spec, ctx) | 936c3b51257c60c156cd9686e38b09ec55a929f2 | 35,108 |
import time
import torch
def train_baseline(train_loader, model, criterion, optimizer, epoch):
"""
:param train_loader: data loader with training images
:param model: model used for training
:param criterion: loss function
:param optimizer: optimizer
:param epoch: current training epoch
:r... | ccac87a4e7a9d43fd5f5f85f00ab4cf797c23def | 35,109 |
def best_match(supported, header):
"""Return mime-type with the highest quality ('q') from list of candidates.
Takes a list of supported mime-types and finds the best match for all the
media-ranges listed in header. The value of header must be a string that
conforms to the format of the HTTP Accept: he... | b7774bcce984dce5d55b5351218ec71163fc5032 | 35,110 |
def hourly_median(hours, series, all_hours=True):
"""
Calculate hourly binned medians of a time series.
Parameters
----------
hours : array_like
Time series of the hour number. Must be of the same length as `series`.
series : array_like
Time series of the data.
all_hours : b... | 7712b425e9445a520eda6bcc8cc18a6ac8274de4 | 35,111 |
def is_orthonormal_direct(basis):
"""
Returns True if the basis is orthonormal and direct:
Parameters
----------
basis
Returns
-------
"""
return is_orthonormal(basis) and np.allclose(
np.cross(basis[0, :], basis[1, :]), basis[2, :]
) | d58f5f9c30ea82d52fd6444febf0515fb99a9147 | 35,112 |
def matlab_style_gauss2D(shape=(3, 3), sigma=0.5):
"""
2D gaussian mask - should give the same result as MATLAB's fspecial('gaussian',[shape],[sigma])
Acknowledgement : https://stackoverflow.com/questions/17190649/how-to-obtain-a-gaussian-filter-in-python (Author@ali_m)
"""
m, n = [(ss - 1.) / 2. fo... | 4be8f129fd7063bc959802e206782bee46310dae | 35,113 |
def triangle2str(idx, triangle):
"""
converts a triangle to a string
"""
return f"shapes[{idx}] = makeShape(" + \
f"materials[{triangle['matid']}]," + \
f"makeTriangle({vec32str(triangle['a'])}," + \
f"{vec32str(triangle['b'])}," + \
f"{vec32str(triangle['c'])}));" | 13761396602855bf38901f5eef365f0bbc2592bf | 35,114 |
import socket
def get_hosts_from_yaml(test_yaml, args, key_match=None):
"""Extract the list of hosts from the test yaml file.
This host will be included in the list if no clients are explicitly called
out in the test's yaml file.
Args:
test_yaml (str): test yaml file
args (argparse.N... | 4dce69fe52769972c396208859d9cc5cfe4cf64a | 35,115 |
def parse_labels_mapping(s):
"""
Parse the mapping between a label type and it's feature map.
For instance:
'0;1;2;3' -> [0, 1, 2, 3]
'0+2;3' -> [0, None, 0, 1]
'3;0+2;1' -> [1, 2, 1, 0]
"""
if len(s) > 0:
split = [[int(y) for y in x.split('+')] for x in s.split(';')]
e... | d2f77876f1759e6d4093afc720e7631f1b4d9ff4 | 35,116 |
from typing import Optional
from typing import Any
from typing import Dict
def sraa_eedi3(clip: vs.VideoNode, rep: Optional[int] = None, **eedi3_args: Any)-> vs.VideoNode:
"""Drop half the field with eedi3+nnedi3 and interpolate them.
Args:
clip (vs.VideoNode): Source clip.
rep (Optional[int]... | 24f5bcaedbd16fe0feabfb589fdf4244554888ae | 35,117 |
from typing import Any
import dataclasses
def _is_nested(x: Any) -> bool:
"""Returns whether a value is nested."""
return isinstance(x, dict) or dataclasses.is_dataclass(x) | 798000adfd8eb900b61be988ab6a31e1b062540d | 35,118 |
import math
def pedel(lsize, seq_len, mps, dist_fx=poisson):
"""
Pedel calculates library diversity given library size and mutational load.
For poisson distribution use poisson (default).
For pcr distribution, use first pcr_distribution_factory(efficiency, cycles) to obtain a function specific to thos... | d5f75a1032272961a407dc7f02292e3095966281 | 35,119 |
def contains_pept(name):
"""Checks if the saccharide name contains the peptide fragment,
such as EES, GS, SA etc"""
contains_pept = False
for pept_stub_name in ('_E', '_G', '_S', '_A'):
if (pept_stub_name in name) and ('_NRE' not in name):
contains_pept = True
return contains... | 937679a96b21766e96eb455baca51c1695412287 | 35,120 |
import torch
def check_stacked_complex(data: torch.Tensor) -> torch.Tensor:
"""
Check if tensor is stacked complex (real & imag parts stacked along last dim) and convert it to a combined complex
tensor.
Args:
data: A complex valued tensor, where the size of the final dimension might be 2.
... | afce7ac1840ff64199c9ebc9f4222e1d3f09dafd | 35,121 |
def circle(x, y, a, b, width):
"""
widthで指定された直径の中に含まれているかを判定
:param x:
:param y:
:param a:
:param b:
:param width:
:return:
"""
_x = round(((x - a) ** 2), 3)
_y = round(((y - b) ** 2), 3)
_r = round(((width/2) ** 2), 3)
if (_x + _y) <= _r:
return _r - (_x + _... | fabddad9e3c404dc36e1cf1830ebcc107cf66516 | 35,122 |
def fetch_representative_points(
service_area_ids,
include_census_data,
engine=connect.create_db_engine()
):
"""
Fetch representative points for a list of service areas.
Prepares responses for use by the frontend.
"""
if not service_area_ids:
return []
query_params = {
... | daec38168159c537454d55696f6bcac72799b586 | 35,123 |
def get_most_similar(candidates, target_val, endpointService):
"""
select the entity from candidates that are most similar to the original one
ties are broken by overall popularity
"""
closest_dist = float('inf')
closest_matches = []
target_val = target_val.lower()
for cand in candidat... | 0f4c99e0ed9428160880a778385c35597732b322 | 35,124 |
def dict_remove_none(starting_seq=None, extend_chained=True, chained=None, chained_status=None):
"""
Given a target sequence, look for dictionary keys that have values of None and remove them.
By default, ``chained`` will have ``.extend()`` or ``.update()`` called on it with
``starting_seq`` as the onl... | ce43ce9cdfff92fcce329b50cf25aeb8f74b6ff5 | 35,125 |
import requests
def get_scoped_token(os_auth_url, access_token, project_id):
"""
Get a scoped token, will try all protocols if needed
"""
unscoped_token, protocol = get_unscoped_token(os_auth_url, access_token)
url = get_keystone_url(os_auth_url, "/v3/auth/tokens")
body = {
"auth": {
... | 1ebeeb09e90ae6ad6091ef2623c9be59b27a22d5 | 35,126 |
def split_feature_class(label: str, frame: pd.DataFrame):
""" Split features and class from encode dataset. `label` is the class, and
`frame` is the dataset which has been encoded.
"""
sub_cols = [attr for attr in frame.columns if attr.startswith(label)]
if len(sub_cols) <= 1:
return frame, ... | 03cd3b4f3c2909aaf03ec8832bb7a543a6c1f789 | 35,130 |
def user_form_test(): # <dev>
"""recommender user form.
Returns:
request: dictionary (json object)
list of user's strain description
schema:
{"type_list": [""],
"effect_list": [""],
"flavor_list": [""]}
"""
return render_template("index.h... | 3f853f197ffa7d879af77a6c1777ec6f9ea394dc | 35,131 |
def bestfit_sphere_numpy(points):
"""Returns the sphere's center and radius that fits best through a set of points.
Parameters
----------
points: list of points
XYZ coordinates of the points.
Returns
-------
tuple: center, radius
sphere center (XYZ coordinates) and sphere r... | 52cee41806ef1ea7dc5c3b3c00109ab686b606cd | 35,132 |
import numpy
def absupearson(a,b,weights):
"""Distance between two points based on the pearson correlation coefficient.
By treating each data point as half of a list of ordered pairs it is
possible to caluclate the pearson correlation coefficent for the list. The
correlation coefficent is then ... | 7bc70816f96a8bd90a424eb7ca13fd291d086b06 | 35,133 |
def plot_met(data_df: pd.DataFrame, data_interp_df: pd.DataFrame, met_selection: list, scaled_conc: bool = False,
x_scale: str = 'linear', y_scale: str = 'linear', x_lim: tuple = (10 ** -10, 1), y_lim: tuple = None):
"""
Plots a given metabolite across all models in altair. Uses line plots.
Ar... | cad99c352a4c04a1a9492811bb79fa61853fb25a | 35,134 |
def get_page(db: Session, name: str) -> models.Page:
"""
Get the page with the given name.
:param db: The db session to check.
:param name: The name of the page to find.
:return: The desired page in the db, or None if DNE.
"""
return db.query(models.Page).filter(models.Page.name == name).fir... | f4fb59efe5dc68260e9a261858e77a9e946502f8 | 35,136 |
from typing import Tuple
def _dbms_utility_name_resolve(
connection: oracle.Connection, name: str, context: int
) -> Tuple[str, str, str, str, int, int]:
"""Wrapper for Oracle DBMS_UTILITY.NAME_RESOLVE procedure"""
with connection.cursor() as cursor:
schema = cursor.var(str)
part1 = cursor... | 43bdf191c8f7b296cbac93f9d63a405a7f0f1115 | 35,138 |
def func_call(instance: ARIA, func_name: str, command_name: str, demisto_arguments: list, args: dict):
""" Helper function used to call different demisto command
Args:
instance: An ARIA instance.
func_name: Name of the functions in the ARIA class.
command_name: Related demisto command n... | 2d55693c7df9179f4771717ed00da45ea74f2d1d | 35,139 |
def admin_role_required(f):
"""
Grant access if user is in Administrator role
"""
@wraps(f)
def decorated_function(*args, **kwargs):
if g.user.role.name != 'Administrator':
return redirect(url_for('error', code=401))
return f(*args, **kwargs)
return decorated_function | e0f67f97339af3867227f9507047e240fea43eaa | 35,140 |
def format_location_detail_tract(data):
"""Reformat the list of data to Location Detail format for tract
Args:
data (list): A list of FSF object
Returns:
A pandas formatted DataFrame
"""
df = pd.DataFrame([vars(o) for o in data])
df.rename(columns={'fsid': 'fsid_placeholder'}, i... | 3d99e5790aab8e3031494fac824dd5425acf2463 | 35,141 |
from typing import List
def pgcdDesDistancesEntreRepetitions(crypted: List[int], i: int) -> int:
"""
Returns pgcd{ }
"""
assert 0 <= i < len(crypted) - 2, "i must be in [0, len(crypted)-2)"
search_for = crypted[i:i+2+1]
current_pattern: List[int] = []
distances: List[int] = []
for i, ... | 7843c9d86f5dc0a28793cb6158261cdb9425df84 | 35,142 |
import numpy
def preprocess(simulation, field):
"""
Store DOF and geometry info that will not change unless the mesh is
updated (which is not handled in any way)
"""
mesh = simulation.data['mesh']
dofmap = field.function_space().dofmap()
conFC = simulation.data['connectivity_FC']
# Da... | 552cba3b5c092ea530f2089ec8252991349a0853 | 35,143 |
def drop_probable_entities(X):
"""
:param X: a data matrix: a list wrapping a list of strings, with each sublist being a sentence.
:return:
>>> drop_empty_lists(drop_arabic_numeric(drop_probable_entities([['Catullus'], ['C.', 'VALERIVS', 'CATVLLVS'],['1','2', '2b', '3' ],['I.', 'ad', 'Cornelium'],['Cui... | 18e21d21212d56e256fd015f9513e06b31ed1027 | 35,144 |
def wrong_obj_msg(*objs, allow="sources"):
"""return error message for wrong object type provided"""
assert len(objs) <= 1, "only max one obj allowed"
allowed = allow.split("+")
prefix = "No" if len(allowed) == 1 else "Bad"
msg = f"{prefix} {'/'.join(allowed)} provided"
if "sources" in allowed:
... | 09294ccc6da5f02718edbdc2e04c8a92f213eb4a | 35,145 |
def text2haiku(text, keep_chance=0.75, iterations=2000):
"""
Given a string of text, try to make a haiku
returns a haiku as a string or None if it fails
"""
word_list = text_to_word_list(text)
haiku = bagging_haiku_maker(word_list, keep_chance=keep_chance, iterations=iterations)
return haiku | 759e6a94698e252f2df29911700a9fa6b945e61d | 35,146 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.