content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def function_3():
"""This is a Function prototype in Python"""
print("Printing Docs String")
return 0 | 4268904e75772b9fef804931e3a3564fda333bc7 | 25,647 |
def client():
""" client fixture """
return testing.TestClient(app=service.microservice.start_service(), headers=CLIENT_HEADERS) | ea9997f9904057f0ffdc3175f081acb7e21e719d | 25,648 |
def get_character_bullet(index: int) -> str:
"""Takes an index and converts it to a string containing a-z, ie.
0 -> 'a'
1 -> 'b'
.
.
.
27 -> 'aa'
28 -> 'ab'
"""
result = chr(ord('a') + index % 26) # Should be 0-25
if index > 25:
current = index // 26
whi... | 357f68feb302f11a996b5446c642ad9ca1f0f8d3 | 25,649 |
def update_det_cov(
res: OptResult,
jacobian: JacobianValue):
"""Calculates the inv hessian of the deterministic variables
Note that this modifies res.
"""
covars = res.hess_inv
for v, grad in jacobian.items():
for det, jac in grad.items():
cov = propagate_uncert... | c505654be6f08dcf037337104b4077f6003db876 | 25,651 |
def simplex_init_modified(A, b, c):
"""
Attempt to find a basic feasible vector for the linear program
max: c*x
ST: Ax=b
x>=0,
where A is a (m,n) matrix.
Input Parameters:
A - (n,m) constraint matrix
b - (m,1) vector appearing in the constr... | fd415eedaec1138812fb054656c45450a53535b8 | 25,652 |
def LeakyRelu(
alpha: float,
do_stabilize: bool = False) -> InternalLayer:
"""Leaky ReLU nonlinearity, i.e. `alpha * min(x, 0) + max(x, 0)`.
Args:
alpha: slope for `x < 0`.
do_stabilize: set to `True` for very deep networks.
Returns:
`(init_fn, apply_fn, kernel_fn)`.
"""
return ABRelu(al... | 93a9f103c42979e5107291f818d387eb06feb41b | 25,654 |
def load_interp2d(xz_data_path: str, y: list):
"""
Setup 2D interpolation
Example:
x1, y1, z1, x2, y2, z2\n
1, 3, 5, 1, 4, 6\n
2, 3, 6, 2, 4, 7\n
3, 3 7, 3, 4, 8\n
xy_data_path will lead to a file such as:
1,5,6\n
2,6,7\n
3,7,8\n
y will be: [3, 4]
... | 0883c317c44a97a8e38c615285315adb22a091c5 | 25,655 |
def save_new_party(json_data):
"""saves a new party in the database
Args:
json_data (json) : party details
Returns:
json : api endpoint response
"""
# Deserialize the data input against the party schema
# check if input values throw validation errors
try:
data = p... | e6a11646c1aa13bfceabb1c143308fc985b3f59d | 25,656 |
def cost_function(theta, X, y, lamda=0.01, regularized=False):
"""
Compute cost and gradient for logistic regression with and without regularization.
Computes the cost of using theta as the parameter for regularized logistic regression
and the gradient of the cost w.r.t. to the parameters.
using l... | e4002fc30455be730e6ba46db85588b113e24451 | 25,658 |
from pathlib import Path
import torch
def read_image_numpy(input_filename: Path) -> torch.Tensor:
"""
Read an Numpy file with Torch and return a torch.Tensor.
:param input_filename: Source image file path.
:return: torch.Tensor of shape (C, H, W).
"""
numpy_array = np.load(input_filename)
... | 987185e7b207ecae1abcf01fd5ea939ace0fb869 | 25,659 |
def solution(n: int = 4000000) -> int:
"""Returns the sum of all fibonacci sequence even elements that are lower
or equals to n.
>>> solution(10)
10
>>> solution(15)
10
>>> solution(2)
2
>>> solution(1)
0
>>> solution(34)
44
"""
fib = [0, 1]
i = 0
while ... | b2c3983b9888ae8a10b4ceca2faf5d943b17fbe3 | 25,661 |
def triu(m: ndarray,
k: int = 0) -> ndarray:
"""
Upper triangle of an array.
"""
af_array = af.data.upper(m._af_array, is_unit_diag=False)
return ndarray(af_array) | 00b0b4a301b0b59214a53d8b741c7417bac95f3d | 25,662 |
def generate_annotation(overlay_path,img_dim,ext):
"""
Generate custom annotation for one image from its DDSM overlay.
Args:
----------
overlay_path: string
Overlay file path
img_dim: tuple
(img_height,img_width)
ext: string
Image ... | e9d334c834063ee27b5b9a9d597f084bc735f794 | 25,663 |
from datetime import datetime
def parse_episode_page(loc, contents):
"""Parse a page describing a single podcast episode.
@param loc: The URL of this page.
@type loc: basestring
@param contents: The raw HTML contents of the episode page from which
episode information should be parsed.
@ty... | 805e466c15741ee004059817efa70da66e470871 | 25,664 |
def _bitarray_to_message(barr):
"""Decodes a bitarray with length multiple of 5 to a byte message (removing the padded zeros if found)."""
padding_len = len(barr) % 8
if padding_len > 0:
return bitstring.Bits(bin=barr.bin[:-padding_len]).bytes
else:
return barr.bytes | 79e601bc30519e42c8dbf2369deea5b36a5851ff | 25,665 |
def align_address_to_page(address: int) -> int:
"""Align the address to a page."""
a = align_address(address) >> DEFAULT_PAGE_ALIGN_SHIFT
return a << DEFAULT_PAGE_ALIGN_SHIFT | 1211d3c1a3ae6b1bd183f3d1b1cfb1097fc7dc40 | 25,667 |
def getNamespace(modelName):
"""Get the name space from rig root
Args:
modelName (str): Rig top node name
Returns:
str: Namespace
"""
if not modelName:
return ""
if len(modelName.split(":")) >= 2:
nameSpace = ":".join(modelName.split(":")[:-1])
else:
... | abfb4c54f2dd1b54563f6c7c84e902ed4ee77b01 | 25,669 |
import re
def compile_rules(environment):
"""Compiles all the rules from the environment into a list of rules."""
e = re.escape
rules = [
(
len(environment.comment_start_string),
TOKEN_COMMENT_BEGIN,
e(environment.comment_start_string),
),
(
... | ca7971de422f66e9c9574c13306610e84a000271 | 25,670 |
def compute_window_based_feature(seq,
sample_freq,
func_handle,
window_length,
window_stride,
verbose=False,
**kwargs):
... | 4ab084d3459c617640e404b5232db4557b22c8b8 | 25,672 |
def read_cif(filename):
"""
read the cif, mainly for pyxtal cif output
Be cautious in using it to read other cif files
Args:
filename: path of the structure file
Return:
pyxtal structure
"""
species = []
coords = []
with open(filename, 'r') as f:
lines = f.... | d6d164a6425d088a17bb449b75e875047a5fbc29 | 25,673 |
import random
def custom_data_splits(src_sents, trg_sents, val_samples=3000, seed=SEED):
"""
splits data based on custom number of validation/test samples
:param src_sents: the source sentences
:param trg_sents: the target sentences
:param val_samples: number of validation/test samples
:param ... | 5a4754ce9fe400248a46f4868aeaa0b96ebd5760 | 25,674 |
def normalize(output):
"""将null或者empty转换为暂无输出"""
if not output:
return '暂无'
else:
return output | 18af58c74325522a64dcfd98a75f55e677c01ca3 | 25,675 |
def sgd(args):
""" Wrapper of torch.optim.SGD (PyTorch >= 1.0.0).
Implements stochastic gradient descent (optionally with momentum).
"""
args.lr = 0.01 if args.lr == -1 else args.lr
args.weight_decay = 0 if args.weight_decay == -1 else args.weight_decay
args.momentum = 0 if args.momentum == -1 ... | 17a852165766bcf02f92bac4c847684f2dcfb133 | 25,676 |
def normal_conjugates_known_scale_posterior(prior, scale, s, n):
"""Posterior Normal distribution with conjugate prior on the mean.
This model assumes that `n` observations (with sum `s`) come from a
Normal with unknown mean `loc` (described by the Normal `prior`)
and known variance `scale**2`. The "known scal... | 0bc94999ee10ce63ba0156510a9807523de6c085 | 25,677 |
def make_matrix(num_rows, num_cols, entry_fn):
"""retorna a matriz num_rows X num_cols
cuja entrada (i,j)th é entry_fn(i, j)"""
return [[entry_fn(i, j) # dado i, cria uma lista
for j in range(num_cols)] # [entry_fn(i, 0), ... ]
for i in range(num_rows)] | f706773245730eab3ce6cf41b0f6e81fbe3d52ab | 25,678 |
def add_relationtoforeignsign(request):
"""Add a new relationtoforeignsign instance"""
if request.method == "POST":
form = RelationToForeignSignForm(request.POST)
if form.is_valid():
sourceid = form.cleaned_data['sourceid']
loan = form.cleaned_data['loan']
... | 44e6a80ed4596b9dae48ce8f4ed37927feb1ec71 | 25,679 |
def check_url(url):
"""
Check if a URL exists without downloading the whole file.
We only check the URL header.
"""
good_codes = [httplib.OK, httplib.FOUND, httplib.MOVED_PERMANENTLY]
return get_server_status_code(url) in good_codes | f6dede6aaf41f404c182052cd4dc5708b9a0b879 | 25,680 |
from datetime import datetime
def ap_time_filter(value):
"""
Converts a datetime or string in hh:mm format into AP style.
"""
if isinstance(value, basestring):
value = datetime.strptime(value, '%I:%M')
value_tz = _set_timezone(value)
value_year = value_tz.replace(year=2016)
return ... | 0539cd58bfa4b7ee647ac88a58bcac93108d4819 | 25,682 |
def make_signal(time, amplitude=1, phase=0, period=1):
"""
Make an arbitrary sinusoidal signal with given amplitude, phase and period over a specific time interval.
Parameters
----------
time : np.ndarray
Time series in number of days.
amplitude : float, optional
A specific ampl... | 9f940922ae2a4bf1e3ff7d1c13351f4d07c40ca8 | 25,683 |
def train_data(X, y):
"""
:param X: numpy array for date(0-5), school_id
:param y: output for the data provided
:return: return the learned linear regression model
"""
regression = linear_model.LinearRegression()
regression.fit(X, y)
return regression | abaa0ba6f02ed111b6ec9b0945e9e26c643836be | 25,684 |
import re
def clean_text(s, stemmer, lemmatiser):
"""
Takes a string as input and cleans it by removing non-ascii characters,
lowercasing it, removing stopwords and lemmatising/stemming it
- Input:
* s (string)
* stemmer (object that stems a string)
* lemmatiser (object that le... | 0bcb14378c6b72e24526c7eff9f1daf2b6871152 | 25,685 |
def make_rst_sample_table(data):
"""Format sample table"""
if data is None:
return ""
else:
tab_tt = tt.Texttable()
tab_tt.set_precision(2)
tab_tt.add_rows(data)
return tab_tt.draw() | 160b28355f1bea80878417f2a92e5dc31dde66cd | 25,686 |
def is_thunk(space, w_obj):
"""Check if an object is a thunk that has not been computed yet."""
while 1:
w_alias = w_obj.w_thunkalias
if w_alias is None:
return space.w_False
if w_alias is w_NOT_COMPUTED_THUNK:
return space.w_True
w_obj = w_alias | 1918a7d79d02a2a20e6f7ead8b7a2dc6cfe05a85 | 25,687 |
def plot_roc_curve(
fpr,
tpr,
roc_auc=None,
ax=None,
figsize=None,
style="seaborn-ticks",
**kwargs,
):
"""Plots a receiver operating characteristic (ROC) curve.
Args:
fpr: an array of false postive rates
tpr: an array of true postive rates
roc_auc (None): the... | d4d6f9d33857598a16b04097de035a5a7a3f354b | 25,688 |
def my_place_or_yours(our_address: Address, partner_address: Address) -> Address:
"""Convention to compare two addresses. Compares lexicographical
order and returns the preceding address """
if our_address == partner_address:
raise ValueError("Addresses to compare must differ")
sorted_addresses... | 991b2d44042520eea28817f33cbb9421d7b99a78 | 25,689 |
def get_dataset_json(met, version):
"""Generated HySDS dataset JSON from met JSON."""
return {
"version": version,
"label": met['data_product_name'],
"starttime": met['sensingStart'],
} | d84f3652866c83e8c1618a9f87bc3bf6b5c6a0cf | 25,690 |
def encode(value):
"""
pyg_mongo.encoder is similar to pyg_base.encoder with the only exception being that bson.objectid.ObjectId used by mongodb to generate the document _id, are not encoded
Parameters
----------
value : value/document to be encoded
Returns
-------
encoded value/docum... | fa7dec607dca66736e3b9203bf97289a0ffdd733 | 25,692 |
def locate_line_segments(isolated_edges):
"""
Extracts line segments from observed lane edges using Hough Line Transformations
:param isolated_edges: Lane edges returned from isolated_lane_edges()
:return: Line segments extracted by HoughLinesP()
"""
rho = 1
theta = np.pi / 180
threshold... | 3b26da0535b327dfac4b268552209c75481bb4d2 | 25,693 |
def proj(A, B):
"""Returns the projection of A onto the hyper-plane defined by B"""
return A - (A * B).sum() * B / (B ** 2).sum() | 982cdfb1564166dce14432bf24404f066e2acee3 | 25,694 |
def v6_multimax(iterable):
"""Return a list of all maximum values.
Bonus 2: Make the function works with lazy iterables.
Our current solutions fail this requirement because they loop through
our iterable twice and generators can only be looped over one time only.
We could keep track of the maximu... | 5539adb0dcb6c9db4f8f2f68487fc13c6aa8d067 | 25,695 |
import traceback
def format_traceback_string(exception):
"""Format exception traceback as a single string.
Args:
exception: Exception object.
Returns:
Full exception traceback as a string.
"""
return '\n'.join(
traceback.TracebackException.from_exception(exception).format... | debdf53966b26b6562671bf48d283a3bf10d85d5 | 25,696 |
def get_stored_file(file_id):
"""Get the "stored file" or the summary about the file."""
return JsonResponse(StoredFile.objects(id=ObjectId(file_id)).first()) | 860f6f5dd24e5ebaf59fff1f4c82f4b5c7ce6da5 | 25,697 |
def _compute_array_job_index():
# type () -> int
"""
Computes the absolute index of the current array job. This is determined by summing the compute-environment-specific
environment variable and the offset (if one's set). The offset will be set and used when the user request that the
job runs in a n... | 5c9b451af75f894ad49dc8aa95b7c1a80e6e9c96 | 25,698 |
def make_transpose(transpose_name, input_name, input_type, perm):
"""Makes a transpose node.
Args:
transpose_name: name of the transpose op.
input_name: name of the op to be the tranpose op's input.
input_type: type of the input node.
perm: permutation array, e.g. [0, 2, 3, 1] for NCHW ... | 21e05caed8a439f748f3fa939b5bff9864c2525d | 25,699 |
def is_batch_norm(layer):
""" Return True if `layer` is a batch normalisation layer
"""
classname = layer.__class__.__name__
return classname.find('BatchNorm') != -1 | 6494b75a3fbfbfd55ff43b05536a1094290ea915 | 25,700 |
import torch
def predictive_entropy(y_input, y_target):
"""
Computes the entropy of predictions by the model
:param y_input: Tensor [N, samples, class]
:param y_target: Tensor [N] Not used here.
:return: mean entropy over all examples
"""
y_input = torch.exp(y_input) # model output is log... | 6c3c4c3cfc93d0c19e2662b54a9b6d41146264d5 | 25,701 |
def exec_cmd(cmd_args, *args, **kw):
"""
Execute a shell call using Subprocess. All additional `*args` and
`**kwargs` are passed directly to subprocess.Popen. See `Subprocess
<http://docs.python.org/library/subprocess.html>`_ for more information
on the features of `Popen()`.
:param cmd_args:... | c946fce186e56d19c2e182e2061f4f9739a2ce59 | 25,702 |
from datetime import datetime
def roundTime(dt=None, roundTo=1):
"""Round a datetime object to any time period (in seconds)
dt : datetime.datetime object, default now.
roundTo : Closest number of seconds to round to, default 1 second.
Author: Thierry Husson 2012 - Use it as you want but don't blame me... | c17cbf9092cc2a88cb486afd1a7ff0ad984987bd | 25,703 |
from typing import OrderedDict
import requests
def get_imagery_layers(url):
"""
Get the list of available image layers that can be used as background
or foreground based on the URL to a WTML (WorldWide Telescope image
collection file).
Parameters
----------
url : `str`
The URL of ... | 9e5a37552d18ebd1994c892c2af07bd3a3445ac1 | 25,704 |
def _typecheck(op1, op2):
"""Check the type of parameters used and return correct enum type."""
if isinstance(op1, CipherText) and isinstance(op2, CipherText):
return ParamTypes.CTCT
elif isinstance(op1, PlainText) and isinstance(op2, PlainText):
return ParamTypes.PTPT
elif isinstance(op... | 872a05347ac26324e26f7444798c977f5cfad2fa | 25,705 |
def vm_update_cb(result, task_id, vm_uuid=None, new_node_uuid=None):
"""
A callback function for api.vm.base.views.vm_manage.
"""
vm = Vm.objects.select_related('dc').get(uuid=vm_uuid)
_vm_update_cb_done(result, task_id, vm)
msg = result.get('message', '')
force = result['meta']['apiview']['... | 3d7ad728cb6c3ddd8fe3638f98223635378ce8d7 | 25,706 |
from typing import Union
def _class_effective_mesh_size(
geo_graph: geograph.GeoGraph, class_value: Union[int, str]
) -> Metric:
"""
Return effective mesh size of given class.
Definition taken from:
https://pylandstats.readthedocs.io/en/latest/landscape.html
"""
class_areas = geo_grap... | fd98849f6a7ff9d9cf17ecd15a3bcd790f6dcb6f | 25,707 |
def noam_schedule(step, warmup_step=4000):
""" original Transformer schedule"""
if step <= warmup_step:
return step / warmup_step
return (warmup_step ** 0.5) * (step ** -0.5) | ad42f6f478f06c2641cb189db769c4a6e0272f6f | 25,708 |
def word_list_to_long(val_list, big_endian=True):
"""Word list (16 bits int) to long list (32 bits int)
By default word_list_to_long() use big endian order. For use little endian, set
big_endian param to False.
:param val_list: list of 16 bits int value
:type val_list: list
:... | 954d1cefc521c2f8fd88492858590df8bc0ce120 | 25,710 |
from typing import List
def _show_problems_info(id_tournament: int) -> List:
"""
Функция возвращает информацию о задачах турнира по его id(id_tournament)
"""
return loop.run_until_complete(get_request(f'https://codeforces.com/api/contest.standings?contestId=1477&from=1&count=5&showUnofficial=true'))['problems'] | 36bafa02b2523c538fefbb5d77496dfddcbda6a1 | 25,711 |
from typing import Dict
from typing import Any
def make_shell_context() -> Dict[str, Any]:
"""Make objects available during shell"""
return {
"db": db,
"api": api,
"Playlist": Playlist,
"User": User,
"BlacklistToken": BlacklistToken,
} | c2121fc95a0916021338d2b39debcc7d88933982 | 25,712 |
async def find_user_by_cards(app, cards, fields=["username"]):
"""Find a user by a list of cards assigned to them.
Parameters
----------
app : aiohttp.web.Application
The aiohttp application instance
cards : list
The list of cards to search for
fields : list, default=["username"... | ef5b20ea668b39eda51c859a3b33f1af30a644f5 | 25,713 |
def _calc_y_from_dataframe(trafo_df, baseR):
"""
Calculate the subsceptance y from the transformer dataframe.
INPUT:
**trafo** (Dataframe) - The dataframe in net.trafo
which contains transformer calculation values.
RETURN:
**subsceptance** (1d array, np.complex128) - The subs... | f6b3493dd56d93a269b2c82431a5ef0a6a7ff946 | 25,714 |
def mutual_coherence(A, B):
""""Mutual coherence between two dictionaries A and B
"""
max_val, index = mutual_coherence_with_index(A, B)
return max_val | 8e6f8d499e84394ef1af551d4fea9ab9a259c05a | 25,715 |
def pdf_page_enumeration(pdf):
"""Generate a list of pages, using /PageLabels (if it exists). Returns a list of labels."""
try:
pagelabels = pdf.trailer["/Root"]["/PageLabels"]
except:
# ("No /Root/PageLabels object"), so infer the list.
return range(1, pdf.getNumPages() + 1)
... | 133c97f4d25dc562d08a7d45c9f85cbe04776162 | 25,716 |
import torch
def transform_points_torch(points, homography):
"""Transforms input points according to homography.
Args:
points: [..., H, W, 3]; pixel (u,v,1) coordinates.
homography: [..., 3, 3]; desired matrix transformation
Returns:
output_points: [..., H, W, 3]; transformed (u,v... | f45bf1b94c360241272bc084adcf6fee1b9f3afe | 25,717 |
def _sane_fekete_points(directions, n_dim):
"""
get fekete points for DirectionalSimulator object.
use get_directions function for other use cases.
"""
if directions is None:
n_dir = n_dim * 80
elif isinstance(directions, int):
n_dir = directions
else:
try:
... | f1d0a7dfa1438f2a4071536fb048504074e8b95d | 25,718 |
def backoffPolicy(initialDelay=1.0, maxDelay=60.0, factor=1.5,
jitter=_goodEnoughRandom):
"""
A timeout policy for L{ClientService} which computes an exponential backoff
interval with configurable parameters.
@since: 16.1.0
@param initialDelay: Delay for the first reconnection at... | 679185a35f4e830ded528d59d77b2bf91a548999 | 25,719 |
def block_group(inputs,
filters,
strides,
block_fn,
block_repeats,
conv2d_op=None,
activation=tf.nn.swish,
batch_norm_activation=nn_ops.BatchNormActivation(),
dropblock=nn_ops.Dropblock(),
... | 990dae88aa1fcad078094f3a667ce5ae48f37521 | 25,720 |
def GeneratePublicKeyDataFromFile(path):
"""Generate public key data from a path.
Args:
path: (bytes) the public key file path given by the command.
Raises:
InvalidArgumentException: if the public key file path provided does not
exist or is too large.
Returns:
A publi... | a233b31c3ca2328952b09592fe054aff69c5d4ce | 25,721 |
def make_keyword_html(keywords):
"""This function makes a section of HTML code for a list of keywords.
Args:
keywords: A list of strings where each string is a keyword.
Returns:
A string containing HTML code for displaying keywords, for example:
'<strong>Ausgangswörter:</stro... | 71e35245ad7b2fe2c67f6a4c27d53374945089bd | 25,723 |
def is_match(set, i):
"""Checks if the three cards all have the same characteristic
Args:
set (2D-list): a set of three cards
i (int): characterstic
Returns:
boolean: boolean
"""
if (set[0][i] == set[1][i] and set[1][i] == set[2][i]):
return True
return False | bd4063dba02f10d7d9d4093aa8f0df8920db17b3 | 25,724 |
def notGroup (states, *stateIndexPairs):
"""Like group, but will add a DEFAULT transition to a new end state,
causing anything in the group to not match by going to a dead state.
XXX I think this is right...
"""
start, dead = group(states, *stateIndexPairs)
finish = len(states)
states.append... | 9fecae45c8cadc2ba2a4a7962416b8b31e8b1bce | 25,725 |
def test_softsign():
"""Test using a reference softsign implementation.
"""
def softsign(x):
return np.divide(x, np.ones_like(x) + np.absolute(x))
x = K.placeholder(ndim=2)
f = K.function([x], [activations.softsign(x)])
test_values = get_standard_values()
result = f([test_values])[... | 1de242e1a545ca7a182c3e3b086a551c0774d578 | 25,728 |
def run(
package_out_dir,
package_tests_dir,
work_dir,
packages):
"""Deployes build *.cipd package locally and runs tests against them.
Used to verify the packaged code works when installed as CIPD package, it is
important for infra_python package that has non-trivial structure.
Args:
pack... | 277613b42502725d751cfdc0493f545f4fb46125 | 25,729 |
def get_published_questions(quiz):
"""
Returns the QuerySet of the published questions for the given quiz
"""
questions = get_questions_by_quiz(quiz) #Questions are ordered by serial number
return questions.filter(published = True) | 19cec8b57954ae68605de1acefef57f0a68671da | 25,730 |
def moving_average(x, window):
"""
:param int window: odd windows preserve phase
From http://nbviewer.ipython.org/github/demotu/BMC/blob/master/notebooks/DataFiltering.ipynb
"""
return np.convolve(x, np.ones(window) / window, "same") | c0bd4438d54e3a26bf398f019ca40eec62db83a2 | 25,731 |
def validate_interval_avg_data(in_data): # test
"""Validates input to get_avg_since for correct fields
Args:
in_data: dictionary received from POST request
Returns:
boolean: if in_data contains the correct fields
"""
expected_keys = {"patient_id", "heart_rate_average_since"}
f... | 0fcf927c3912bea594554fdffc73312a7da4d628 | 25,732 |
def _get_cm_control_command(action='--daemon', cm_venv_name='CM', ex_cmd=None):
"""
Compose a system level command used to control (i.e., start/stop) CloudMan.
Accepted values to the ``action`` argument are: ``--daemon``, ``--stop-daemon``
or ``--reload``. Note that this method will check if a virtualen... | d6c4448da86ddd790977c4c0c150b748dd8f26b7 | 25,733 |
def get_all_db_data() -> list:
"""Возвращает все строки из базы"""
cursor.execute('''SELECT * FROM news''')
res = cursor.fetchall()
return res | 52f0e59f892898f15a361c5d1de56898f48ac2d7 | 25,734 |
def astra_projector(vol_interp, astra_vol_geom, astra_proj_geom, ndim, impl):
"""Create an ASTRA projector configuration dictionary.
Parameters
----------
vol_interp : {'nearest', 'linear'}
Interpolation type of the volume discretization. This determines
the projection model that is cho... | df3458ea09d2a9bffdced2738404aec419e7b48f | 25,735 |
def __hit(secret_number, choice):
"""Check if the choice is equal to secret number"""
return secret_number == choice | 55bee8370a2480b5ca84cd5f478fd8eb367276bd | 25,736 |
def minimal_product_data(setup_data):
"""Valid product data (only required fields)"""
return {
'name': 'Bar',
'rating': .5,
'brand_id': 1,
'categories_ids': [1],
'items_in_stock': 111,
} | ecf027704ea8533d71468527335201a021d8ae4f | 25,737 |
def flatten_column_array(df, columns, separator="|"):
"""Fonction qui transforme une colonne de strings séparés par un
séparateur en une liste : String column -> List column"""
df[columns] = (
df[columns].applymap(lambda x: separator.join(
[str(json_nested["name"]) for json_nested in x])... | 770b519a5b086d872e4bd16bc92663f693453745 | 25,738 |
from typing import List
def part2(lines: List[List[int]]):
"""
"""
grid = Grid.from_text(lines)
lim_x = grid.width()
lim_y = grid.height()
for by in range(5):
for bx in range(5):
if bx == by == 0:
continue
for dy in range(lim_y):
... | c11c452e71b61b7cda98acda6908832aec7bca60 | 25,739 |
def translate_point(point, y_offset=0, x_offset=0):
"""Translate points.
This method is mainly used together with image transforms, such as padding
and cropping, which translates the top left point of the image
to the coordinate :math:`(y, x) = (y_{offset}, x_{offset})`.
Args:
point (~nump... | fffd18a2df12e8d51b0ea30fe378da37aa245d5d | 25,740 |
def _get_tau_var(tau, tau_curriculum_steps):
"""Variable which increases linearly from 0 to tau over so many steps."""
if tau_curriculum_steps > 0:
tau_var = tf.get_variable('tau', [],
initializer=tf.constant_initializer(0.0),
trainable=False)
tau_... | a4ba777a70df55f22299e415e7998dc303c0b3cf | 25,741 |
def des_descrypt(s):
"""
DES 解密
:param s: 加密后的字符串,16进制
:return: 解密后的字符串
"""
iv = constants.gk
k = des(iv, CBC, iv, pad=None, padmode=PAD_PKCS5)
#print binascii.b2a_hex(s)
de = k.decrypt(binascii.a2b_hex(s), padmode=PAD_PKCS5)
print de
return de | 2a1224ec5a197928aedc6b4168762bac7f287624 | 25,742 |
def get_compound_coeff_func(phi=1.0, max_cost=2.0):
"""
Cost function from the EfficientNets paper
to compute candidate values for alpha, beta
and gamma parameters respectively.
These values are then used to train models,
and the validation accuracy is used to select
the best base parameter... | ec2e3e07a93741827c934e05d2e4e7e5e4a54901 | 25,744 |
import re
def get_kver_bin(path, split=False, proc=None):
"""
Get version of a kernel binary at 'path'. The 'split' and 'proc' arguments are the same as in
'get_kver()'.
"""
if not proc:
proc = Procs.Proc()
cmd = f"file -- {path}"
stdout = proc.run_verify(cmd)[0].strip()
msg... | 212da809d1c2dc52e7bf7cee2aafd89d9437eadb | 25,745 |
from datetime import datetime
def post_apply_become_provider_apply_id_accept(request: HttpRequest, apply_id, **kwargs) -> JsonResponse:
"""
允许成为设备拥有者
:param request: 视图请求
:type request: HttpRequest
:param kwargs: 额外参数
:type kwargs: Dict
:return: JsonResponse
:rtype: JsonResponse
"... | 1440d2ae9495b75c398000d3367d68fdb84f2c00 | 25,746 |
import tokenize
def get_var_info(line, frame):
"""Given a line of code and a frame object, it obtains the
value (repr) of the names found in either the local or global scope.
"""
tokens = utils.tokenize_source(line)
loc = frame.f_locals
glob = frame.f_globals
names_info = []
names =... | d584e1c83a9bf7d0134be1251b92cb789a7ac51c | 25,747 |
from typing import Union
from typing import Optional
def MPS_SimAddRule(event_mask: Union[IsoSimulatorEvent,
FeliCaSimulatorEvent,
VicinitySimulatorEvent,
NfcSimulatorEvent,
... | d945885635eba27c74edb33eb72e6bac3791a190 | 25,749 |
import json
def to_pretty_json(obj):
"""Encode to pretty-looking JSON string"""
return json.dumps(obj, sort_keys=False,
indent=4, separators=(',', ': ')) | b325c4e6e150e089da1d9027299831bd1576e57f | 25,751 |
def parse_access_token(request):
"""Get request object and parse access token"""
try:
auth_header = request.headers.get('Authorization')
return auth_header.split(" ")[1]
except Exception as e:
return | a51d51d83cba5fc8e8eb7b9a9147a0219e2bcb20 | 25,752 |
def postscriptWeightNameFallback(info):
"""
Fallback to the closest match of the *openTypeOS2WeightClass*
in this table:
=== ===========
100 Thin
200 Extra-light
300 Light
400 Normal
500 Medium
600 Semi-bold
700 Bold
800 Extra-bold
900 Black
=== ======... | 4521375a668c81fdee9a3fc20391f633a60af777 | 25,753 |
def down_spatial(in_planes, out_planes):
"""downsampling 21*21 to 5*5 (21-5)//4+1=5"""
return nn.Sequential(nn.Conv2d(in_planes, out_planes, kernel_size=5, stride=4),
nn.BatchNorm2d(out_planes)) | 2570eb4f837d45a3683f8594ef9ba0fa5b996445 | 25,754 |
def add_integral_control(
plant, regulator=None, integrator_ugf=None,
integrator_time_constant=None, **kwargs):
"""Match and returns an integral gain.
This function finds an integral gain such that
the UGF of the integral control matches that of the specified
regulator.
If ``integra... | 16c6efe598e60e325f7be2fe018156f89deaac11 | 25,755 |
def script():
"""Render the required Javascript"""
return Response(response=render_template("settings/settings.js"),
status=200,
mimetype="application/javascript") | d879fded0ebf2e160d3dcbc541ae07bc08571b8e | 25,756 |
def repr_helper(tuple_gen_exp, ind=2):
""" given a sequence of 2-tuples, return a nice string like:
.. code_block:: python
(1, 'hi'), (2, 'there'), (40, 'you') ->
.. code_block:: python
[ 1] : hi
[ 2] : there
[40] : you
"""
lines = []
k_v = list(tuple_gen_exp)... | a80739ac09167ce582bf35dc8e7ce1c7654ba6e2 | 25,757 |
from IPython import get_ipython
def in_ipython() -> bool:
"""Return true if we're running in an IPython interactive shell."""
try:
return get_ipython().__class__.__name__ == 'TerminalInteractiveShell'
except Exception:
pass
return False | f0a92dfc8c02da2761c5f2074b3928943e7abd8f | 25,758 |
def demo_loss_accuracy_curve():
"""Make a demo loss-accuracy curve figure."""
steps = np.arange(101)
loss = np.exp(-steps * 0.1) * 20. + np.random.normal(size=101) * 2.
loss = loss - np.min(loss) + .2
valid_steps = np.arange(0, 101, 10)
valid_loss = (np.exp(-valid_steps * 0.1) * 25. +
... | 1d530d0f4f6c830a974fd634c636f691595f1d38 | 25,759 |
def text_filter(sentence:str)-> str:
"""
过滤掉非汉字和标点符号和非数字
:param sentence:
:return:
"""
line = sentence.replace('\n', '。')
# 过滤掉非汉字和标点符号和非数字
linelist = [word for word in line if
word >= u'\u4e00' and word <= u'\u9fa5' or word in [',', '。', '?', '!',
... | 9c0949b2e9b374f1aa5392b5a4c215ebff21171b | 25,761 |
import math
def get_lr_schedule(base_lr, global_batch_size, base_batch_size=None,
scaling=None, n_warmup_epochs=0, warmup_factor=-1, decay_schedule={}, is_root=True):
"""Get the learning rate schedule function"""
if scaling == 'linear':
scale_factor = global_batch_size / base_batch... | 385d9f01992dc650732420580803b147068f70fc | 25,762 |
import math
def stdp_values(values, period=None):
"""Returns list of running population standard deviations.
:param values: list of values to iterate and compute stat.
:param period: (optional) # of values included in computation.
* None - includes all values in computation.
:rtype: list of w... | b3be172dc377325b75ac7f8fe908751b47ecca58 | 25,763 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.