content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
import scipy
def sortedEig(X,M=None,k=None, lambda0=0):
"""
Return the k largest eigenvalues and the corresponding eigenvectors of the
solution to X*u = b*M*u
Inputs:
X: matrix
M: matrix
k: (int) if k is None, return all but one.
lambda0: (float) regularization parameter to ensur... | 957c36b625d2e7676123547e49b9a8d3e2ba48d2 | 34,803 |
from typing import List
def _fourier_transform_multi_fermionic_mode(
n: int, amplitude: complex, modes: List[int]) -> np.ndarray:
"""Fermionic Fourier transform of a multi Fermionic mode base state.
Args:
n: State length, number of qubits used.
amplitude: State amplitude. Absolute val... | a4983387f622f450d31e25ba1a30027eda9d99c5 | 34,804 |
def get_metric_parser(op):
"""Return a function which can parse a line with this operator."""
return {
OP_START_TIMER: parse_timer,
OP_STOP_TIMER: parse_timer,
OP_NAMED_EVENT: parse_named_event,
OP_GAUGE: parse_gauge,
}[op] | b78272c9f70318bc76d43ccaf03df294cc2de4ea | 34,805 |
def parse_division(l, c, line, root_node, last_section_node):
"""
Extracts a division node from a line
:param l: The line number (starting from 0)
:param c: The column number
:param line: The line string (without indentation)
:param root_node: The document root node.
:return: tuple(last... | 376322fa8678f5440a96caaa7f3b4f968e4f24de | 34,806 |
def diff_eqs(INP, t):
"""The main set of equations"""
Y = np.zeros((2))
V = INP
Y[0] = gamma * (N0 - V[0]) - tau * V[1]
Y[1] = (
tau * (n - 1) * (n * V[0] - V[1]) * V[1] / (n * V[0])
+ gamma * (n * N0 - n * V[0] - V[1])
- tau * V[1]
- tau * (n - 1) * V[1] * V[1] / (n ... | 6736fab5d0f1c54a0d44cb64af85fca31f4b18dd | 34,807 |
from datetime import datetime
def register():
"""
Функция регистрации пользователя
:return: Страницы Login или Register
"""
if request.method == "POST":
# Достаем из формы данные пользователя
username = request.form["FirstName"]
lastname = request.form["LastName"]
... | 6663508e40746484c96bb789ae091ba2c7a6662b | 34,808 |
from pathlib import Path
import re
def get_detectron2_current_version():
"""Version is not available for import through Python since it is
above the top level of the package. Instead, we parse it from the
file with a regex."""
# Get version info from detectron2 __init__.py
version_source = (Path(_... | 52b7717fdee1fc64b7e8c3d4d3aa074373fcffb6 | 34,809 |
def accuracy_score(y_true, y_pred, *, normalize=True, sample_weight=None):
"""Accuracy classification score.
In multilabel classification, this function computes subset accuracy:
the set of labels predicted for a sample must *exactly* match the
corresponding set of labels in y_true.
Read more in the... | 306b7095ec02e4192cf7de76aa31fb8503ce0a9f | 34,810 |
def aspect_ratio(bbox, ratios):
"""
Enumerate box for each aspect ratio.
Args:
bbox (:py:class:`BBox2D`): 2D bounding box.
ratios (:py:class:`list`): list of int/float values.
"""
cx, cy = bbox.center()
w, h = bbox.w, bbox.h
size = w * h
ratios = np.asarray(ratios, dtyp... | 73ce16b3ed755bb07e680ab5626fb2b160b4aa53 | 34,811 |
def str2bool(value):
"""
Convert CLI args to boolean
:param str value:
:return bool:
"""
if value.lower() in ("yes", "true", "t", "y", "1"):
return True
elif value.lower() in ("no", "false", "f", "n", "0"):
return False
else:
raise ArgumentTypeError("Boolean value... | 5b204bb20913f0214048a8332229b80017c7a701 | 34,812 |
def layernorm_cx(cx, w_in):
"""Accumulates complexity of layernorm into cx = (h, w, flops, params, acts)."""
h, w, flops, params, acts = cx["h"], cx["w"], cx["flops"], cx["params"], cx["acts"]
params += 2 * w_in
return {"h": h, "w": w, "flops": flops, "params": params, "acts": acts} | 97ffd7678c3d4d3fbbf63b6717fe3cc11823c230 | 34,814 |
async def _get_privileges(user_id: int, chat_id: int) -> Privileges:
"""
Check user access
:param user_id: user id
:param chat_id: access chat id
:return: privileges
"""
bot = Bot.get_current()
chat_member = await bot.get_chat_member(chat_id, user_id)
if chat_member.is_chat_admin():
... | 421cfeb48c2a1a4bfd8d0240d4f7c3acc25bb856 | 34,815 |
def sso_login_url(service):
"""Get SSO login url for service"""
app_config = current_app.config
login_host = app_config.get('SSO').get('HOST')
sso_redirect_url = app_config.get(f'SERVER_{service}_DOMAIN_NAME')
query = urlencode({
'service': service,
'redirect_url': f'https://{sso_red... | 28828ab734d95304e60b13812de4550587f577d9 | 34,817 |
def get_config():
"""Default configuration for the Harvest level."""
config = config_dict.ConfigDict()
# Basic configuration.
config.individual_observation_names = ["RGB"]
config.global_observation_names = ["WORLD.RGB"]
# Lua script configuration.
config.lab2d_settings = {
"levelName": #
... | 8cfbac7ebe371278332e7d71f7f89b02f701b59b | 34,819 |
def evaluate_regression_error(predicted_output, true_output,
norm=norms.euclidean_2):
"""Calculate the error with respect to a norm of regression output.
Parameters
----------
predicted_output : numpy.ndarray
The predictions made by the classifier.
true_output... | 243bc61234f20995a8db765653bd37cf7d3f8e40 | 34,820 |
def classify(character: str) -> int:
"""String classifier."""
if character.isupper():
return StringType.UPPER
if character.islower():
return StringType.LOWER
if character.isnumeric():
return StringType.NUMERIC
return StringType.OTHER | a17af3771bc2d1dd51ea735bcc78f856a01df5cd | 34,821 |
import json
def getGold(session, city):
"""
Parameters
----------
session : ikabot.web.session.Session
city : dict
Returns
-------
gold : int
"""
url = 'view=finances&backgroundView=city¤tCityId={}&templateView=finances&actionRequest={}&ajax=1'.format(city['id'], actionRe... | e312f7bda229340ec3709f025ae33194909e82ee | 34,822 |
from typing import Iterable
from typing import Mapping
def _iter_but_not_str_or_map(maybe_iter):
"""Helper function to differ between iterables and iterables that are
strings or mappings. This is used for pynads.concrete.List to determine
if an iterable should be consumed or placed into a single value tup... | 3dab46cfd2d2d19bd0fa744370b9059d6a0683bc | 34,823 |
def interrogate_decision_tree(wxtree):
"""
Obtain a list of necessary inputs from the decision tree as it is currently
defined. Return a formatted string that contains the diagnostic names, the
thresholds needed, and whether they are thresholded above or below these
values. This output is used to cr... | 14ac92c25bccd8c549de6d7a5bbf696e18c1e47e | 34,824 |
def script_resolve_name(script_name, name):
"""
Name resolver for scripts. Supports ROS_NAMESPACE. Does not
support remapping arguments.
@param name: name to resolve
@type name: str
@param script_name: name of script. script_name must not
contain a namespace.
@type script_name: str
... | 38e0be53417719bc9521b80a4621b3127aab1749 | 34,825 |
def offbyKExtra(s1,s2,k):
"""Input: two strings s1,s2 and integer k
Process: to check if number of extra characters in s2 as compared to s1
(or vice versa) is equal to k
Output: return True when above condition is met otherwise return False"""
flag=0
extra1=''
if len(s1)>len(s2):
for... | 10cb2480c95a729aceb219e14999dcbcf0cad1eb | 34,826 |
def Optimizer(Efunc,x0,method='L-BFGS-B',jac=None,optns={}):
"""
Efunc(x,count)
See the scipy.optimize.minimize manual for options
"""
const.CONSOLEMESSAGE('Entered in lib.Optimizer')
methlst=['Nelder-Mead','Powell','CG','BFGS','Newton-CG','Anneal','L-BFGS-B',
'TNC', 'COBYLA', ... | 2fe2ff9263a0cb0662c30a47b90e089b92988ad2 | 34,828 |
def plot_feature_calibrator(model_graph,
feature_name,
plot_submodel_calibration=True,
font_size=12,
axis_label_font_size=14,
figsize=None):
"""Plots feature calibrator(s) extrac... | 16576f1497937fb04be2d7fea17b578177564f65 | 34,829 |
def calc_reg_cdd(
temperatures,
t_base_cooling,
model_yeardays,
crit_temp_min_max=False
):
"""Calculate CDD for every day and daily yd shape of cooling demand
Arguments
----------
temperatures : array
Temperatures
t_base_cooling : array
Base tempe... | 62699977be16efbdd511e987e736822fca6a82c3 | 34,830 |
def get_number_of_polymorphic_sites(pileup):
"""
# ========================================================================
GET NUMBER OF POLYMORPHIC SITES
PURPOSE
-------
Returns the number of polymorphic sites.
INPUT
-----
[PILEUP] [pileup]
A Pileup object, which rep... | e388b20f500b141da0eedc54616703c6e444de8a | 34,831 |
def test(sess, evaluate, ph, dataset, testmodel):
"""Apply the models."""
## word model
acc = Accuracies()
out_sentences = []
results_w = []
for f_word in dataset.batches:
batch_values, out_logits_w_out_w = sess.run(
[testmodel.predictions_w, testmodel.out_logits_w],
feed_dict={ph.inputs... | 03f2035e90f1facce191548b061c7407d9715ab7 | 34,832 |
def _compile_rules(rules_file, externals, cur_logger):
"""
Saves Yara rule content to file, validates the content with Yara Validator, and uses Yara python to compile
the rule set.
Args:
rules_file: Yara rule file content.
Returns:
Compiled rules, compiled rules md5.
"""
tr... | dcad814fc91ae577952a926021dbfb71ae638080 | 34,833 |
async def hello(request):
"""Test webserver request."""
return web.Response(text="Hello, world") | d8a68eb12fd094a5beed0610d8601ea63334aaab | 34,834 |
def user_save(form, is_patient=False, is_office=False):
"""Function saving the user to the database."""
user = form.save(commit=False)
# The account is not active until the user activates it.
user.is_active = False
user.is_patient = is_patient
user.is_office = is_office
user.save()
retur... | 8ce0a7af24bc72da98c015d0e9f7545069bbce19 | 34,836 |
def int_divmod(context, builder, ty, x, y):
"""
Integer divmod(x, y). The caller must ensure that y != 0.
"""
if ty.signed:
return int_divmod_signed(context, builder, ty, x, y)
else:
return builder.udiv(x, y), builder.urem(x, y) | 93fa13c703a9419ea9a5926f32a69a7269d57fd9 | 34,837 |
def initial_state(layer, dimensions=None):
"""
Initalizes the recurrence relation with an initial hidden state
if needed, else replaces with a "None" to tell Theano that
the network **will** return something, but it does not need
to send it to the next step of the recurrence
"""
if dimension... | 3788adbe14604d50b5aa9701616f3bdaa5af94a7 | 34,838 |
def lin_smooth(x, window_len=15, window='hanning'):
"""
Smooth the data using a window with requested size.
This method is based on the convolution of a scaled window with the signal.
The signal is prepared by introducing reflected copies of the signal
(with the window size) in both ends so that tr... | a1a5a5c0ab76a4b38007947cc161fbcf0bc90dd9 | 34,839 |
def product_details(request, id):
""" The view rendering the page for one selected
product and all of its details """
selected_product = get_object_or_404(Product, id=id)
# get existing number of views, increment and update model
number = selected_product.num_of_views + 1
Product.objects.fi... | d567b378286a19bdc70442f18e65922912aa7c67 | 34,840 |
def compute_colors_for_labels(labels):
"""Simple function that adds fixed colors depending on the class
"""
palette = np.array([2 ** 25 - 1, 2 ** 15 - 1, 2 ** 21 - 1, 1])
colors = labels[:, None] * palette
colors = (colors % 255).astype("float")
colors /= 255
colors[:, -1] = 1
return colors | 5ce1dc5a43d94a7bd316137b217c32cec9fab355 | 34,841 |
def vms_ajax_revoke_ip(request, vm_id, template_name='generic/form.html', form_class=RevokeIPForm):
"""
Ajax view for detaching elastip IP from a virtual machine.
"""
rest_data = prep_data({'vm': ('user/vm/get_by_id/', {'vm_id': vm_id})}, request.session)
if request.method == 'POST':
form =... | 8ae82abbde4a883673b376af05820dd882813f96 | 34,843 |
import hashlib
def make_message_hash(msg, include=(), exclude=()):
"""
Returns hashcode for ROS message, as a hex digest.
@param include message fields to include if not all, as [((nested, path), re.Pattern())]
@param exclude message fields to exclude, as [((nested, path), re.Pattern())]
... | 325d5d0bd5d8d5f05ecfcc6983425ac121fbbea3 | 34,844 |
def non_overlap_df(input_df: pd.DataFrame) -> pd.DataFrame:
"""
Args:
input_df: DataFrame with possibly overlapping calls
Returns: a DataFrame object with non-overlapping calls (after merge).
"""
non_overlap = []
for file_name, file_df in input_df.groupby(by='filename'):
file_df... | 8753f0c3f28d3b9e31b415c7a4d05aab22001df1 | 34,845 |
import prometheus_client
def benchmark_last_result(project,benchmark):
"""
Get latest benchmark result from Victoria Metrics
Returns "-1" if result not found
"""
query = f"last_over_time(parity_benchmark_common_result_ns{{project=\"{project}\",benchmark=\"{benchmark}\"}}[1y])"
query_result = p... | 9e7db0dda645f977fab85a98e9efdfbc7c6683be | 34,846 |
def get_lambda_config(module, aws):
"""
Returns the lambda function configuration if it exists.
:param module: Ansible module reference
:param aws: AWS client connection
:return:
"""
client = aws.client('lambda')
# set API parameters
api_params = dict(FunctionName=module.params['f... | 509db0f745a3aeaea07722f1135a339d720cabdc | 34,847 |
def standard_deviation(lst, population=True):
"""Calculates the standard deviation for a list of numbers."""
num_items = len(lst)
mean = sum(lst) / num_items
differences = [x - mean for x in lst]
sq_differences = [d ** 2 for d in differences]
ssd = sum(sq_differences)
if population is True... | 7f15f6d80adf722912cba49c3dfad9b40e2f3b2a | 34,848 |
def solve(global_step):
"""add solver to losses"""
# learning reate
lr = _configure_learning_rate(82783, global_step)
optimizer = _configure_optimizer(lr)
tf.summary.scalar('learning_rate', lr)
# compute and apply gradient
losses = tf.get_collection(tf.GraphKeys.LOSSES)
loss = tf.add_n(... | e26ccdcfef8eadc7f0335ff4d36e29158c85134b | 34,849 |
def group_points_into_lines(edges, x_coords, y_coords, x_size=10, y_size=3):
"""
Группирует отдельные точки в линии при помощи функции connect_line
:param edges:
:param x_coords:
:param y_coords:
:param x_size:
:param y_size:
:return:
"""
point_dict = {(x_, y_): i for i, (x_, y_)... | dd505f739b83aef2bf91f0eb816e86c1bb7df997 | 34,850 |
def start(image):
"""Function to find start point of the Non - White pixel"""
for i in range(image.shape[0]):
if 0 in image[i]:
return i | 504b3cfc90610f34ce1ee6791dcf4c8139f06fe8 | 34,851 |
def ip4_bytes_to_str(ip_bytes):
"""Convert ip address from byte representation to 127.0.0.1."""
return "%d.%d.%d.%d" % unpack_ipv4(ip_bytes) | feb662972ff8d808dfeb0794cc9bfb443234fbe6 | 34,856 |
def BuildTelemax(x: int, c: int) -> str:
"""
utility fct to build Telemax Pointage
"""
msg = '123456MAC:4c24e9870203PROT005170817100*Q:'
msg += str(x + c + 1).zfill(6)
msg += '9103'
msg += '0071'
msg += '0093'
msg += '2 '
msg += '0'
# msg += 'xx'
msg += '10020100^1*'
... | ba5d51cc6e7463d693f74eb618471fb23a62b6a9 | 34,857 |
from typing import Tuple
from typing import cast
def create_ephemeral_key_pair(curve_type: str) -> Tuple[PublicKey, SharedKeyGenerator]:
"""Facilitates ECDH key exchange."""
if curve_type != "P-256":
raise NotImplementedError()
key_pair = create_new_key_pair(curve_type)
def _key_exchange(ser... | ada825897fec2c818835f4d70298cf571ab79183 | 34,859 |
from typing import Dict
from typing import Any
def get_unlisted_livestreams_by_username(username: str) -> Dict[str, Any]:
"""Get a user's unlisted livestreams from their username.
Args:
username (str): The user's username.
Returns:
Dict[str, Any]: The unlisted livestream.
"""
ite... | 53a9ac945457eaa4b4418605670b13db90e201b7 | 34,860 |
async def async_setup_entry(
hass: HomeAssistantType, entry: ConfigEntry, async_add_entities
) -> None:
"""Add a weather entity from mapped location."""
fcst_coordinator = hass.data[DOMAIN][entry.entry_id]["fcst_coordinator"]
if not fcst_coordinator.data:
return
cur_coordinator = hass.data... | 526bea80afeaa4f6c91db6d2de91f625bc5e4bcd | 34,861 |
def parse_sync_agent_forwarder_id(json):
"""
Extract the sync agent forwarder id from the get response of LearningLocker.
:param json: JSON statement from the get response.
:type json: dict(str, list(dict(str, str))
:return: The statement forwarder id from the sync agent.
:rtype: str
"""
... | 4b07dc13ca978cfc3fad46e432c8c21d46ee53fa | 34,862 |
import numpy
def generate_lineal_parameter(parameter_values):
"""Generate parameters list for lineal parameter type."""
initial_value = parameter_values['initial_value']
final_value = parameter_values["final_value"]
interval = parameter_values["interval"]
param_options = numpy.arange(
... | 6359a0c93c07aa3dfeba096501b73f69fb3b02f9 | 34,863 |
def get_plugin_arguments(plugin_name):
"""Gets plugin arguments, as a dict of version to argument list."""
plugin = plugins_base.PLUGINS.get_plugin(plugin_name)
versions = plugin.get_versions()
return {version: plugin.get_image_arguments(version)
for version in versions} | ad056ecccc5ac40120493245709235b6587955b5 | 34,864 |
import re
def to_snake_case(s):
"""Convert a string to snake-case format
Parameters
----------
s: String
String to convert to snake-case
Returns
-------
String
Snake-case formatted string
Notes
-----
Adapted from https://gist.github.com/jaytaylor/3660565
... | cf3ca065c471ed526ab15de5d6c07e9be74ddb59 | 34,865 |
def get_var(name, program=None):
"""
Get a variable by name from the global block of a program
Args:
name(str): name of the variable
program(Program|None): program object.
If None, default_global_program() will be used.
Returns:
Variable
"""
if program is No... | 7f6bca1482834b1688175b6508fa269cfcee882a | 34,866 |
def _update_cluster_config(cluster, session=None, user=None, **kwargs):
"""Update a cluster config."""
check_cluster_editable(cluster, user=user)
return utils.update_db_object(
session, cluster, **kwargs
) | fe7e2f099f2719385ccde62aa94c71f2c91fbf85 | 34,867 |
def read_file(file_path="data/short.list"):
"""
Reads file, short.list by default.
"""
data = ""
with open(file_path, "r", encoding="utf8", errors="ignore") as file:
data = file.read().split("\n")[14:-1]
return tuple(set(data)) | f2ced72bfa6328c6794b629d043b837144304716 | 34,868 |
import torch
def sample(lnprobs, temperature=1.0):
"""
Sample an element from a categorical distribution
:param lnprobs: Outcome log-probabilities
:param temperature: Sampling temperature. 1.0 follows the given distribution,
0.0 returns the maximum probability element.
:return: The index o... | 62ef43b30ffd9c6fac4254074d7b740cbfc01987 | 34,870 |
import pprint
import logging
def get_submit_input_metadata(body):
"""
Extract relevant metadata from the body message included with a submit
input action.
:param body: (dict) the body of the json payload, including details
about the message and the button clicked
:returns: user_i... | 7d26392d54c9996a48965fa696a9243f5ea85716 | 34,871 |
def connection_is_established():
"""
Function to check if a connection to the remote server has been established
"""
return (not _remote_client is None) | 8ea9583b6585e8af57f775d8ce974dbdaf85197f | 34,872 |
def getLanguage(langcode):
"""Returns the full name of the language referred to by its two-letters
language code.
"""
if languages.has_key(langcode):
return languages[langcode]
else:
raise RuntimeError("cannot find language with code " + str(langcode)) | 777c069f24f92ff9b2f65413535bc38c4be57865 | 34,873 |
import json
def get_images(username):
"""
Retrieves image history for given username
:return: resp: (json) All the pathways to the images the user has previously uploaded
"""
resp = []
for image in ImPath.query.filter_by(username=username):
if (is_valid_image_path(image.impath)):
... | cdf5ed91d0c88065d07e0c992dc460f6555ee8ef | 34,874 |
def otf2psf(otf, shape):
"""
Convert optical transfer function (OTF) to point-spread function (PSF).
Compute the Inverse Fast Fourier Transform (ifft) of the OTF array and
creates the PSF array that is not influenced by the OTF off-centering.
By default, the PSF array is the same size as the OTF arr... | b3a142d26b15951c32e5c2e10aaba69ac9552fc8 | 34,875 |
def inventreeInstanceName():
""" Returns the InstanceName settings for the current database """
return InvenTreeSetting.get_setting("InstanceName", "") | 7c57f2156b69b8a0155ce168921132863483824f | 34,876 |
def predict(sentence: str) -> [str]:
"""
Lemmatize a given sentence
:param sentence: sentence to lemmatize
:return: lemmatized sentence
"""
lemmatizer = WordNetLemmatizer()
word_list = nltk.word_tokenize(sentence)
return [lemmatizer.lemmatize(w) for w in word_list] | b9b11cbb7d540fc517d9888f9e2449e3773617f4 | 34,877 |
def is_nominal_tolerance_met(data : pd.DataFrame, criteria_nominal : list = [], nominal_tolerance : list = []):
"""
Checks that the tolerances for categorical columns are met. The tolerance is defined as the sum of the maximum frequency deviation
between groups for each categorical column passed in criteri... | 03a432010f1ca46b6d80d491f76fa9acf3e2aa91 | 34,878 |
def test_limit_by_resource_and_method():
""" Test using a custom key_func - one which creates different buckets by resource and method
"""
def get_key(req, resp, resource, params) -> str:
user_key = get_remote_addr(req, resp, resource, params)
return f"{user_key}:{resource.__class__.__name_... | b20492c686411a5d7db13959a7745bade605d1d1 | 34,880 |
def pdoo_wrap(doo_obj, total_budget, nu_max=1.0, rho_max=0.9, K=2, C_init=0.8, tol=1e-3,
POO_mult=0.5, Randomize=False, return_history=False):
""" Wrapper for running PDOO optimisation. """
# pylint: disable=too-many-locals
total_budget = total_budget * doo_obj.eval_cost_single_point_normalise... | 0d06a400a62021cf4c6f1f91ed3bc547ce822ca9 | 34,881 |
def chi2(sp, pars):
"""
Given a spectrum and some parameters, calculate the chi^2 value
"""
pars = list(pars) + [0]
return ((sp.specfit.get_model_frompars(sp.xarr, pars) -
sp.specfit.spectofit)**2 /
(sp.specfit.errspec**2)
).sum() | ce8c6362eb88dfce17dc56414e3bed4f67ec6ffa | 34,882 |
def cartesian2spherical(xyz):
"""
Transform cartesian coordinates (x, y, z)
in spherical coordinates. The function only returns
the (theta, phi) pair since
the magnetisation is fixed at zero Temperature
(the r-component is constant) and is
fully characterised by two degrees of freedom.
(... | 8f1ed7021da943082ae336f6d52bed8df09ee52b | 34,884 |
from typing import Mapping
def dict_list_select(dict_list, keys, default_value='', include_conditions={}, exclude_conditions={}):
"""
Transforms a list of dictionaries into a new list of dictionaries that only
includes the specified keys. List entries that are missing key(s) will
get the default valu... | 472f1c14eea0b40fa438aa5e0d13f42a95dd33c7 | 34,885 |
import inspect
def route_hardware_function(api_version: str, function: str):
"""Can be used to execute standard UOS IO functions."""
if api_version not in API_VERSIONS:
return jsonify(
ComResult(
False,
exception=f"'{function}' not supported in api version {... | 0be2fbe888b516dde6337ef532b05ace82217152 | 34,886 |
def calculate_ci(patICDList, version=ELIXHAUSER):
"""
Calculate comorbidity index
"""
if version not in CI_MAP:
raise ValueError("Unsupported comorbidity index")
patCCMap = _calculate_comorbidity_score(patICDList, CI_MAP[version])
return sum(patCCMap.values()) | 69d37081466f2564e3334bb60742cece19bcdc89 | 34,887 |
def _map_spectrum_weight(map, spectrum=None):
"""Weight a map with a spectrum.
This requires map to have an "energy" axis.
The weights are normalised so that they sum to 1.
The mean and unit of the output image is the same as of the input cube.
At the moment this is used to get a weighted exposure... | 0b7571bbc50aa7fed154951d2fc433e2952c0ab2 | 34,888 |
import torch
def predict(processed_input):
"""Function to predict dog breed using the available model
Args:
processed_input (torch 4D tensor): transformed and preprocessed image
Returns:
breed_pred (str): name of the predicted breed
class_prob (float):... | 4af217d05b6734de67b99c9171f1e06d9d11dfd3 | 34,889 |
def getChannels(server: utils.HikVisionServer):
"""
It is used to get the properties of streaming channels for the device
"""
return utils.getXML(server, "Streaming/channels") | 032718216dfba1c7011a29c4d298a16599a0c873 | 34,891 |
def is_help_command(command):
"""
Checks that the user inputted command is a help command, which will not go over the wire.
This is a command with -h or --help.
The help functionality is triggered no matter where the -h appears in the command (arg ordering)
:param command: a list of strings repres... | e68142c38d734e492f9f65dfdf04ac87f79bd666 | 34,893 |
def _holoviews_chart():
"""## Dashboard Orders Chart generated by HoloViews"""
data = _get_chart_data()
line_plot = data.hvplot.line(
x="Day", y="Orders", width=None, height=500, line_color="#007BFF", line_width=6,
)
scatter_plot = data.hvplot.scatter(x="Day", y="Orders", height=300).opts(
... | 4ceb6e712b72a247ead5a6e5f0b442f704e40ab8 | 34,894 |
def api_user_required(f):
"""A decorator for APIs that require a logged-in user."""
@wraps(f)
def decorated(*args, **kwargs):
if not are_logged_in():
return Response("API requires logged-in user", 401)
return f(*args, **kwargs)
return decorated | b4439868dc1401203a50052c430f3213352b1cbe | 34,895 |
import warnings
def fitGMM_patch_post_process( centre_patch_intensity, n_samples=1000, max_dist_thresh=10, min_area_pair=0, max_area_pair=10000):
""" Fits an n-component mixture to a 2d image to resolve closely overlapping centroids
This function simplifies the calling and wraps `fit_2dGMM` so we directly gi... | 5bacc80660a144572b3fbd599e2ca07e2c1f8aaa | 34,896 |
def StartOfInterval(intervalVar:NexVar) -> NexVar:
"""Creates the new event. Copies the start of each interval of the specified interval variable to the result."""
return NexRun("StartOfInterval", locals()) | a272a09944ccc5433182ca58fdc7c085212e8706 | 34,898 |
import ipaddress
def is_global(host: str) -> bool:
"""
>>> assert not is_global("127.0.0.1")
>>> assert not is_global("192.168.20.168")
>>> assert is_global("211.13.20.168")
>>> assert is_global("google.com")
"""
if host == "localhost":
return False
try:
address = ipadd... | 1e68b762a279eb7b54f32339c783a631bedfa2c9 | 34,899 |
def make_tweet(quantity, ticker, asset_description, price, tx_date, tx_time, instrument, trade_type):
"""Create and return a new instance of a Tweet object."""
tweet = Tweet(quantity, ticker, asset_description, price, tx_date, tx_time, instrument, trade_type)
return tweet | f35f25bcbd9235d9c13864106952554a5cc4a163 | 34,900 |
import warnings
def rescale_laplacian(laplacian):
"""
Scale graph Laplacian by the largest eigenvalue of normalized graph Laplacian,
so that the eigenvalues of the scaled Laplacian are <= 1.
Args:
laplacian: Laplacian matrix of the graph
Returns:
Return a scaled Laplacian matrix.... | cf43000542c9c8b23001b0df0d157077a8a84d98 | 34,901 |
def get_function_signature(uplevels=0):
"""
RETURNS the calling function signature, at runtime.
"""
uplevels += 1
funcname = get_function_name(uplevels)
params = get_function_parameters_and_values(uplevels)
params = ", ".join(["{}={}".format(*i) for i in params])
sig = "{}({})".format(... | 62b23ca9f644b46ebbe4ba122ccd7c11291efbcd | 34,903 |
def multivariate_multiply(m1, c1, m2, c2):
""" Multiplies the two multivariate Gaussians together and returns the
results as the tuple (mean, covariance).
Examples
--------
.. code-block:: Python
m, c = multivariate_multiply([7.0, 2], [[1.0, 2.0], [2.0, 1.0]],
... | 59cba92949533e4ec001ffa758bc125fd74960d5 | 34,905 |
def make_initial_state():
"""
Create an initial state dictionary.
"""
return { 'geogrid' : 'waiting',
'ingest' : 'waiting',
'ungrib' : 'waiting',
'metgrid' : 'waiting',
'real' : 'waiting',
'wrf' : 'waiting',
'output': 'waiting... | 7a9e2bccb52c1a75ce2ef1d313177fd573433461 | 34,906 |
def xliff_import_confirm(request, xliff_dir):
"""
Confirm the XLIFF import and write changes to database
:param request: The current request (used for error messages)
:type request: ~django.http.HttpRequest
:param xliff_dir: The directory containing the xliff files
:type xliff_dir: str
:r... | aa022adc6c4a471c3fd1f7b9896f9b3aa5c1ddcf | 34,907 |
def generate_gaps_time_series(nt, nx, ny, pct, gaps_type):
""" Generate gaps on time series of modeled fields.
Input:
- pct: percentage of gaps to be generated
- gaps_type: type of gaps, can be:
- 'random': randomly distributed gaps across time series
- 'corr'... | 20267e0043efbf40f1779592961012f8999ac249 | 34,908 |
from datetime import datetime
def leave_feedback():
"""Оставить отзыв"""
json = request.get_json()
if "text" in json:
Feedback.create(text=json["text"], user=get_user_from_request())
Telegram(current_app.config).notify_admin_channel(
"Пользователь %s оставил отзыв: %s"
... | cdc1c5898c1f68ebcb1d4b34dd05ff2fab6c450f | 34,909 |
from typing import Optional
def get_control_panel(control_panel_arn: Optional[str] = None,
opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetControlPanelResult:
"""
AWS Route53 Recovery Control Control Panel resource schema .
:param str control_panel_arn: The Amazon Resou... | d8dd1280505b70ee25166941f9822827f10850c4 | 34,910 |
from typing import Sequence
from typing import Optional
from typing import Type
from typing import Union
def zeros(shape: Sequence[int],
dtype: Optional[Type[np.number]] = None,
backend: Optional[Union[Text, AbstractBackend]] = None) -> Tensor:
"""Return a Tensor of shape `shape` of all zeros.
... | e913c5fa24095842492cec670fde2ea61afc24c6 | 34,911 |
def staff_required(
function=None, redirect_field_name=REDIRECT_FIELD_NAME, login_url="login"
):
"""Decorator for views that checks that the logged in user is a staff/admin,
redirects to the log-in page if necessary."""
actual_decorator = user_passes_test(
lambda user: user.is_active and user.is... | 804ba1021993507796fd7009ffea880fcebc2edc | 34,912 |
def from_Peppercorn_restingset_reaction(reaction, restingsets):
""" Converts a condensed Peppercorn PepperReaction object to an equivalent
DNAObjects RestingSetReaction object. This function requires as an argument a
dict mapping Peppercorn RestingSet objects to equivalent DNAObject RestingSets.
"""
if rea... | 12f368f7c2a2e5f20456c37131f28a76573cebe3 | 34,913 |
from unittest.mock import Mock
def mock_stripe_checkout(monkeypatch):
"""Fixture to monkeypatch stripe.checkout.* methods"""
mock = Mock()
mock.Session.create.return_value.url = "https://example.net/stripe_checkout/"
monkeypatch.setattr(stripe, "checkout", mock)
return mock | 78c8bf08bb41c831f2e0a602a889b937ea1534c5 | 34,914 |
import time
def milliseconds():
"""
Current time in milliseconds (UTC).
"""
return int(time.time() * 1000) | cc829688be8742423a8306b0ffae14f318541687 | 34,915 |
def test_dispatch_responses():
"""
MessageSenderMixin._dispatch_responses() Test plan:
-Ensure False returned if pre_dispatch_responses hook returns false
-Ensure False returned if post_dispatch_responses hook returns false
-Catch invalid response from hpit on [message][id]
-Catc... | c2d25ccde706246f89eb74ff11dbf673ca07f792 | 34,916 |
def fit_wave_interval(wave, old_sampling, new_sampling, new_size = None):
"""
Produces an array of wavelengths between two values and with a given number
of elements.
Parameters
----------
wave : np.ndarray, list
List or ndarray with initial wavelength and final wavelength e.g.:
... | 0e2473fa707f704f60ecf5a4dcf0966ab5f041be | 34,917 |
def make_network_from_structural_and_functional(structural_edges, functional_edges):
"""
Combine structural and functional dataframes to get a deduplicated dataframe of edges
:param structural_edges: pandas DataFrame including columns ['source_content_id', 'destination_content_id']
:param functional_edg... | fdea72dab9da4cab05d7a998e543476b761dd74a | 34,918 |
import math
def num_k_of_n(n: int, k: int) -> int:
"""Return number of combinations of k elements out of n."""
if k > n:
return 0
if k == n:
return 1
return math.factorial(n) // (math.factorial(k) * math.factorial((n - k))) | de99dd88fc6e747421e36c698a525b7e58b1e4de | 34,920 |
def new_graph():
"""Make graph to play with."""
return Graph() | eac2a6a9e65db733cc744e391fbbb6f2906cf744 | 34,921 |
def subtract_mean_batch_reward(population):
"""Returns new Population where each batch has mean-zero rewards."""
df = population.to_frame()
mean_dict = df.groupby('batch_index').reward.mean().to_dict()
def reward_for_sample(sample):
return sample.reward - mean_dict[sample.batch_index]
shifted_samples = ... | 73813c3f165dc933983b0abe48392505cc202e6e | 34,922 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.