content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def logs(request, tplname="core/logs.html"):
"""Return a list of log entries.
This view is only called the first time the page is displayed.
"""
page = get_logs_page(request, 1)
return render_to_json_response({
"callback": "logs",
"content": render_to_string(tplname, {"logs": page.... | a43b52533a0dc67a65b6ab3753a79754f97da26e | 3,604,400 |
def log_out():
"""Log user out"""
# Remove user from session
del session['user']
return redirect("/") | cf8dece3e216d96df3678d63bcd7a2a9dc84dbe9 | 3,604,401 |
def square_of_sum(limit):
""" Returns the square of the sum of all integers in the range 1 up to and
including limit.
"""
return sum([i for i in range(limit + 1)]) ** 2 | 503048c7b175d10dce20ff9d2f9435be4fbe1c35 | 3,604,402 |
def expand_unique_results(y, idx):
"""Inverse of unique_bitstrings_with_counts.
Args:
y: Values to pick according to `idx`.
idx: The index at which to place each value of `y` in the output.
Returns:
expanded: `tf.Tensor` such that `expanded[i] == y[idx[i]]`.
"""
expanded = tf.gather(y, idx, axis... | 4d8df1d42b1b437c722ad84cc967679860752c6b | 3,604,403 |
def create_news_abc(schedule_model):
"""Abstract base news model factory.
:param schedule_model: Schedule model to use as news's schedule.
:type schedule_model: Any concrete schedule model of abc models from
:func:`~create_abc_schedule` factory function.
:returns: A abstract base news model.
... | c2572992175f990f557cc02db5010fb62d83c5ca | 3,604,404 |
def ResNet18(include_top=True,
weights=None,
input_tensor=None,
input_shape=None,
pooling=None,
classes=1000,
use_bias=False,
block_fn=vanilla_block,
**kwargs):
"""Instantiates the ResNet18 architecture."""
... | 240127eb117366849de2cdc5d7d6b95d26d96c2a | 3,604,405 |
def sigmoid2(temperature, b, c):
"""The two parameter sigmoid function from Chuine 2000
The full equation is f(x) = 1 / (1 + exp(b*(temp -c)))
The scipy.special.expit function = 1/(1+(-x))
Using float32 increases speed significantly over
the default float64
Parameters
----------
tem... | 44f8af88df2363e4cbe34f5388e5765bbb61de48 | 3,604,406 |
def empty():
"""
This matcher matches any collection-like object that responds to the
__len__ method, and has a length of 0.
"""
return IsEmpty() | ead89734a3768f8cbdd1c0345fb2e3ada2ee5e0d | 3,604,407 |
def calc_VCC(mdot_kgpers, T_sup_K, T_re_K, q_nom_chw_W, number_of_VCC_chillers):
"""
For th e operation of a Vapor-compressor chiller between a district cooling network and a condenser with fresh water
to a cooling tower following [D.J. Swider, 2003]_.
The physically based fundamental thermodynamic mode... | 204f723ef1034a7183c2b3951b6e26d89badb9c4 | 3,604,408 |
def version_to_str(version): # type: (t.Tuple[int, ...]) -> str
"""Return a version string from a version tuple."""
return '.'.join(str(n) for n in version) | 6f0ebb96c944645b228fec6f05aeb65d9d6d3374 | 3,604,409 |
def _get_testcase(_):
"""Retrieve the json representation of the test case with the given id."""
# TODO(mbarbella): Actually fetch the test case info from the server.
testcase_json = {
'crash_state': '',
'security_flag': False,
'gestures': [],
'flaky_stack': False,
'job_definition': ... | 9e66391edfe463e71ddbf418f405c3fc2c9e0f01 | 3,604,410 |
from typing import Optional
from typing import Any
import logging
def get_logger(name: Optional[str] = None, **kwargs: Any) -> Logger:
"""Return a logger with the specified name.
:param name: Logging channel name, defaults to None.
:returns: Logger instance.
.. seealso::
:py:func:`logging.g... | c300b87d622f3a0d01a0a6fa24e0f9e6000d32ce | 3,604,411 |
def has_duplicate(sampled_clumper):
"""Checks for a duplicate"""
for i in range(len(sampled_clumper)):
source_clump = sampled_clumper[i]
for j in range(len(sampled_clumper)):
if i != j:
if sampled_clumper[j] == source_clump:
return True
return ... | d34dc7de8d84b1dc9e1b65e0a83b9cefcbed8055 | 3,604,412 |
def _resolve_expressions(expression_chain):
""" Given a chain of intermittend expressions and operators, resolve it
into single expression by taking priority rules into account.
"""
chain = expression_chain.copy()
for ops in TOKEN_PRECEDENCE:
i = 0
while i < len(chain):
i... | 2975b3aa51d8451ed9c7f3a916f93b9eb9d28f18 | 3,604,413 |
def subtract_noise_from_squared_rir(data, noise_level='auto'):
""" Subtracts the noise energy level from the squared RIR. Note, that the
RIR has to be squared before.
Parameters
----------
data : ndarray, double
The squared room impulse response with dimension [..., n_samples]
Retu... | 0ea7ae47b0d05a4b10a788a47eae43e7165e35af | 3,604,414 |
import time
import os
import gc
def impute_ard(typed_file, genotype_file, output_file, population_file, markers_file, masked_file=None, window_size=100,
maf = 0, weight_optimization=True, weights_file=None, verbose=False, snpid_check=False, gpu=False):
"""Usage:
typed_file (required) specif... | 5304089f81113e77bf4145359ad571de9175f34e | 3,604,415 |
def compute_spherical_volume(radius):
"""
Given radius, return volume of corresponding sphere.
Args:
radius (float): radius of sphere
Returns:
(float): volume of sphere
"""
volume = 4.0/3.0 * np.pi * radius**3
return volume | 4536a386274e617ac23fba12d50aed6b38a46079 | 3,604,416 |
import re
def is_valid_regex(regex):
"""Helper function to determine whether the provided regex is valid.
Args:
regex (str): The user provided regex.
Returns:
bool: Indicates whether the provided regex was valid or not.
"""
try:
re.compile(regex)
return True
... | 4c544168f2b1894e7cc7c7804342f923287022b5 | 3,604,417 |
from typing import Iterable
from re import T
from typing import Iterator
def take_last(iterable: Iterable[T], n: int) -> Iterator[T]:
"""
take only the last n elements of the iterable.
>>> list(take_last(range(1000), 3))
[997, 998, 999]
"""
return deque(iterable, maxlen=n) | c6fab277038ff512683c38d9ce5986788c19d152 | 3,604,418 |
def make_rigidgroups_data(prot):
"""
ziyao: this function generates all rigid-groups-related keys including:
[
'rigidgroups_gt_frames',
'rigidgroups_gt_exists',
'rigidgroups_group_exists',
'rigidgroups_group_is_ambiguous',
'rigidgroups_alt_gt_frames'
]
"""
# ziyao: this function assumes ... | 782364d866a37cf0d4730dc7c950ad69abbb1ae9 | 3,604,419 |
def map_header(values):
"""
Map the values generated with the hypothesis-ros header strategy to a rospy header type.
"""
if not isinstance(values, _Header):
raise TypeError('Wrong type. Use appropriate hypothesis-ros type.')
ros_header = Header()
ros_header.seq = values.seq
ros_heade... | 13c4ae25b0a00b6cbb3dda7b9540e0a7a30c073d | 3,604,420 |
def markov_order_tests(a, max_order=5, text_len=10000, verbose=False):
"""Tests of the Markov order inferrer using Markov chains of diff. orders.
"""
result = []
max_estimated_order = max_order + 2
for real_order in range(max_order):
print "Actual Markov order:", real_order
s = rando... | 33aa4eaf44eb182db843003c2596fcef238ec8b3 | 3,604,421 |
def getCurKlines(quote_ctx, stockCode, ktype, num):
""" 得到实时K线 """
# 订阅股票的各种K线种类
sub_type_list = ["K_1M", "K_5M", "K_15M", "K_30M", "K_60M", "K_DAY", "K_WEEK", "K_MON"]
for sub_type in sub_type_list:
ret_status, ret_data = quote_ctx.subscribe(stockCode, sub_type)
if ret_status != RET_OK:... | 11a1e548231d7653530cf6cc5501fda87bbe4570 | 3,604,422 |
def shell_wrap_command(command):
"""wraps the given command in a shell invocation.
default shell is /bin/bash (like Fabric)
no support for configurable shell at present"""
# '-l' is 'login' shell
# '-c' is 'run command'
shell_prefix = "/bin/bash -l -c"
escaped_command = _shell_escape(comma... | 4bf2a1bd553f9a1ff474c4d7894a3d32669c25a2 | 3,604,423 |
import time
def submit_onboarding():
"""
Parse onboarding as if it were a request sent from the
active agent, rather than coming as a request from the router.
"""
router_incoming_timestamp = time.time()
data = request.get_json()
provider_data = data["provider_data"]
agent_id = provider... | ee44b7b158402737ac39a19087ceffc252428da9 | 3,604,424 |
def spatial_overlap_conv_3x3_stride_1_dilate_2(p):
"""
This method computes the spatial overlap of dilated 3x3 convolutional layer with stride 1 and dialation rate of 2 in terms
of its input feature map's spatial overal value (p).
"""
denominator = 9 - 24 * max(p - 0.5, 0)
if p < 0.5:
r... | 91a6bd178e7dcad6e21ad7fa58df28aaf1ad279b | 3,604,425 |
def temporal_autocorrelation_multivariate(
x, d=0, mask=None, window="gaussian", window_radius=np.inf
):
"""
For a :math:`q`-variate time series
:math:`\mathbf{x}_1,\mathbf{x}_2,\dots,\mathbf{x}_n`, compute the lag-l
correlation matrices :math:`\mathbf{\Gamma}_l`, where
:math:`\Gamma_{l,i,j}=\ga... | 6f62025e2ea12ad52e0e8b60f3be6ee006dc0f6f | 3,604,426 |
def normalize_medical_kind(shape, properties, fid, zoom):
"""
Many medical practices, such as doctors and dentists, have a speciality,
which is indicated through the `healthcare:speciality` tag. This is a
semi-colon delimited list, so we expand it to an actual list.
"""
kind = properties.get('k... | dbf75799624cbe119c4c3a74c8814d0a979d828e | 3,604,427 |
def _get_tws(sel_cim_data):
"""Return terrestrial water storage."""
return sel_cim_data.TWS_tavg | 2b8405a245d39466ef2b47463d88518cc3b5bedf | 3,604,428 |
import os
import sys
def add_to_path(path):
"""Add the specified path to the system path.
@param path: Path to add.
@return True if path was added. Return false if path does not exist or path was already in sys.path
"""
if os.path.exists(path) and path not in sys.path:
sys.path.insert(0, ... | 8e57968a2384e80959a30f97267d2ea8a5650ce1 | 3,604,429 |
import warnings
def eq_wefli(wair,entr=None,wetf=None,wliq=None,wice=None,airf=None,
temp=None,pres=None,dhum=None,dliq=None,chkvals=False,
chktol=_CHKTOL,airf0=None,temp0=None,pres0=None,dhum0=None,
dliq0=None,chkbnd=False,mathargs=None):
"""Get equilibrium values at WEF or WLI.
Get the valu... | c005f3297c1609d6695cf01e9ecdc662a7ef0368 | 3,604,430 |
def get_project(connection, name, error_msg=None, throw_error=True,
whitelist=[('ERR001', 500), ('ERR014', 403)]):
"""Get a specific project that the authenticated user has access to.
Args:
connection: MicroStrategy REST API connection object
name (string): MicroStrategy project... | 0b7ff2c9ca1debe15bcc11a4f4c246c1ffee9f6f | 3,604,431 |
import torch
def load_graph(pt_file_path="./sample_graph.pt"):
"""
Parameters
----------
pt_file_path : file path
Returns
-------
graph : torch_geometric.data.Data
- data.n_node: number of nodes
- data.n_node_type: number of node types == (1 or 2)
- data.n_edge: nu... | a45304199c92527e4b3e48430c8ac0f9f59a74d5 | 3,604,432 |
def _is_number(data):
"""
Test whether input is numeric array rather than datetime or strings.
"""
return len(data) and np.issubdtype(_to_array(data).dtype, np.number) | 9cf05f4cb0e1fc64841f6fbeffa9834b11bc74fb | 3,604,433 |
def duffing(x, u, dt=0.05, delta=0.2):
"""Duffing's oscillator"""
dxdt = (x[1], x[0] - delta*x[1] - x[0]**3 + u)
return x[0] + dt*dxdt[0], x[1] + dt*dxdt[1] | ef193499ce213a1848a2482fdb13c53227e464d0 | 3,604,434 |
def yearly_aggregator(date: pd.Timestamp, end_of_year: pd.Timestamp):
"""Округляет дату вверх до месяца и числа конца года
Parameters
----------
date
Дата, для которой необходимо рассчитать годовую агрегацию
end_of_year
Пример даты окончания года - ее месяц и число используются для ... | 829363ef21aee394e6ed29db11f8af508bfcda1b | 3,604,435 |
from typing import Optional
def encode(hrp: str, witver: int, witprog: bytes) -> Optional[str]:
"""Encode a segwit address."""
spec = Encoding.BECH32 if witver == 0 else Encoding.BECH32M
ret = bech32_encode(hrp, [witver] + convertbits(witprog, 8, 5), spec)
if decode(hrp, ret) == (None, None):
... | 039d403d481ae9738146779832d8b02a9a587be1 | 3,604,436 |
def flac_read_s32(data: bytes) -> DecodedSoundFile:
"""Reads and decodes the whole flac audio data. Resulting sample format is 32 bits signed integer."""
with ffi.new("unsigned int *") as channels, \
ffi.new("unsigned int *") as sample_rate, \
ffi.new("drflac_uint64 *") as num_frames:
me... | f61029972b441e7c8a47d7ddb4aecbab78bbdbe9 | 3,604,437 |
def isEmptyIter(it):
"""Return True iff the iterator is empty or exhausted"""
return next(it, _nothing) is _nothing | 468c6825d77ebb47b05487e16dd3c9afc8beee6f | 3,604,438 |
def encode(lonlat, length=12):
"""Encode a (lon,lat) pair to a GeoHash."""
assert len(lonlat) == 2, "Invalid lon/lat: %s"%lonlat
# Half the length for each component.
length //= 2
lon = _float_to_bits(lonlat[0], lower=-180.0, upper=180.0, length=length*5)
lat = _float_to_bits(lonlat[1], lower=-90.0, upper=9... | 9ae3ce1cbac1c3c77726a565e211f5f3cc0521a9 | 3,604,439 |
def parse(data, template, prefix=''):
""" Parse json """
if isinstance(data, dict):
data = data.items()
elif isinstance(data, list):
data = enumerate(data)
else:
return data
for name, value in data:
name = (str(prefix) + '_' + str(name)).strip('_')
if isinstan... | 02e395af23c6eea2bbb9a5615501cd996af2732e | 3,604,440 |
def brownian_trajectories_generator(n_part=5,
n_times=100,
p_disapear=0,
sigma=1.,
init_dispersion=10.,
seed=None):
"""Build and return ... | 30ac33b403393da4f69261f3805c27295dcbcf76 | 3,604,441 |
def rpn_class_loss_graph(rpn_match, rpn_class_logits):
"""RPN anchor classifier loss.
rpn_match: [batch, anchors, 1]. Anchor match type. 1=positive,
-1=negative, 0=neutral anchor.
rpn_class_logits: [batch, anchors, 2]. RPN classifier logits for BG/FG.
"""
# Squeeze last dim to simpli... | 1c0b04381abeacecfc72c1475d8731d132660ce9 | 3,604,442 |
def merge_arrays(*lsts: list):
"""Merges all arrays into one flat list.
Examples:
>>> lst_abc = ['a','b','c']\n
>>> lst_123 = [1,2,3]\n
>>> lst_names = ['John','Alice','Bob']\n
>>> merge_arrays(lst_abc,lst_123,lst_names)\n
['a', 'b', 'c', 1, 2, 3, 'John', 'Alice', 'Bob']... | f2dd78a9e2d31347d72e1e904c0f2c6e30b37431 | 3,604,443 |
def rotTransMatrix(axis, s, c, t):
"""
build a rotate * translate matrix - MUCH faster for derivatives
since we know there are a ton of zeros and can act accordingly
:param axis: x y or z as a character
:param s: sin of theta
:param c: cos of theta
:param t: translation (a 3 tuple)
:retu... | bf9bdbcff086ef7be52a3742316d4883d3bf70a3 | 3,604,444 |
import hashlib
def sha256(msg):
"""Return the sha256 hash of the passed data. Non binary data is automatically converted
>>> hexlify(sha256("e hat eye pie plus one is O"))
b'c5b94099f454a3807377724eb99a33fbe9cb5813006cadc03e862a89d410eaf0'
"""
msg = anything2bytes(msg)
return hashlib.new('sh... | 49ffa2bd96eea5e98fdd030469e2a08a599a9357 | 3,604,445 |
def fast_pow(x, y):
"""Fast power x^y for x > 0. Reproduces `FastPow()` in the C library.
An approximation of x^y with about 0.5% relative error.
Limitations:
- Assumes x is positive and finite.
- Assumes 1e-37 <= |x^y| <= 1e37, i.e. that the exact result would be
neither very large nor very close to... | 282a88d510de89bc507e025812832365c0959699 | 3,604,446 |
def get_file_to_save(win, oms='', extension='', start=''):
"""toon een dialoog waarmee een file geopend kan worden om te schrijven
"""
what = shared.get_open_title(win, 'C_SELFIL', oms)
fname, ok = qtw.QFileDialog.getSaveFileName(win, what, filter=extension)
return fname | 57899b4c8d5c40f401178cd3d72c9bdb86522a9f | 3,604,447 |
def check_requirements(
filename=DEFAULT_FILE,
errors_only=False, spec_only=False, latest=False, location=False):
""" Check requirements against installed versions and print status lines
for all of them.
"""
reqs = Requirementz.from_file(filename=filename)
if len(reqs) == 0:
... | e7c3845d7978a3609918508b32cb9ac3b87f8874 | 3,604,448 |
def _sample_mean(values):
"""Mean over sample indices. In this module this is always [0]."""
return math_ops.reduce_mean(values, reduction_indices=[0]) | 2c42ebd2c6d3b97625436b9bbf2766825d804fbd | 3,604,449 |
import gzip
import bz2
def open_zipped(infile, mode='r'):
"""Open a regular, gzipped, or bz2 file.
If infile is a file handle or text device, it is returned without
changes.
Returns
-------
text mode file handle.
"""
mode = mode[0] + 't'
if hasattr(infile, 'write'):
ret... | 345ad46c2dc113961d74d29c44f88a6be7b74526 | 3,604,450 |
def get_Theta_ex_a_Ave(Theta_ex_d_t):
"""年平均外気温度[℃] (1)
Args:
Theta_ex_d_t(ndarray): 外気絶対温度[K]
Returns:
ndarray: 年平均外気温度[℃]
"""
return np.sum(Theta_ex_d_t) / 8760 | 125a12ed4586e9df90fdc23e9152b0a2f9a38938 | 3,604,451 |
def delete_entry(request, entry_id):
"""
Give the user the ability to delete a log entry, with a confirmation
beforehand. If this method is invoked via a GET request, a form asking
for a confirmation of intent will be presented to the user. If this method
is invoked via a POST request, the entry wi... | 34e423972b3965f9642e3ae23aefcc4ac96812f0 | 3,604,452 |
def build_full_multi_view_cnn_forward_pass_with_features(
model,
H,
W,
views,
depth_planes,
padding,
depth_range_min,
depth_range_max,
sampling_scheme
):
"""
Arguments
---------
model: the Keras model to be used for feature extraction
H: int, the height of... | 79c81aef4b0dcf4255b1a064fcc0e7bd2a225906 | 3,604,453 |
def conv3x3(in_channels: int, out_channels: int, stride: int = 1, padding: int = 1) -> nn.Conv2d:
"""3x3 convolution for resnet block."""
return nn.Conv2d(in_channels, out_channels, kernel_size=3, stride=stride, padding=padding, bias=False) | d355bdec243787a34fa801eff9051cbb6645b796 | 3,604,454 |
import os
import sqlite3
def connect_to_sqlite():
"""
Connects to sqlite database or create it if does not exists
"""
f = os.path.join(_config.get('directories', 'storage'), 'save_tv.sqlite')
c = sqlite3.connect(f)
s = 'CREATE TABLE IF NOT EXISTS shows '
s += '(id text primary key, title t... | 52fde05f3162074f1df4cd9fc7b0fd8ead2ca395 | 3,604,455 |
from typing import Callable
def nlsvm_solve(X: np.ndarray, y: np.ndarray, classes: tuple[str, str], cost: float, kernel: Callable) -> Callable:
"""
训练一个SVM二分类器
:param X: 训练数据的特征矩阵,n行,dim列,dim为数据维数,每一行为一个训练样本,每一列为一个特征
:param y: 训练数据的标签矩阵,n行,1列,取值为-1或1
:param classes: 长度为2的字符串元组,表示当前用于训练的二分类
:pa... | cbb8fd656214508c7d83901508a06402a1b52c9a | 3,604,456 |
import os
def augment_audio_with_sox(path, sample_rate, tempo, gain, channel=-1): # channels: -1 = both, 0 = left, 1 = right
"""
Changes tempo and gain of the recording with sox and loads it.
"""
with NamedTemporaryFile(suffix=".wav") as augmented_file:
augmented_filename = augmented_file.nam... | eff4a03cfe7af247efb41f0e496801990990c957 | 3,604,457 |
import argparse
import sys
def parse_args(args):
""" Create the arguments """
parser = argparse.ArgumentParser()
parser.add_argument("-u", dest="user", help="Username", default="user")
parser.add_argument("-p", dest="passwd", help="Password", default="user")
parser.add_argument("-k", dest="key_pat... | 479d5127503c367e78d81935d987f3149fd48ce1 | 3,604,458 |
import logging
def hset_object(client, field, key, src_data):
"""Add value from configured redis under specified key of certain hashtable
:param client: redis client object
:param field: string
:param key: string
:param src_data: bytestream, int, string
:return: True if src_data was added to ... | cd7859b683cd18a6a4e314df22245991c6ebc36f | 3,604,459 |
def matrix_median_blur_fcn(matrix,size):
"""Function to apply median blur to the matrix that represents sarcomeres as voxels."""
matrix_blur = median_filter(matrix_blur, size=size)
return matrix_blur | b8e306d2af3007e07939a793e1a8e1f767e43c0f | 3,604,460 |
def get_pystache_parsed(mustache_file):
"""Return a ParsedTemplate instance based on the contents of
$mustache_file."""
with open(mustache_file, "r") as file_:
parsed = pystache.parse(file_.read())
return parsed | eb4f57bf8ffce628cf10470d61a6b0b850ff5621 | 3,604,461 |
def lngamma(x):
"""
lngamma(x) -> number
Return logarithm of gamma(x).
"""
res, x = _init_check_mpfr(x)
gmp.mpfr_lngamma(res, x, gmp.MPFR_RNDN)
return mpfr._from_c_mpfr(res) | e002190cbbd5ec9b31261eb2bf3bbd3d3cb2f740 | 3,604,462 |
def bytes2hex(byte_string: bytes) -> str:
"""Return a hex string representation of encoded bytes."""
s = b2a_hex(byte_string).decode()
return " ".join(s[i:i + 2] for i in range(0, len(s), 2)) | 35f1836f442234040a7fa47c8ee432bb7e429387 | 3,604,463 |
def sample_encoding(X, interaction_times, batch_size, k,
sequence_length,
first_indices,
second_indices,
gate_type='sum',
norm_type='l2'):
"""
input X: embedding inputs or max-pooling outputs
output: ... | 036e695355fcb1f51934298c34c7e9f2f790223b | 3,604,464 |
def is_method_request(topic: str, method_name: str = None) -> bool:
"""
Determine if a topic string is for a method request.
:param str topic: The topic to test
:returns: True if the topic is for a method request.
"""
if constants.EDGEHUB_TOPIC_RULES:
is_method = topic.startswith("$iot... | 78b7948e7a50dd0ec0d96884599288c30e5a89b7 | 3,604,465 |
def phone_setup_iwlan(log,
ad,
is_airplane_mode,
wfc_mode,
wifi_ssid=None,
wifi_pwd=None):
"""Phone setup function for epdg call test.
Set WFC mode according to wfc_mode.
Set airplane mode according... | 60f87427bf1d51185d1e1fe6339b083c445b6b37 | 3,604,466 |
from typing import OrderedDict
def join_values(x,column_types):
"""This function filters out the most likely sector and subsector codes assigned to a building
In an OSM dataset, based on a mapping of building attributes to macroeconomic sectors
Based on our mapping a building might be either ass... | 3767f6f8242def2e69cbd5b5c5311c923c2a9539 | 3,604,467 |
def is_within_range(num, lower_bound: int, upper_bound: int) -> bool:
"""
check if a number is within a range bounded by upper and lower bound
:param num: target number needs to be checked against
:param lower_bound: exclusive lower bound
:param upper_bound: exclusive upper bound
:return: True ... | 325f4084a88254ec2f29dd28749b8709de394078 | 3,604,468 |
from typing import Optional
from typing import Tuple
def _shape_param_to_id_str(shape_param: Optional[Tuple[Optional[int], ...]]) -> str:
"""Convert kernel input shape parameter used in `test_call.py` and `conftest.py`
into a human readable representation which is used in the pytest parameter id."""
if s... | ba73efa0693217a32ba42754af36204631c4200d | 3,604,469 |
def structural_holes(graph,includeOutLinks=True,includeInLinks=False,wholeNetwork=True):
"""
Calculate each node's contraint / structural holes value, as described by Ronal Burt
Parameters
----------
G : graph
a networkx Graph or DiGraph
includeInLinks : whether each ego network should include nodes which... | 89c469376475fd4ed9305819fc646b7181765b9d | 3,604,470 |
from typing import Optional
from typing import Sequence
def get_service_principals(application_ids: Optional[Sequence[str]] = None,
display_names: Optional[Sequence[str]] = None,
ignore_missing: Optional[bool] = None,
object_ids: Optiona... | 592aff76fef710e44d04dacf52f263b62e943773 | 3,604,471 |
import requests
from io import StringIO
import pandas
def send_request(**kwargs):
"""Return a data frame from a web service request to cBio portal.
Sends a web service requrest to the cBio portal with arguments given in
the dictionary data and returns a Pandas data frame on success.
More information... | 4526c46960c8ea3f30727a0e0e998c9d914e6021 | 3,604,472 |
from typing import Dict
from typing import List
def map_account_for_insert(file_id, gab_id, account_json) -> Dict[str, List[Dict]]:
"""
Takes JSON object for the gab user account, and the Gab ID of the Gab this user
account information was fetched with, and returns an SQL insert statement, ready
to be... | 7ff23a991faa3b1a60aaceba1371630e044a10b5 | 3,604,473 |
import time
def load_dataframe(db, code, filename=None):
"""
打印/加载* DataFrame by code, or save into filename
"""
begin_time = time.time()
sql = "select date, open, close, high, low, volume, turnover from sk_stock_daily_data where code='%s'" % code
with db.cursor(cursorclass=MySQLdb.cursors.Dic... | 56bd3c52dc432ef9217366acd78ba1c259671974 | 3,604,474 |
def restore_model(model_path):
"""
直接指定模型
:param model_path:
:return:
"""
print("恢复模型:",model_path)
# tf.reset_default_graph()
params={}
g = tf.get_default_graph()
with g.as_default():
#从pb模型直接恢复
sess = tf.Session(config=tf.ConfigProto(allow_soft_placement=Tru... | 904fba4950b98198e42f93b24aa232c44260fe62 | 3,604,475 |
def graph_to_str(graph):
"""
Convert a NetworkX graph to a string. This one represents its adjacency matrix.
:graph: The NetworkX graph.
:return: The string of the graph.
"""
adjacency_matrix = np.array(to_adjacency_matrix(graph))
graph_row_str = []
for row in adjacency_matrix:
graph_row_str.append(''.join... | 1b33e240b3cc4b52f41911084d15bbdb005b5a1d | 3,604,476 |
def get_travel_time(catalog):
"""Find the time between origin and propagation"""
v_mean = FLAGS.v_mean
coordinates = [(lat, lon, depth)
for (lat, lon, depth) in zip(catalog.latitude,
catalog.longitude,
... | a14bf2461eac8dd688c27c55745f4261360b2d70 | 3,604,477 |
import pandas
def estimate_test_percentages_for_regions(df: pandas.DataFrame) -> pandas.Series:
""" Calculates the fraction of tests per region.
Uses the 7 days up to the last day for which daily new_test data is available for all regions.
WARNING: If any region has a gap _before_ the last day for which... | a422f4621cc76d8bb0819ab6a1f12996da962a46 | 3,604,478 |
def make_blueprint(db_connection_string=None):
"""Create blueprint.
"""
controllers = Controllers(db_connection_string)
# Create instance
blueprint = Blueprint('datarecords', 'datarecords')
# Controller Proxies
@check_permission([Permissions.datarecordListAll, Permissions.datarecordLi... | 71b29d2691401617942c6e91192f9cdb19ca79b4 | 3,604,479 |
def get_circulate_supply(endpoint=_default_endpoint, timeout=_default_timeout) -> int:
"""
Get current block number
Parameters
----------
endpoint: :obj:`str`, optional
Endpoint to send request to
timeout: :obj:`int`, optional
Timeout in seconds
Returns
-------
int
... | ad61a3ddc625f70fa0a956ba06587b772bef03a9 | 3,604,480 |
def get_atom_ids_sorted_type(species):
"""
Get a list of atom ids sorted by increasing atomic weight, useful for when
a molecular graph depends on the order
of atoms in what will be considered bonded
Arguments:
species (autode.species.Species):
Returns:
(list(int)):
"""
... | f825f9734d61b4850e907f949b4db4a403e55fff | 3,604,481 |
def get_install_soft_current():
"""
for line chart and radar
:return:
"""
soft_install_list = install_softgame_current("soft")
if soft_install_list != "no data":
return jsonify({"softtop5": soft_install_list[0: 5],
"softtop10": soft_install_list[5: 10]})
else:... | b8b47e19c6ba31d22a128b4496462c5492022e51 | 3,604,482 |
def Shuffle(pcoll):
"""Shuffles a PCollection. Collection should not contain duplicates."""
return (pcoll
| 'PairWithHash' >> beam.Map(lambda x: (hash(x), x))
| 'GroupByHash' >> beam.GroupByKey()
| 'DropHash' >> beam.FlatMap(
lambda hash_and_values: hash_and_values[1])) | 18750487675046d9330b1c54dd5ff4e27e4552d5 | 3,604,483 |
def init_rand(N, r, rng):
"""
Initialize N robots with radii r uniformly at random in a box centered at
(0,0) such that the robots occupy roughly 2% of the space.
"""
config = np.zeros((N, 3))
arena_side_len = sqrt(N * np.pi * r**2 / 0.02)
for i in range(N):
while True:
... | 4eb5fe10e68dd053bb1265203543e63a08d38016 | 3,604,484 |
def fit_predict(X, y, index):
"""Train and make in-sample prediction."""
clf = LinearRegression().fit(X, y)
daily = clf.predict(X)
daily_predicted = pd.Series(daily, index=index, name="predicted")
return [daily_predicted, clf] | ff016024e26f10acdda3145926b9c20d1bddf4fa | 3,604,485 |
async def job_edit(
job_id: int,
job: CreateAndUpdateJob,
db=Depends(get_db),
current_user=Depends(get_current_active_superuser),
):
"""
Update existing job
"""
return edit_job(db, job_id, job) | 2898c88aa2a00ff0d6c89aa2b680022b888baf06 | 3,604,486 |
def extract_EC_chunks(cq):
"""
Find EC chunks and replace their occurences with EC tags
"""
def _get_EC_span_reject_wh_starters(chunk):
"""
By default, SpaCy treats question words (wh- pronouns starting questions: where, what,...)
as nouns, so often if questions star... | 331ad919e436a46c89321c75cd975fcaf6eff7ac | 3,604,487 |
from scipy.spatial.distance import euclidean, cdist
def evaluate_clustering_DB(X, idx):
"""
Davies-Bouldin index a coefficient to evaluate the goodness of a
clustering solution. The more it approaches to zero, the better
the clustering solution is. -- Tested OK with comparison Matlab
"""
... | 9322139094850b4a529dd9b0f4b693c057fc70ca | 3,604,488 |
import logging
async def build_mint_req(wallet_handle: int,
submitter_did: str,
outputs_json: str) -> (str, str):
"""
Builds Indy request for doing tokens minting according to this payment method.
This method consumes set of UTXO inputs and outputs.
... | 48dcdf14eb28a58140a538848f9ab2718d58f1f5 | 3,604,489 |
import json
def ratelimit():
"""untrusted id found"""
return json.dumps({
'success': False,
'error': 'signal api rate limit reached'
}), 413, {'ContentType': 'application/json'} | b8a2e917acdbe26850e950e62dadf419d64ecc02 | 3,604,490 |
def get_lr(optimizer):
"""Used for convenience when printing"""
for param_group in optimizer.param_groups:
return param_group['lr'] | c73d08f3cbac372b02c3ccce7e40526d7e686e63 | 3,604,491 |
def MobileNetV1_x0_5(pretrained=False, use_ssld=False, **kwargs):
"""
MobileNetV1_x0_5
Args:
pretrained: bool=False or str. If `True` load pretrained parameters, `False` otherwise.
If str, means the path of the pretrained model.
use_ssld: bool=False. Whether using distill... | 851a78f5ef122cb8243cd79e0802a1dbb6690c8d | 3,604,492 |
def motion_T(input_line, cur, count):
"""Go to `count`'th occurence of char to the left and return position.
The position returned is the position of the character to the right of
char.
See Also:
`motion_base()`.
"""
return start_catching_keys(1, "cb_motion_T", input_line, cur, count) | cbf7d5535bd510e1c20d2a68d5e9aab8ae04181d | 3,604,493 |
import os
def find_executable(filename, environ=None):
"""Find an executable by searching the current $PATH."""
if environ is None:
environ = os.environ
path = environ.get("PATH", "/usr/local/bin:/usr/bin:/bin").split(":")
for dirpath in path:
dirpath = os.path.abspath(dirpath.strip())... | be3cabb7298d4a22cb3e81c1878352f2bb405430 | 3,604,494 |
from typing import Tuple
from typing import Dict
from typing import Any
import copy
import uuid
def create_occluder(wall_material: str, pole_material: str,
x_position: float, x_scale: float, sideways: bool = False) \
-> Tuple[Dict[str, Any]]:
"""Create an occluder pair of objects: (wal... | a79811340ab2c4b8b7ad1c464b6dac1ceee67311 | 3,604,495 |
from typing import List
import json
def build_workflow_blocks(
incident: Incident, workflows: List[Workflow], selected_workflow: Workflow = None
):
"""Builds all blocks required to run a workflow."""
modal_template = {
"type": "modal",
"title": {"type": "plain_text", "text": "Run workflow"... | cb5e334f699e3b02efebafeb59658a60cee0c819 | 3,604,496 |
def cmp_by_level_2_tag_code(left, right):
"""
tag按照第二列标签进行排序
:param left: tag1
:param right: tag2
:return:-1,1,0
"""
left = left["tag_code"]
right = right["tag_code"]
if left == "other":
return 1
elif right == "other":
return -1
else:
return 0 | 6ee210c54967dcad7673d4c130ecc0e5bc907bc5 | 3,604,497 |
def lcs(string_a, string_b):
"""
Calculate the length of the longest common subsequence of characters
between two strings.
The time complexity of this implementation is dominated by the two nested
loops, let the length of string_a and string_b is 'n' and 'm' respectively.
This would lead to ... | dc1183092928e1cb9bce5926207fbceb85b79e2e | 3,604,498 |
def getbox(xcenter, ycenter, size=500):
"""
A function to compute coordinates of a bounding box.
Arguments:
- xcenter: int, x position of the center of the box.
- ycenter: int, y position of the center of the box.
- size: int, size of the side of the box.
Returns:
- box... | 6e8030f113a13775365fcd715be46690849154f3 | 3,604,499 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.