content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def covid_API(cases_and_deaths: dict) -> dict:
"""
Imports Covid Data
:param cases_and_deaths: This obtains dictionary from config file
:return: A dictionary of covid information
"""
api = Cov19API(filters=england_only, structure=cases_and_deaths)
data = api.get_json()
return data | 8429c35770d25d595a6f51a2fe80d2eac585c785 | 3,650,927 |
def gather_gltf2(export_settings):
"""
Gather glTF properties from the current state of blender.
:return: list of scene graphs to be added to the glTF export
"""
scenes = []
animations = [] # unfortunately animations in gltf2 are just as 'root' as scenes.
active_scene = None
for blende... | 6a382349a1a2aef3d5d830265b0f7430440ac6ef | 3,650,929 |
import time
def getOneRunMountainCarFitness_modifiedReward(tup):
"""Get one fitness from the MountainCar or MountainCarContinuous
environment while modifying its reward function.
The MountainCar environments reward only success, not progress towards
success. This means that individuals that are tryi... | f17e768755d0b4862ee70a0fe7d317a8074d7852 | 3,650,930 |
def ArtToModel(art, options):
"""Convert an Art object into a Model object.
Args:
art: geom.Art - the Art object to convert.
options: ImportOptions - specifies some choices about import
Returns:
(geom.Model, string): if there was a major problem, Model may be None.
The string will... | 3130471f7aa6b0b8fd097c97ca4916a51648112e | 3,650,931 |
def simulate_data(N, intercept, slope, nu, sigma2=1, seed=None):
"""Simulate noisy linear model with t-distributed residuals.
Generates `N` samples from a one-dimensional linear regression with
residuals drawn from a t-distribution with `nu` degrees of freedom, and
scaling-parameter `sigma2`. The true ... | a88e7f1958876c3dd47101da7f2f1789e02e4d18 | 3,650,932 |
def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode:
"""
52ms 93.76%
13.1MB 83.1%
:param self:
:param head:
:param n:
:return:
"""
if not head:
return head
dummy = ListNode(0)
dummy.next = head
fast = dummy
while n:
fast = fast.next
... | 5b9fa939aec64425e7ca9932fe0cc5814fd0f608 | 3,650,934 |
import logging
def get_masters(domain):
""" """
content = request.get_json()
conf = {
'check_masters' : request.headers.get('check_masters'),
'remote_api' : request.headers.get('remote_api'),
'remote_api_key' : request.headers.get('remote_api_key')
}
masters = pdns_get_mast... | dd006d889ee9f11a8f522a111ce7a4db4f5ba039 | 3,650,938 |
def SplitGeneratedFileName(fname):
"""Reverse of GetGeneratedFileName()
"""
return tuple(fname.split('x',4)) | 0210361d437b134c3c24a224ab93d2ffdcfc32ec | 3,650,939 |
def chooseBestFeatureToSplit(dataSet):
"""
选择最优划分特征
输入: 数据集
输出: 最优特征
"""
numFeatures = len(dataSet[0])-1
baseEntropy = calcShannonEnt(dataSet) #原始数据的熵
bestInfoGain = 0
bestFfeature = -1
for i in range(numFeatures): #循环所有特征
featList = [example[i] for example in dataSet]
... | 1e9935cf280b5bf1a32f34187038301109df7d19 | 3,650,940 |
import torch
import tqdm
def evaluate_model(model: torch.nn.Module, dataloader: torch.utils.data.DataLoader, device: torch.device):
"""Function for evaluation of a model `model` on the data in `dataloader` on device `device`"""
# Define a loss (mse loss)
mse = torch.nn.MSELoss()
# We will accumulate t... | e550c469d0b66cc0a0ef32d2907521c77ed760fa | 3,650,941 |
def get_DOE_quantity_byfac(DOE_xls, fac_xls, facilities='selected'):
"""
Returns total gallons of combined imports and exports
by vessel type and oil classification to/from WA marine terminals
used in our study.
DOE_xls[Path obj. or string]: Path(to Dept. of Ecology transfer dataset)
faci... | 371fd9b2bc0f9e45964af5295de1edad903729c9 | 3,650,942 |
import re
def number_finder(page, horse):
"""Extract horse number with regex."""
if 'WinPlaceShow' in page:
return re.search('(?<=WinPlaceShow\\n).[^{}]*'.format(horse), page).group(0)
elif 'WinPlace' in page:
return re.search('(?<=WinPlace\\n).[^{}]*'.format(horse), page).group(0) | 483067fcfa319a7dfe31fdf451db82550fd35d03 | 3,650,943 |
from ...data import COCODetection
def ssd_300_mobilenet0_25_coco(pretrained=False, pretrained_base=True, **kwargs):
"""SSD architecture with mobilenet0.25 base networks for COCO.
Parameters
----------
pretrained : bool or str
Boolean value controls whether to load the default pretrained weigh... | 5c234e824d60a116b7640eff4c50adba98792927 | 3,650,944 |
def get_project_by_id(client: SymphonyClient, id: str) -> Project:
"""Get project by ID
:param id: Project ID
:type id: str
:raises:
* FailedOperationException: Internal symphony error
* :class:`~psym.exceptions.EntityNotFoundError`: Project does not exist
:return: Project
:rt... | 72904b1f72eb2ce3e031df78d8f00cef8d5b5791 | 3,650,945 |
def write_trans_output(k, output_fname, output_steps_fname, x, u, time, nvar):
"""
Output transient step and spectral step in a CSV file"""
# Transient
if nvar > 1:
uvars = np.split(u, nvar)
results_u = [np.linalg.norm(uvar, np.inf) for uvar in uvars]
results = [
time... | 5681902519af79777f8fb5aa2a36f8445ee4cf32 | 3,650,946 |
def browser(browserWsgiAppS):
"""Fixture for testing with zope.testbrowser."""
assert icemac.addressbook.testing.CURRENT_CONNECTION is not None, \
"The `browser` fixture needs a database fixture like `address_book`."
return icemac.ab.calendar.testing.Browser(wsgi_app=browserWsgiAppS) | 47c9a0d4919be55d15a485632bca826183ba92b2 | 3,650,947 |
def mixture_fit(samples,
model_components,
model_covariance,
tolerance,
em_iterations,
parameter_init,
model_verbosity,
model_selection,
kde_bandwidth):
"""Fit a variational Bayesian non-p... | 807f0ef2028a5dcb99052e6b86558f8b325405db | 3,650,948 |
def find_best_lexer(text, min_confidence=0.85):
"""
Like the built in pygments guess_lexer, except has a minimum confidence
level. If that is not met, it falls back to plain text to avoid bad
highlighting.
:returns: Lexer instance
"""
current_best_confidence = 0.0
current_best_lexer = ... | 57cffae3385886cc7841086697ce30ff10bb3bd8 | 3,650,951 |
def volta(contador, quantidade):
"""
Volta uma determinada quantidade de caracteres
:param contador: inteiro utilizado para determinar uma posição na string
:param quantidade: inteiro utilizado para determinar a nova posição na string
:type contador: int
:type quantidade: int
:return: retorn... | 4183afebdfc5273c05563e4675ad5909124a683a | 3,650,952 |
from operator import and_
def keep_room(session, worker_id, room_id):
"""Try to keep a room"""
# Update room current timestamp
query = update(
Room
).values({
Room.updated: func.now(),
}).where(
and_(Room.worker == worker_id,
Room.id == room_id)
)
proxy... | b4dbbc972d7fd297bf55b205e92d2126a5a68e6e | 3,650,953 |
from typing import List
def get_rounds(number: int) -> List[int]:
"""
:param number: int - current round number.
:return: list - current round and the two that follow.
"""
return list(range(number, number + 3)) | 9bf55545404acd21985c1765906fc439f5f4aed6 | 3,650,954 |
from bs4 import BeautifulSoup
from datetime import datetime
def parse_pasinobet(url):
"""
Retourne les cotes disponibles sur pasinobet
"""
selenium_init.DRIVER["pasinobet"].get("about:blank")
selenium_init.DRIVER["pasinobet"].get(url)
match_odds_hash = {}
match = None
date_time = None
... | 5cda34741f4e6cc26e2ecccec877c9af2426084a | 3,650,955 |
def create_toolbutton(parent, icon=None, tip=None, triggered=None):
"""Create a QToolButton."""
button = QToolButton(parent)
if icon is not None:
button.setIcon(icon)
if tip is not None:
button.setToolTip(tip)
if triggered is not None:
button.clicked.connect(triggered)
re... | dfff516f498f924ca5d5d6b15d94907ed2e06029 | 3,650,956 |
import select
def __basic_query(model, verbose: bool = False) -> pd.DataFrame:
"""Execute and return basic query."""
stmt = select(model)
if verbose:
print(stmt)
return pd.read_sql(stmt, con=CONN, index_col="id") | eb9c44eb64144b1e98e310e2dd026e5b1e912619 | 3,650,957 |
def format_data_preprocessed(data, dtype = np.float):
"""
The input data preprocessing
data the input data frame
preprocessing whether to use features preprocessing (Default: False)
dtype the data type for ndarray (Default: np.float)
"""
train_flag = np.array(data['train_flag'])
print '... | a5785ef81a0f5d35f8fb73f72fbe55084bc5e2b0 | 3,650,958 |
def get_word_idxs_1d(context, token_seq, char_start_idx, char_end_idx):
"""
0 based
:param context:
:param token_seq:
:param char_start_idx:
:param char_end_idx:
:return: 0-based token index sequence in the tokenized context.
"""
spans = get_1d_spans(context,token_seq)
idxs ... | b279a3baea0e9646b55e598fd6ae16df70de5100 | 3,650,960 |
import binascii
def create_b64_from_private_key(private_key: X25519PrivateKey) -> bytes:
"""Create b64 ascii string from private key object"""
private_bytes = private_key_to_bytes(private_key)
b64_bytes = binascii.b2a_base64(private_bytes, newline=False)
return b64_bytes | 3abd69bcd3fc254c94da9fac446c6ffbc462f58d | 3,650,961 |
def create_fake_record(filename):
"""Create records for demo purposes."""
data_to_use = _load_json(filename)
data_acces = {
"access_right": fake_access_right(),
"embargo_date": fake_feature_date(),
}
service = Marc21RecordService()
draft = service.create(
data=data_to_u... | 744ed3a3b13bc27d576a31d565d846850e6640a3 | 3,650,962 |
import json
def load_configuration():
"""
This function loads the configuration from the
config.json file and then returns it.
Returns: The configuration
"""
with open('CONFIG.json', 'r') as f:
return json.load(f) | 91eae50d84ec9e4654ed9b8bcfa35215c8b6a7c2 | 3,650,963 |
def scrape(webpage, linkNumber, extention):
"""
scrapes the main page of a news website using request and beautiful soup and
returns the URL link to the top article as a string
Args:
webpage: a string containing the URL of the main website
linkNumber: an integer point... | f04cb8c8583f7f242ce70ec4da3e8f2556af7edb | 3,650,965 |
def Scheduler(type):
"""Instantiate the appropriate scheduler class for given type.
Args:
type (str): Identifier for batch scheduler type.
Returns:
Instance of a _BatchScheduler for given type.
"""
for cls in _BatchScheduler.__subclasses__():
if cls.is_scheduler_for(type):
... | 21074ecf33383b9f769e8dd63786194b4678246b | 3,650,966 |
def event_detail(request, event_id):
"""
A View to return an individual selected
event details page.
"""
event = get_object_or_404(Event, pk=event_id)
context = {
'event': event
}
return render(request, 'events/event_detail.html', context) | 6fda0906e70d88839fbcd26aa6724b5f2c433c07 | 3,650,967 |
from typing import Optional
from typing import Iterable
from typing import Tuple
import numpy
def variables(
metadata: meta.Dataset,
selected_variables: Optional[Iterable[str]] = None
) -> Tuple[dataset.Variable]:
"""Return the variables defined in the dataset.
Args:
selected_variables: The v... | 6175ad712996a30673eb2f5ff8b64c76d2f4a66b | 3,650,968 |
def builder(tiledata, start_tile_id, version, clear_old_tiles=True):
"""
Deserialize a list of serialized tiles, then re-link all the tiles to
re-create the map described by the tile links
:param list tiledata: list of serialized tiles
:param start_tile_id: tile ID of tile that should be used as th... | 235df5c953705fbbbd69d8f1c7ed1ad282b469ba | 3,650,969 |
import base64
def data_uri(content_type, data):
"""Return data as a data: URI scheme"""
return "data:%s;base64,%s" % (content_type, base64.urlsafe_b64encode(data)) | f890dc1310e708747c74337f5cfa2d6a31a23fc0 | 3,650,970 |
def next_line(ionex_file):
"""
next_line
Function returns the next line in the file
that is not a blank line, unless the line is
'', which is a typical EOF marker.
"""
done = False
while not done:
line = ionex_file.readline()
if line == '':
return line
... | 053e5582e5146ef096d743973ea7069f19ae6d4d | 3,650,971 |
def last(value):
"""
returns the last value in a list (None if empty list) or the original if value not a list
:Example:
---------
>>> assert last(5) == 5
>>> assert last([5,5]) == 5
>>> assert last([]) is None
>>> assert last([1,2]) == 2
"""
values = as_list(value)
ret... | f3a04f0e2544879639b53012bbd9068ae205be18 | 3,650,972 |
import numpy
def levup(acur, knxt, ecur=None):
"""
LEVUP One step forward Levinson recursion
Args:
acur (array) :
knxt (array) :
Returns:
anxt (array) : the P+1'th order prediction polynomial based on the P'th
order prediction polynomial, acur, and the... | 182102d03369d23d53d21bae7209cf49d2caecb4 | 3,650,973 |
def gradient_output_wrt_input(model, img, normalization_trick=False):
"""
Get gradient of softmax with respect to the input.
Must check if correct.
Do not use
# Arguments
model:
img:
# Returns
gradient:
"""
grads = K.gradients(model.output, model.input)[0]
... | ed45fccb0f412f8f8874cd8cd7f62ff2101a3a40 | 3,650,974 |
def response_GET(client, url):
"""Fixture that return the result of a GET request."""
return client.get(url) | b4762c9f652e714cc5c3694b75f935077039cb02 | 3,650,975 |
import tqdm
def twitter_preprocess():
"""
ekphrasis-social tokenizer sentence preprocessor.
Substitutes a series of terms by special coins when called
over an iterable (dataset)
"""
norm = ['url', 'email', 'percent', 'money', 'phone', 'user',
'time', 'date', 'number']
ann = {"hashtag", "elongated", "allca... | 18bcd48cff7c77480cd76165fef02d0e39ae19cc | 3,650,977 |
import math
def rotation_matrix(axis, theta):
"""
Return the rotation matrix associated with counterclockwise rotation about
the given axis by theta radians.
"""
axis = np.asarray(axis)
axis = axis / math.sqrt(np.dot(axis, axis))
a = math.cos(theta / 2.0)
b, c, d = -axis * math.sin(the... | cd940b60096fa0c92b8cd04d36a0d62d7cd46455 | 3,650,978 |
from typing import Type
from typing import List
def get_routes(interface: Type[Interface]) -> List[ParametrizedRoute]:
"""
Retrieves the routes from an interface.
"""
if not issubclass(interface, Interface):
raise TypeError('expected Interface subclass, got {}'
.format(interface.__name__))
route... | 9d3baf951312d3027e2329fa635b2425dda579e5 | 3,650,979 |
def _get_realm(response):
"""Return authentication realm requested by server for 'Basic' type or None
:param response: requests.response
:type response: requests.Response
:returns: realm
:rtype: str | None
"""
if 'www-authenticate' in response.headers:
auths = response.headers['www... | 346b3278eb52b565f747c952493c15820eece729 | 3,650,981 |
import math
def exp_mantissa(num, base=10):
"""Returns e, m such that x = mb^e"""
if num == 0:
return 1, 0
# avoid floating point error eg log(1e3, 10) = 2.99...
exp = math.log(abs(num), base)
exp = round(exp, FLOATING_POINT_ERROR_ON_LOG_TENXPONENTS)
exp = math.floor(exp) # 1 <= manti... | b0fd7a961fbd0f796fc00a5ce4005c7aa9f92950 | 3,650,982 |
from typing import Callable
def decide_if_taxed(n_taxed: set[str]) -> Callable[[str], bool]:
"""To create an decider function for omitting taxation.
Args:
n_taxed: The set containing all items, which should not be taxed.
If empty, a default set will be chosen.
Returns:
D... | c13c7e832b86bd85e2cade03cbc84a43893dfe17 | 3,650,983 |
def generate_two_cat_relation_heat_map():
"""
A correlation matrix for categories
"""
data = Heatmap(
z=df_categories.corr(),
y=df_categories.columns,
x=df_categories.columns)
title = 'Correlation Distribution of Categories'
y_title = 'Category'
x_title = 'Category'
... | 90efbffd54c723eef9297ba0abba71d55a500cd0 | 3,650,984 |
def build_phase2(VS, FS, NS, VT, VTN, marker, wc):
"""
Build pahase 2 sparse matrix M_P2 closest valid point term with of source vertices (nS)
triangles(mS) target vertices (nT)
:param VS: deformed source mesh from previous step nS x 3
:param FS: triangle index of source mesh mS * 3
:param NS: t... | ab3622f5b4377b1a60d34345d5396f66d5e3c641 | 3,650,985 |
def voronoi_to_dist(voronoi):
""" voronoi is encoded """
def decoded_nonstacked(p):
return np.right_shift(p, 20) & 1023, np.right_shift(p, 10) & 1023, p & 1023
x_i, y_i, z_i = np.indices(voronoi.shape)
x_v, y_v, z_v = decoded_nonstacked(voronoi)
return np.sqrt((x_v - x_i) ** 2 + (y_v - y_i) ** 2 + (z_v - z_i) ... | 38c2630d45b281477531fcc845d34ea7b2980dab | 3,650,986 |
def post_update_view(request):
"""View To Update A Post For Logged In Users"""
if request.method == 'POST':
token_type, token = request.META.get('HTTP_AUTHORIZATION').split()
if(token_type != 'JWT'):
return Response({'detail': 'No JWT Authentication Token Found'}, status=status.HTTP... | 8044e12328c5bb63c48f673971ae1ed8727b02b7 | 3,650,987 |
from typing import List
def _is_binary_classification(class_list: List[str]) -> bool:
"""Returns true for binary classification problems."""
if not class_list:
return False
return len(class_list) == 1 | 82ada7dd8df93d58fad489b19b9bf4a93ee819c3 | 3,650,988 |
def create_post_like(author, post):
"""
Create a new post like given an author and post
"""
return models.Like.objects.create(author=author, post=post) | f8e07c10076015e005cd62bb3b39a5656ebc45a3 | 3,650,989 |
def translate_entries(yamldoc, base_url):
"""
Reads the field `entries` from the YAML document, processes each entry that is read using the
given base_url, and appends them all to a list of processed entries that is then returned.
"""
if 'entries' in yamldoc and type(yamldoc['entries']) is list:
entries =... | 0c949939020b3bb1017fca5543be8dcc77d03bbf | 3,650,990 |
def get_in(obj, lookup, default=None):
""" Walk obj via __getitem__ for each lookup,
returning the final value of the lookup or default.
"""
tmp = obj
for l in lookup:
try: # pragma: no cover
tmp = tmp[l]
except (KeyError, IndexError, TypeError): # pragma: no cover
... | 73dfcaadb6936304baa3471f1d1e980f815a7057 | 3,650,991 |
import six
def GetSpec(resource_type, message_classes, api_version):
"""Returns a Spec for the given resource type."""
spec = _GetSpecsForVersion(api_version)
if resource_type not in spec:
raise KeyError('"%s" not found in Specs for version "%s"' %
(resource_type, api_version))
spec =... | ece9dd996c52f01bb985af9529b33bb7b12fbfdc | 3,650,992 |
def ips_between(start: str, end: str) -> int:
"""
A function that receives two IPv4 addresses,
and returns the number of addresses between
them (including the first one, excluding the
last one).
All inputs will be valid IPv4 addresses in
the form of strings. The last address will
always be greater than the first o... | aa523ec8a127e2224b7c9fc7a67d720ac4d100ed | 3,650,993 |
def tmNstate(trTrg):
"""Given (newq, new_tape_sym, dir),
return newq.
"""
return trTrg[0] | 17db0bc5cae4467e7a66d506e1f32d48c949e5eb | 3,650,994 |
def _preprocess_continuous_variable(df: pd.DataFrame, var_col: str, bins: int,
min_val: float = None,
max_val: float = None) -> pd.DataFrame:
"""
Pre-processing the histogram for continuous variables by splitting the variable in buckets.
... | 9c2844497dbe55727f6b2aea17cf7a23e60a3002 | 3,650,996 |
import itertools
def get_pairs(labels):
"""
For the labels of a given word, creates all possible pairs
of labels that match sense
"""
result = []
unique = np.unique(labels)
for label in unique:
ulabels = np.where(labels==label)[0]
# handles when a word sense has on... | 454de57eedf6f272fef2c15b40f84de57ed3fa64 | 3,650,997 |
def iredv(tvp,tton):
""" makes sop tvp irredundant relative to onset truth table"""
res = []
red = list(tvp)
for j in range(len(tvp)):
tvj=tvp[j]&tton #care part of cube j
if (tvj&~or_redx(red,j)) == m.const(0): # reduce jth cube to 0
red[j]=m.const(0)
else: #keep cub... | 5fdb9ed97216b668110908419b364107ed3b7c37 | 3,650,998 |
def ridder_fchp(st, target=0.02, tol=0.001, maxiter=30, maxfc=0.5, config=None):
"""Search for highpass corner using Ridder's method.
Search such that the criterion that the ratio between the maximum of a third order
polynomial fit to the displacement time series and the maximum of the displacement
tim... | ee3198c443885fa9524d12c30aa277d8cd843d27 | 3,650,999 |
def get_impropers(bonds):
"""
Iterate over bonds to get impropers.
Choose all three bonds that have one atom in common.
For each set of bonds you have 3 impropers where one of the noncommon atoms is out of plane.
Parameters
----------
bonds : list
List of atom ids that make up bonds... | c5c2fe4684269407cd4387d86840bd982f1d3fa5 | 3,651,001 |
def get_ret_tev_return(*args):
"""get_ret_tev_return(int n) -> ea_t"""
return _idaapi.get_ret_tev_return(*args) | 94d476d12313b7df4da32cb45cfe644a0078debb | 3,651,002 |
def make_figure_6(prefix=None, rng=None, colors=None):
"""
Figures 6, Comparison of Performance
Ported from MATLAB Code
Nicholas O'Donoughue
24 March 2021
:param prefix: output directory to place generated figure
:param rng: random number generator
:param colors: colormap for plotting... | 761d6ddd541dfbe42e5b57cd680306c71ae978d9 | 3,651,003 |
def slim_form(domain_pk=None, form=None):
"""
What is going on? We want only one domain showing up in the
choices. We are replacing the query set with just one object. Ther
are two querysets. I'm not really sure what the first one does, but
I know the second one (the widget) removes the choices. Th... | 7b58674e307fbbd31f0546b70309c0c723d1021c | 3,651,004 |
def input(*args):
"""
Create a new input
:param args: args the define a TensorType, can be either a TensorType or a shape and a DType
:return: the input expression
"""
tensor_type = _tensor_type_polymorhpic(*args)
return InputTensor(tensor_type, ExpressionDAG.num_inputs) | 47ab3a08f412b7dc9c679ae72bb44c76123a9057 | 3,651,005 |
def commong_substring(input_list):
"""Finds the common substring in a list of strings"""
def longest_substring_finder(string1, string2):
"""Finds the common substring between two strings"""
answer = ""
len1, len2 = len(string1), len(string2)
for i in range(len1):
mat... | 9e5e0878072a5416326ac1ed0d929adcb8511b37 | 3,651,006 |
def is_valid_url(url):
"""Checks if a URL is in proper format.
Args:
url (str): The URL that should be checked.
Returns:
bool: Result of the validity check in boolean form.
"""
valid = validators.url(url)
if valid:
return True
else:
return False | b55fd89267884dfc2507966825272a02e18d34f5 | 3,651,007 |
import re
import requests
def codepoint_to_url(codepoint, style):
"""
Given an emoji's codepoint (e.g. 'U+FE0E') and a non-apple emoji style,
returns a url to to the png image of the emoji in that style.
Only works for style = 'twemoji', 'noto', and 'blobmoji'.
"""
base = codepoint.replace(... | a5b47f5409d465132e3fb7141d81dbd617981ca8 | 3,651,008 |
def getRNCS(ChargeSA):
"""The calculation of relative negative charge surface area
-->RNCS
"""
charge=[]
for i in ChargeSA:
charge.append(float(i[1]))
temp=[]
for i in ChargeSA:
temp.append(i[2])
try:
RNCG = min(charge)/sum([i for i in charge if i < 0.0])
... | f03011de85e1bcac01b2aba4afde61a3dd9f7866 | 3,651,009 |
def handle_auth_manager_auth_exception(error):
"""Return a custom message and 403 status code"""
response_header = {'X-REQUEST-ID': util.create_request_id()}
return {'message': error.message}, 403, response_header | 4b5212f4471a21cd54d012728705e83de5c7a86f | 3,651,010 |
def get_default_converter():
"""Intended only for advanced uses"""
return _TYPECATS_DEFAULT_CONVERTER | f88cdb13d53a228ff1d77a9065c1dabd0f83ed1d | 3,651,011 |
import json
def login(request):
"""
:param: request
:return: JSON data
"""
response = {}
if request.method == 'GET':
username = request.GET.get('username')
password = request.GET.get('password')
try:
usr = models.User.objects.filter(username=username, passwo... | 2d9b6791a2160ec63929d5a37e6d8336cca7709a | 3,651,012 |
def average_win_rate(strategy, baseline=always_roll(4)):
"""Return the average win rate of STRATEGY against BASELINE. Averages the
winrate when starting the game as player 0 and as player 1.
"""
win_rate_as_player_0 = 1 - make_averaged(winner)(strategy, baseline)
win_rate_as_player_1 = make_averaged... | 2e6b78127543456b7e931c837cf1a9468c013c33 | 3,651,013 |
def decode(chrom):
"""
Returns the communities of a locus-based adjacency codification
in a vector of int where each position is a node id and the value
of that position the id of the community where it belongs. To position
with the same number means that those two nodes belongs to same community.
... | 998a58e0d4efad2c079a9d023530aca37d0e226e | 3,651,014 |
import math
def bin_search(query, data):
""" Query is a coordinate interval. Approximate binary search for the query in sorted data,
which is a list of coordinates. Finishes when the closest overlapping value of query and
data is found and returns the index in data. """
i = int(math.floor(len(data)/2)) # binar... | bb93034bc5c7e432c3fc55d4485949688e62b84a | 3,651,015 |
def get_rating(business_id):
""" GET Business rating"""
rating = list(
db.ratings.aggregate(
[{"$group": {"_id": "$business", "pop": {"$avg": "$rating"}}}]
)
)
if rating is None:
return (
jsonify(
{
"success": False,
... | 3a1cbf3e815c879b4ddaa5185477f141b261a859 | 3,651,016 |
def fwhm(x,y):
"""Calulate the FWHM for a set of x and y values.
The FWHM is returned in the same units as those of x."""
maxVal = np.max(y)
maxVal50 = 0.5*maxVal
#this is to detect if there are multiple values
biggerCondition = [a > maxVal50 for a in y]
changePoints = []
xPoints... | 2dc18d15d2940520acde39c5914413d89e9fbc71 | 3,651,017 |
import glob
def parse_names(input_folder):
"""
:param input_folder:
:return:
"""
name_set = set()
if args.suffix:
files = sorted(glob(f'{input_folder}/*{args.suffix}'))
else:
files = sorted(glob(f'{input_folder}/*'))
for file in files:
with open(file) as f:
... | 10b72d9822d6c8057f9bc45936c8d1bfb1a029b6 | 3,651,018 |
from typing import Iterable
from typing import Tuple
from typing import Mapping
from typing import Union
def build_charencoder(corpus: Iterable[str], wordlen: int=None) \
-> Tuple[int, Mapping[str, int], TextEncoder]:
"""
Create a char-level encoder: a Callable, mapping strings into integer arrays.
... | 207a5f499930f2c408ac88199ac45c60b3ed9d97 | 3,651,019 |
import struct
def Decodingfunc(Codebyte):
"""This is the version 'A' of decoding function,
that decodes data coded by 'A' coding function"""
Decodedint=struct.unpack('b',Codebyte)[0]
N=0 #number of repetitions
L=0 # length of single/multiple sequence
if Decodedint >= 0: #single
N = 1
... | 450a3e6057106e9567952b33271935392702aea9 | 3,651,020 |
def _metric_notification_text(metric: MetricNotificationData) -> str:
"""Return the notification text for the metric."""
new_value = "?" if metric.new_metric_value is None else metric.new_metric_value
old_value = "?" if metric.old_metric_value is None else metric.old_metric_value
unit = metric.metric_un... | 855ec000b3e37d9f54e4a12d7df4f973b15b706f | 3,651,021 |
from typing import Optional
from typing import Union
from typing import List
from typing import Dict
def train_dist(
domain: Text,
config: Text,
training_files: Optional[Union[Text, List[Text]]],
output: Text = rasa.shared.constants.DEFAULT_MODELS_PATH,
dry_run: bool = False,
force_training: b... | 1d1f55dca4a6274713cdd17a7ff5efcc90b46d14 | 3,651,022 |
def wav2vec2_base() -> Wav2Vec2Model:
"""Build wav2vec2 model with "base" configuration
This is one of the model architecture used in *wav2vec 2.0*
[:footcite:`baevski2020wav2vec`] for pretraining.
Returns:
Wav2Vec2Model:
"""
return _get_model(
extractor_mode="group_norm",
... | fb288116f5ef57b314ecfde4a85b1a9bb5d437ce | 3,651,024 |
from unittest.mock import patch
def dont_handle_lock_expired_mock(app):
"""Takes in a raiden app and returns a mock context where lock_expired is not processed
"""
def do_nothing(raiden, message): # pylint: disable=unused-argument
return []
return patch.object(
app.raiden.message_ha... | 2a893e7e755010104071b2b1a93b60a0417e5457 | 3,651,025 |
def system(_printer, ast):
"""Prints the instance system initialization."""
process_names_str = ' < '.join(map(lambda proc_block: ', '.join(proc_block), ast["processNames"]))
return f'system {process_names_str};' | f16c6d5ebe1a029c07efd1f34d3079dd02eb4ac0 | 3,651,027 |
import random
def genmove(proc, colour, pluck_random=True):
""" Send either a `genmove` command to the client, or generate a random
move until it is accepted by the client """
if pluck_random and random() < 0.05:
for _count in range(100):
proc.stdin.write('1000 play %s %s\n' % (colour,... | 589a054be52c40507d8aba5f10a3d67489ec301b | 3,651,028 |
def geojson_to_meta_str(txt):
""" txt is assumed to be small
"""
vlayer = QgsVectorLayer(txt, "tmp", "ogr")
crs_str = vlayer.sourceCrs().toWkt()
wkb_type = vlayer.wkbType()
geom_str = QgsWkbTypes.displayString(wkb_type)
feat_cnt = vlayer.featureCount()
return geom_str, crs_str, feat_cnt | 33b0a2055ec70c2142977469384a20b99d26cee8 | 3,651,029 |
def tdf_UppestID(*args):
"""
* Returns ID 'ffffffff-ffff-ffff-ffff-ffffffffffff'.
:rtype: Standard_GUID
"""
return _TDF.tdf_UppestID(*args) | 1d9d5c528a2f202d49c104b7a56dd7a75b9bc795 | 3,651,030 |
def blend_multiply(cb: float, cs: float) -> float:
"""Blend mode 'multiply'."""
return cb * cs | d53c3a49585cf0c12bf05c233fc6a9dd30ad25b9 | 3,651,031 |
def print_data_distribution(y_classes, class_names):
"""
:param y_classes: class of each instance, for example, if there are 3 classes, and y[i] is [1,0,0], then instance[i] belongs to class[0]
:param class_names: name of each class
:return: None
"""
count = np.zeros(len(class_names))
pro = ... | 289ada7cab00153f894e81dd32980b8d224d637c | 3,651,032 |
import collections
def reorder_conj_pols(pols):
"""
Reorders a list of pols, swapping pols that are conjugates of one another.
For example ('xx', 'xy', 'yx', 'yy') -> ('xx', 'yx', 'xy', 'yy')
This is useful for the _key2inds function in the case where an antenna
pair is specified but the conjugate... | 98730f8434eff02c9a63506e01fbcd478e23e76e | 3,651,033 |
def get_machine_from_uuid(uuid):
"""Helper function that returns a Machine instance of this uuid."""
machine = Machine()
machine.get_from_uuid(uuid)
return machine | 6f78afd9547af5c83abf49a1ac56209ee0e6b506 | 3,651,034 |
def convert_numbers(text):
"""Convert numbers to number words"""
tokens = []
for token in text.split(" "):
try:
word = w2n.num_to_word(token)
tokens.append(word)
except:
tokens.append(token)
return " ".join(tokens) | 8d6eb622076a0404824db2dbeaaba704f3bf6e79 | 3,651,035 |
def init_emulator(rom: bytes):
""" For use in interactive mode """
emulator = NitroEmulator()
emulator.load_nds_rom(rom, True)
return emulator | 9ecaa2a876b8e5bd93deece3ccc62b41ef9c6f3f | 3,651,036 |
from typing import Dict
from typing import Union
import torch
def sub_module_name_of_named_params(named_params: kParamDictType, module_name_sub_dict: Dict[str, str]) \
-> Union[Dict[str, nn.Parameter], Dict[str, torch.Tensor]]:
"""Sub named_parameters key's module name part with module_name_sub_dict.
Arg... | 8bbcdb865f2b0c452c773bc18767128561e806c7 | 3,651,037 |
def my_func_1(x, y):
"""
Возвращает возведение числа x в степень y.
Именованные параметры:
x -- число
y -- степень
(number, number) -> number
>>> my_func_1(2, 2)
4
"""
return x ** y | 9572566f1660a087056118bf974bf1913348dfa4 | 3,651,039 |
def indexer_testapp(es_app):
""" Indexer testapp, meant for manually triggering indexing runs by posting to /index.
Always uses the ES app (obviously, but not so obvious previously) """
environ = {
'HTTP_ACCEPT': 'application/json',
'REMOTE_USER': 'INDEXER',
}
return webtest.Test... | 59343963307c39e43034664febb0ebf00f6ab1bd | 3,651,040 |
def BNN_like(NN,cls=tfp.layers.DenseReparameterization,copy_weight=False,**kwargs):
"""
Create Bayesian Neural Network like input Neural Network shape
Parameters
----------
NN : tf.keras.Model
Neural Network for imitating shape
cls : tfp.layers
Bayes layers class
copy_weight... | 9039f70701fd832843fd160cd71d5d46f7b17b56 | 3,651,041 |
def matrix_mult(a, b):
"""
Function that multiplies two matrices a and b
Parameters
----------
a,b : matrices
Returns
-------
new_array : matrix
The matrix product of the inputs
"""
new_array = []
for i in range(len(a)):
new_a... | 5e0f27f29b6977ea38987fa243f08bb1748d4567 | 3,651,042 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.