content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
from typing import List
from typing import Tuple
from typing import Any
from typing import Optional
def walk_extension(
state: State,
trie_prefix: Bytes,
node_key: Bytes,
extension_node: ExtensionNode,
dirty_list: List[Tuple[Bytes, Node]],
cursor: Any,
) -> Optional[InternalNode]:
"""
... | bcc31ae61729db82d84e02168926845b7b42da44 | 26,451 |
def bottleneck_block_v2(inputs, filters, strides, training, projection_shortcut, data_format):
"""
3-layer bottleneck residual block with batch normalization and relu before convolution layer.
:param inputs: Input images
:param filters: number of filters
:param strides: strides of convolutions
:... | 8330e68d1411c643ffcee6916ba95ef77b7cc5ee | 26,453 |
def preprocess_lines(lines, otherAutorizedSymbols, sentencesSeparator=None):
""" complete my dataset"""
if sentencesSeparator :
result = []
for line in lines :
e = line.split(sentencesSeparator)
if e[0] != "__Error__" and e[1]!= "__Error__" :
lignes_i = sent_tokenize(e[0])
lignes... | 04bf9f90bf06f07803ca8dd6199728d33a73a6de | 26,455 |
def is_slashable_validator(validator: Validator, epoch: Epoch) -> bool:
"""
Check if ``validator`` is slashable.
"""
return (not validator.slashed) and (validator.activation_epoch <= epoch < validator.withdrawable_epoch) | 9ea82379e270f668d2dde3cb5b10a59f29f2e6e6 | 26,456 |
def check_rate_limit() -> None:
"""
Check whether or not a user has exceeded the rate limits specified in the
config. Rate limits per API key or session and per user are recorded.
The redis database is used to keep track of caching, by incrementing
"rate limit" cache keys on each request and setting... | ca49c4b2c4287bca3d664b20abebd9b7df53a0fb | 26,457 |
def update_db(mode):
"""Mode can be 'add', 'move', 'delete'"""
def decorator(func):
@wraps(func)
def wrapped(*args, **kwargs):
# did and rse are the first 2 args
did, rse = args[0], args[1]
update_db = kwargs.get('update_db', False)
if not update_... | cc91757030c9d398bd17ad73521e23d835879560 | 26,458 |
def right_size2(a1, a2):
"""
Check that a1 and a2 have equal shapes.
a1 and a2 are NumPy arrays.
"""
if hasattr(a1, 'shape') and hasattr(a2, 'shape'):
pass # ok, a1 and a2 are NumPy arrays
else:
raise TypeError('%s is %s and %s is %s - both must be NumPy arrays' \
... | 66aa2097ff67a2ef44c49118dbdbba1539f1e3ba | 26,459 |
def spherDist(stla, stlo, evla, evlo):
"""spherical distance in degrees"""
return SphericalCoords.distance(stla, stlo, evla, evlo) | e2ae206c63712dbf263d6d3af28066f279571e20 | 26,461 |
def get_example(matrix, start_row, input_timesteps=INPUT_TIMESTEPS, output_timesteps=OUTPUT_TIMESTEPS):
"""Returns a pair of input, output ndarrays. Input starts at start_row and has the given input length.
Output starts at next timestep and has the given output length."""
# Make sure there are enough time ... | aa396588a32492c29e1dbb4a0e8f96016974b805 | 26,462 |
def full_mul_modifier(optree):
""" extend the precision of arguments of a multiplication to get the full result of the multiplication """
op0 = optree.get_input(0)
op1 = optree.get_input(1)
optree_type = optree.get_precision()
assert(is_std_integer_format(op0.get_precision()) and is_std_integer_form... | 6c191c274d9f130619e2831b50de65a270b41748 | 26,463 |
def find_used_modules(modules, text):
"""
Given a list of modules, return the set of all those imported in text
"""
used = set()
for line in text.splitlines():
for mod in modules:
if 'import' in line and mod in line:
used.add(mod)
return used | 0b1b2b31f60a565d7ba30a9b21800ba7ec265d0c | 26,464 |
def string2mol2(filename, string):
"""
Writes molecule to filename.mol2 file, input is a string of Mol2 blocks
"""
block = string
if filename[-4:] != '.mol2':
filename += '.mol2'
with open(filename, 'w') as file:
file.write(block)
return None | 51043e7f4edde36682713455dc33c643f89db397 | 26,465 |
def getTimeFormat():
"""
def getTimeFormat(): This functions returns the time format used in the bot.
"""
return timeFormat | cd13ab983cd91dca4fc3ae3414c3724b5019f248 | 26,466 |
from typing import Sequence
from typing import Optional
import numpy
def concatenate(
arrays: Sequence[PolyLike],
axis: int = 0,
out: Optional[ndpoly] = None,
) -> ndpoly:
"""
Join a sequence of arrays along an existing axis.
Args:
arrays:
The arrays must have the same sha... | df6c897b25279dca5187e6cafe5c1b9d22b8a994 | 26,467 |
import requests
import json
def get_cik_map(key="ticker"):
"""Get dictionary of tickers to CIK numbers.
Args:
key (str): Should be either "ticker" or "title". Choosing "ticker"
will give dict with tickers as keys. Choosing "title" will use
company name as keys.
Returns:
... | 6a9cf67bb63bfd057ee936e1a5d5be33d8655abe | 26,468 |
def _data_layers():
"""Index all configured data layers by their "shorthand". This doesn't
have any error checking -- it'll explode if configured improperly"""
layers = {}
for class_path in settings.DATA_LAYERS:
module, class_name = class_path.rsplit('.', 1)
klass = getattr(import_module... | 34b0843c76086b41bf119987283fa4373bc07190 | 26,469 |
import hashlib
def sha1base64(file_name):
"""Calculate SHA1 checksum in Base64 for a file"""
return _compute_base64_file_hash(file_name, hashlib.sha1) | aaf2daca1676c822259bec8a519ab5eae7618b17 | 26,470 |
def readfsa(fh):
"""Reads a file and returns an fsa object"""
raw = list()
seqs = list()
for line in fh:
if line.startswith(">") and len(raw) > 0:
seqs.append(Fsa("".join(raw)))
raw.clear()
raw.append(line)
if len(raw) > 0:
seqs.append(Fsa("".join(raw)... | 089cd4b7addcf99baf9394b59d44702995eff417 | 26,471 |
def with_timeout(name):
"""
Method decorator, wraps method with :py:func:`asyncio.wait_for`. `timeout`
argument takes from `name` decorator argument or "timeout".
:param name: name of timeout attribute
:type name: :py:class:`str`
:raises asyncio.TimeoutError: if coroutine does not finished in ... | 7591a4ed176fad60510dfc7aafbb6df2b44672a4 | 26,472 |
import json
def results():
"""
function for predicting a test dataset input as a body of the HTTP request
:return: prediction labels array
"""
data = request.get_json(force=True)
data = pd.DataFrame(json.loads(data))
prediction = model.predict(data)
output = list(map(int, pred... | caae7f04884532de7a4fef9e5a6d285c982d2187 | 26,473 |
from datetime import datetime
def tradedate_2_dtime(td):
""" convert trade date as formatted by yfinance to a datetime object """
td_str = str(int(td))
y, m, d = int(td_str[:4]), int(td_str[4:6]), int(td_str[6:])
return datetime(y, m, d) | 29db7ed41a5cac48af1e7612e1cd2b59ab843a1f | 26,475 |
def frmchg(frame1, frame2, et):
"""frmchg(SpiceInt frame1, SpiceInt frame2, SpiceDouble et)"""
return _cspyce0.frmchg(frame1, frame2, et) | db05ebf45f0d265e8f75b26fbd7c1234d9a8b4cb | 26,476 |
def map_popularity_score_keys(popularity):
"""
Maps popularity score keys to be more meaningful
:param popularity: popularity scores of the analysis
:return: Mapped dictionary of the scores
"""
return dict((config.popularity_terms[key], value) for (key, value) in popularity.items()) | 84c265e7ec6e881df878f74d5d9b9eda9d223bf3 | 26,477 |
from typing import Callable
from typing import Optional
def _get_utf16_setting() -> Callable[[Optional[bool]], bool]:
"""Closure for holding utf16 decoding setting."""
_utf16 = False
def _utf16_enabled(utf16: Optional[bool] = None) -> bool:
nonlocal _utf16
if utf16 is not None:
... | 1f0caeab03047cc847d34266c1ed53eabdf01a10 | 26,478 |
def uproot_ntuples_to_ntuple_dict(uproot_ntuples, properties_by_track_type,
keep_invalid_vals=False):
"""Takes in a collection of uproot ntuples and a dictionary from
track types to desired properties to be included, returns an ntuple
dictionary formed by selecting properties from the ntuples and th... | e4f391fc0c63e73ff320e973f624e43841a3613f | 26,479 |
from datetime import datetime
def get_container_sas_token(block_blob_client,
container_name, blob_permissions):
"""
Obtains a shared access signature granting the specified permissions to the
container.
:param block_blob_client: A blob service client.
:type block_blob_... | f17623e721e84a0953565854f2e2eedfb4f8afe6 | 26,480 |
def to_one_hot(y):
"""Transform multi-class labels to binary labels
The output of to_one_hot is sometimes referred to by some authors as the
1-of-K coding scheme.
Parameters
----------
y : numpy array or sparse matrix of shape (n_samples,) or
(n_samples, n_classes... | 134f4bce729c98439bdca2cd586f95d0cc9178c7 | 26,483 |
def random():
"""
getting a random number from 0 to 1
"""
return randrange(10000) / 10000 | 12ab43d5e5c8a9a993f8053363e56c2acf8b0ceb | 26,484 |
from typing import Union
def parameter_string_to_value(
parameter_string: str,
passthrough_estimate: bool = False,
) -> Union[float, int, str]:
"""Cast a parameter value from string to numeric.
Args:
parameter_string:
The parameter value, as a string.
passthrough_estimate:... | 3271acf50f5171703e16bce183d246d149d5e053 | 26,485 |
def rfsize(spatial_filter, dx, dy=None, sigma=2.):
"""
Computes the lengths of the major and minor axes of an ellipse fit
to an STA or linear filter.
Parameters
----------
spatial_filter : array_like
The spatial receptive field to which the ellipse should be fit.
dx : float
... | a2e184dd597c840392c05d0955dba826aa528a06 | 26,487 |
import json
def get_config_from_json(json_file):
"""
Get the config from a json file
:param json_file:
:return: config(namespace) or config(dictionary)
"""
# parse the configurations from the config json file provided
with open(json_file, 'r') as config_file:
config_dict = json.loa... | 17aec6d1d0413836f647b222681e32af1a298fbc | 26,488 |
from pathlib import Path
def create_polarimetric_layers(import_file, out_dir, burst_prefix, config_dict):
"""Pipeline for Dual-polarimetric decomposition
:param import_file:
:param out_dir:
:param burst_prefix:
:param config_dict:
:return:
"""
# temp dir for intermediate files
wi... | ddfd3d9b12aefcf5f60b254ad299c59d4caca837 | 26,489 |
from typing import Literal
import math
def Builtin_FLOOR(expr, ctx):
"""
http://www.w3.org/TR/sparql11-query/#func-floor
"""
l_ = expr.arg
return Literal(int(math.floor(numeric(l_))), datatype=l_.datatype) | 495d7e2133028030e1766d0a04eb3d20f800b918 | 26,491 |
import requests
def get(target: str) -> tuple:
"""Fetches a document via HTTP/HTTPS and returns a tuple containing a boolean indicating the result of the request,
the URL we attempted to contact and the request HTML content in bytes and text format, if successful.
Otherwise, returns a tuple containing ... | 1d9d650d77776419318cbd204b722d8abdff94c5 | 26,492 |
def DOM2ET(domelem):
"""Converts a DOM node object of type element to an ElementTree Element.
domelem: DOM node object of type element (domelem.nodeType == domelem.ELEMENT_NODE)
returns an 'equivalent' ElementTree Element
"""
# make some local variables for fast processing
tyCDATA = domelem.CD... | b8288a2704995ec4fbe4dc1bc2805cd7658beb35 | 26,493 |
import torch
def f_score(pr, gt, beta=1, eps=1e-7, threshold=.5):
"""dice score(also referred to as F1-score)"""
if threshold is not None:
pr = (pr > threshold).float()
tp = torch.sum(gt * pr)
fp = torch.sum(pr) - tp
fn = torch.sum(gt) - tp
score = ((1 + beta ** 2) * tp + eps) \
... | 2c54fd24cd04ac2b41a9d5ca4bf8a7afc5e88640 | 26,494 |
def makeSatelliteDir(metainfo):
"""
Make the directory name for the 'satellite' level.
"""
satDir = "Sentinel-" + metainfo.satId[1]
return satDir | dfbb43f235bc027f25fc9b624097e8f2e0dee4f9 | 26,495 |
def resolve_tagged_field(field):
"""
Fields tagged with `swagger_field` shoudl respect user definitions.
"""
field_type = getattr(field, SWAGGER_TYPE)
field_format = getattr(field, SWAGGER_FORMAT, None)
if isinstance(field_type, list):
# Ideally we'd use oneOf here, but OpenAPI 2.0 use... | 90f59615395350dbd0f2ff3ff5573f28e926dada | 26,497 |
def grid_id_from_string(grid_id_str):
"""Convert
Parameters
----------
grid_id_str : str
The string grid ID representation
Returns
-------
ret : tuple of ints
A 4-length tuple representation of the dihedral id
"""
return tuple(int(i) for i in grid_id_str.split(',')) | cec058302aae701c1aa28fcb4c4a9d762efa724e | 26,498 |
def adj_to_edge_index(adj):
"""
Convert an adjacency matrix to an edge index
:param adj: Original adjacency matrix
:return: Edge index representation of the graphs
"""
converted = []
for d in adj:
edge_index = np.argwhere(d > 0.).T
converted.append(edge_index)
return con... | e2c047a6c60bfb3ea109e8686a810749a726265f | 26,499 |
def determine_all_layers_for_elev(std_atmos, layers, values, elevation):
"""Determine all of the layers to use for the elevation
Args:
std_atmos [StdAtmosInfo]: The standard atmosphere
layers [<str>]: All the pressure layers
values [<LayerInfo>]: All the interpolated layers information
... | c3e23670437efa7caa03f1027b2a59d0bd62361a | 26,500 |
from typing import List
def remove_redundant(
text: str,
list_redundant_words: List[str] = S_GRAM_REDUNDANT,
) -> str:
"""To remove phrases that appear frequently and that can not be used to infere skills.
Parameters
----------
text : str
The text to clean.
list_redundant_words : ... | 07a3dfca84acb57b0786e17879d2ac17693c8eba | 26,501 |
import asyncio
def position_controller_mock():
"""
Position controller mock.
"""
mock = MagicMock(spec=PositionController)
future = asyncio.Future()
future.set_result(None)
mock.update_odometry = MagicMock(return_value=future)
return mock | 71e7c4a5894eb56ab99aaec03e9e569291e12e6c | 26,502 |
def forest_overview():
"""
The remove forest URL handler.
:return: The remove_forest.html page
"""
all_sensors = mysql_manager.get_all_sensors()
for sensor_module in all_sensors:
sensor_module['latest_measurements'] = mysql_manager.get_latest_measurements_from_sensor(sensor_module['id... | 05ffdd24a08ab6553ac175bd2dfc690bfbf1876e | 26,504 |
def task_dev():
"""Run the main task for the project"""
return {
'actions': ["docker run --volume %s/:/app %s" % (CONFIG["project_root"], IMAGE)]
} | 7a8f3dab41076d56717312c01a6144dfd7fac43b | 26,505 |
import struct
from datetime import datetime
def header_parse(header, ts_resolution):
"""
parses the header of a TOB3 frame.
Parameters
----------
header: string
of binary encoded dat with length of 12-Bytes
ts_resolution:
frame time resolution. multiplier for sub-second part ... | 7615064961e44167a3efbca888522fc9433e4598 | 26,506 |
def shuff_par_str(shuffle=True, str_type="file"):
"""
shuff_par_str()
Returns string from shuffle parameter to print or for a filename.
Optional args:
- shuffle (bool): default: True
- str_type (str): "print" for a printable string and "file" for a
string usab... | 956fd86c4ce458d73ebfd425e8b9430dbd027705 | 26,507 |
def fft_imaginary(x: np.ndarray) -> np.ndarray:
""" Imaginary values of FFT transform
:param x: a numeric sequence
:return: a numeric sequence
"""
x_fft = np.fft.fft(x)
xt = np.imag(x_fft)
return xt | 6c9a60a160475f687fba8f624b8e06e4f63d5125 | 26,508 |
def prodtype_to_platform(prods):
"""
Converts one or more prodtypes into a string with one or more <platform>
elements.
"""
if isinstance(prods, str):
return name_to_platform(prodtype_to_name(prods))
return "\n".join(map(prodtype_to_platform, prods)) | f23d14001ac9afdf3215b5ecbbc23759708c27fd | 26,509 |
import pickle
def train_config_setting(config, dataset):
"""
Configuring parameter for training process
:param config: type dict: config parameter
:param dataset: type str: dataset name
:return: config: type dict: config parameter
"""
# Load max shape & channels of images and labels.
... | ecb9fde6cf19220f4503c42345fdfaf690f2783a | 26,510 |
def parse_bool(value):
"""Parses a boolean value from a string."""
return _parse_value(value, BooleanField()) | 0291ca0a68abe2f2a0e9b92f6c931e3d5a06a69a | 26,511 |
def load_dataset_X_y(dirname, opt):
"""
load training data
:param : dirname : str, loading target directory
:param : opt : str, option data format "pandas" or "numpy"
:return : data_X : numpy, training data
:return : data_y : numpy, true data
"""
# X
input_filename = di... | 602008cb3c03ec64861646a9f8a1a8647b01d59a | 26,512 |
def connect_to_es(host, port, use_auth=False):
"""
Return client that's connected to an Elasticsearch cluster.
Unless running from authorized IP, set use_auth to True so that credentials are based on role.
"""
if use_auth:
http_auth = _aws_auth()
else:
http_auth = None
es = ... | db29aef8d08c46c375c68e4da6100164321495a5 | 26,513 |
import select
from typing import cast
def task_5():
"""Задание 5"""
s = select([
student.c.name,
student.c.surname,
cast((student.c.stipend * 100), Integer)
])
print(str(s))
rp = connection.execute(s)
return rp.fetchall() | 3932bb3da4a443154805e708a58924d07f1d5221 | 26,514 |
def sentinelCloudScore(img):
"""
Compute a custom cloud likelihood score for Sentinel-2 imagery
Parameters:
img (ee.Image): Sentinel-2 image
Returns:
ee.Image: original image with added ['cloudScore'] band
"""
im = sentinel2toa(img)
# Compute several indicators of cloudyness ... | 672fca54fb0e43d9cae51de95149a44b0ed731bc | 26,515 |
import re
def safe_filename(name: str, file_ending: str = ".json") -> str:
"""Return a safe version of name + file_type."""
filename = re.sub(r"\s+", "_", name)
filename = re.sub(r"\W+", "-", filename)
return filename.lower().strip() + file_ending | 98a887788046124354676a60b1cf7d990dbbc02f | 26,516 |
def group():
""" RESTful CRUD controller """
if auth.is_logged_in() or auth.basic():
pass
else:
redirect(URL(c="default", f="user", args="login",
vars={"_next":URL(c="msg", f="group")}))
module = "pr"
tablename = "%s_%s" % (module, resourcename)
table = s3db[tablename]... | df532b93901b7c709ac21c2da4fffe1e06159f0c | 26,517 |
def _tracking_cost(time: int = 0, state: np.ndarray = None) -> float:
"""Tracking cost function.
The goal is to minimize the distance of the x/y position of the vehicle to the
'state' of the target trajectory at each time step.
Args:
time : Time of the simulation. Used for time-dependent cost ... | cd4f39c78687d3975e2e4d1bc0e3b8d8f8fc4b2c | 26,518 |
def fixture_repo(repo_owner: str, repo_name: str) -> Repository:
"""Return a GitHub repository."""
return Repository(repo_owner, repo_name) | 4a2cae78bfcb0158ae8751305c7a187b368f5d5d | 26,519 |
def get_clean(source_file):
"""Generate a clean data frame from source file"""
print('Reading from source...')
df = pd.read_csv(source_file)
print('Cleaning up source csv...')
# Drop rows with too much NA data
df.drop(['Meter Id', 'Marked Time', 'VIN'], axis=1, inplace=True)
# Drop rows miss... | f565dcd75faf3464b540f42cc76aafdc59f0c2d8 | 26,520 |
def populate_db():
"""Populate the db with the common pop/rock songs file"""
songs = dm.parse_file('static/common_songs.txt')
freq_matrix = dm.get_frequency_matrix(songs)
model, clusters = clustering.clusterize(freq_matrix)
clustering.save(model, MODEL_FILENAME)
clusters_for_db = {}
try:
... | 87ff8fdebd398e0cff006f40ad9a69f658991eda | 26,521 |
def magenta_on_red(string, *funcs, **additional):
"""Text color - magenta on background color - red. (see sgr_combiner())."""
return sgr_combiner(string, ansi.MAGENTA, *funcs, attributes=(ansi.BG_RED,)) | 3b6062a6ae326766a8d44d34e2c3a4e47c232430 | 26,522 |
def create_entry(entry: Entry) -> int:
"""
Create an entry in the database and return an int of it's ID
"""
return create_entry(entry.title, entry.text) | 6aa2832a9bf7b81460e792c96b06a599cc512e7b | 26,524 |
def process_document_bytes(
project_id: str,
location: str,
processor_id: str,
file_content: bytes,
mime_type: str = DEFAULT_MIME_TYPE,
) -> documentai.Document:
"""
Processes a document using the Document AI API.
Takes in bytes from file reading, instead of a file path
"""
# Th... | 92ae70d0e3754b76f7cc8b6b0370d53e9031b319 | 26,525 |
import numpy as np
def merge_imgs(imgs, cols=6, rows=6, is_h=True):
"""
合并图像
:param imgs: 图像序列
:param cols: 行数
:param rows: 列数
:param is_h: 是否水平排列
:param sk: 间隔,当sk=2时,即0, 2, 4, 6
:return: 大图
"""
if not imgs:
raise Exception('[Exception] 合并图像的输入为空!')
img_shape = i... | c591c450e54aea76ea237263b3169ef4af306a96 | 26,526 |
def text_editor():
"""Solution to exercise R-2.3.
Describe a component from a text-editor GUI and the methods that it
encapsulates.
--------------------------------------------------------------------------
Solution:
--------------------------------------------------------------------------
... | 39fd3f41cbc28d333dd5d39fc8d1967164bd7bc4 | 26,528 |
def generate_imm5(value):
"""Returns the 5-bit two's complement representation of the number."""
if value < 0:
# the sign bit needs to be bit number 5.
return 0x1 << 4 | (0b1111 & value)
else:
return value | 72be8225d364ec9328e1bb3a6e0c94e8d8b95fb0 | 26,529 |
def CalculateChiv6p(mol):
"""
#################################################################
Calculation of valence molecular connectivity chi index for
path order 6
---->Chiv6
Usage:
result=CalculateChiv6p(mol)
Input: mol is a molecule object.... | 332a5fab80beaa115366ed3a5967a7c433aa8981 | 26,530 |
def _cart2sph(x,y,z):
"""A function that should operate equally well on floats and arrays,
and involves trignometry...a good test function for the types of
functions in geospacepy-lite"""
r = x**2+y**2+z**2
th = np.arctan2(y,x)
ph = np.arctan2(x**2+y**2,z)
return r,th,ph | fb0184c315c9b4206b4ffc5b019264162b9641d4 | 26,531 |
from typing import Optional
def get_existing_key_pair(ec2: EC2Client, keypair_name: str) -> Optional[KeyPairInfo]:
"""Get existing keypair."""
resp = ec2.describe_key_pairs()
keypair = next(
(kp for kp in resp.get("KeyPairs", {}) if kp.get("KeyName") == keypair_name),
None,
)
if k... | d066431f784e108e0b27a7c73f833b716cf6e879 | 26,532 |
import jinja2
def render_template(template: str, context: dict,
trim_blocks=True, lstrip_blocks=True,
**env_kwargs):
"""
One-time-use jinja environment + template rendering helper.
"""
env = jinja2.Environment(
loader=jinja2.DictLoader({'template': templ... | 26ec504d694682d96fce0240145549f0f62c0695 | 26,533 |
def _func_to_user(uid, func):
"""
Internal function for doing actions against a user. Gets the user from
the database, calls the provided function, and then updates the user
back in the database.
Args:
uid (string) -- The user's key
func (function) -- activity to perform on the use... | f3f9af52410a15f61492adbb88cb9706de2e7042 | 26,534 |
import torch
def breg_sim_divergence(K, p, q, symmetric=False):
# NOTE: if you make changes in this function, do them in *_stable function under this as well.
"""
Compute similarity sensitive Bregman divergence of between a pair of (batches of)
distribution(s) p and q over an alphabet of n elements. ... | f668b4af511c1689ec66a34f386c756b7b0fdb0e | 26,535 |
def manage_pages(request):
"""Dispatches to the first page or to the form to add a page (if there is no
page yet).
"""
try:
page = Page.objects.all()[0]
url = reverse("lfs_manage_page", kwargs={"id": page.id})
except IndexError:
url = reverse("lfs_add_page")
return HttpR... | 5b50821c516cd450dde5dba9f83c27687e63c8ef | 26,536 |
def get_network_info():
"""
Sends a NETWORK_INTERFACES_INFO command to the server.
Returns a dict with:
- boolean status
- list of str ifs (network interfaces detected by RaSCSI)
"""
command = proto.PbCommand()
command.operation = proto.PbOperation.NETWORK_INTERFACES_INFO
data = sen... | 0d0517eeee5260faa2b12de365f08b8d962eb0c8 | 26,537 |
def jp_clean_year(string, format):
"""Parse the date and return the year."""
return getYearFromISODate(iso8601date(string,format)) | 33b1a9121485abaff93c4ec979c3c3f63d7d1252 | 26,540 |
def _epsilon(e_nr, atomic_number_z):
"""For lindhard factor"""
return 11.5 * e_nr * (atomic_number_z ** (-7 / 3)) | 8c6115b77ce3fb4956e5596c400c347e68382502 | 26,541 |
def compute_heatmap(cnn_model, image, pred_index, last_conv_layer):
"""
construct our gradient model by supplying (1) the inputs
to our pre-trained model, (2) the output of the (presumably)
final 4D layer in the network, and (3) the output of the
softmax activations from the model
"""
gradM... | 2ee24d643de319588307913eb5f15edbb4a8e386 | 26,542 |
def did_git_push_succeed(push_info: git.remote.PushInfo) -> bool:
"""Check whether a git push succeeded
A git push succeeded if it was not "rejected" or "remote rejected",
and if there was not a "remote failure" or an "error".
Args:
push_info: push info
"""
return push_info.flags & GIT... | ff9ea6856767cda79ed6a6a82b5cadacb1318370 | 26,543 |
import six
def find_only(element, tag):
"""Return the only subelement with tag(s)."""
if isinstance(tag, six.string_types):
tag = [tag]
found = []
for t in tag:
found.extend(element.findall(t))
assert len(found) == 1, 'expected one <%s>, got %d' % (tag, len(found))
return found... | fd4ec56ba3e175945072caec27d0438569d01ef9 | 26,544 |
async def mongoengine_invalid_document_exception_handler(request, exc):
"""
Error handler for InvalidDocumentError.
Logs the InvalidDocumentError detected and returns the
appropriate message and details of the error.
"""
logger.exception(exc)
return JSONResponse(
Response(succes... | cb9722a6619dfcdaeebcc55a02ae091e54b26207 | 26,545 |
def gen_2Dsersic(size,parameters,normalize=False,show2Dsersic=False,savefits=False,verbose=True):
"""
Generating a 2D sersic with specified parameters using astropy's generator
--- INPUT ---
size The dimensions of the array to return. Expects [ysize,xsize].
The 2D gauss will ... | 8202ef9d79cc7ccb42899a135645244ecd4fc541 | 26,546 |
import torch
def dqn(agent, env, brain_name, n_episodes=2500, max_t=1000, eps_start=1.0,
eps_end=0.01, eps_decay=0.999, train=True):
"""Deep Q-Learning.
Params
======
n_episodes (int): maximum number of training episodes
max_t (int): maximum number of timesteps per episode
... | a1c1715451c8613866871c5e51e423d3a67e6928 | 26,547 |
from datetime import datetime
def get_activity_stats_subprocess(
data_full: list[ActivitiesUsers], data_cp: list[ActivitiesUsers]
) -> DestinyActivityOutputModel:
"""Run in anyio subprocess on another thread since this might be slow"""
result = DestinyActivityOutputModel(
full_completions=0,
... | c7ef7f93e0aeefe659676bac98944fbf88eaabe7 | 26,548 |
def ma_cache_nb(close: tp.Array2d, windows: tp.List[int], ewms: tp.List[bool],
adjust: bool) -> tp.Dict[int, tp.Array2d]:
"""Caching function for `vectorbt.indicators.basic.MA`."""
cache_dict = dict()
for i in range(len(windows)):
h = hash((windows[i], ewms[i]))
if h not in c... | ae2547ba2c300386cc9d7a9262c643a305ca987f | 26,549 |
def get_AllVolumes(controller, secondary=None):
"""Run smcli command 'show AllVolumes' on the controller, the output is
returned to the calling function.
The primary controller (a) is mandatory, but the secondary controller
(b) is optional."""
# Check which controller is reachable.
... | 32125adec4811d1813e3e804c05c647e1de1e011 | 26,550 |
def fetch_slot_freq_num(timestamp, slot, freq_nums):
"""Find GLONASS frequency number in glo_freq_nums and return it.
Parameters
----------
timestamp : datetime.datetime
slot : int
GLONASS satellite number
freq_nums : dict
{ slot_1: { datetime_1: freq-num, ... } }
Returns
... | 835a71def86478cbc7327b3873c203ad6936276d | 26,551 |
def _apply_function(x, fname, **kwargs):
"""Apply `fname` function to x element-wise.
# Arguments
x: Functional object.
# Returns
A new functional object.
"""
validate_functional(x)
fun = get_activation(fname)
lmbd = []
for i in range(len(x.outputs)):
lmbd.appe... | a968dcea7ac95f154c605ba34737c13198b62d77 | 26,552 |
def get_url(city):
"""
Gets the full url of the place you want to its weather
You need to obtain your api key from open weather, then give my_api_key the value of your key below
"""
my_api_key = 'fda7542e1133fa0b1b312db624464cf5'
unit = 'metric' # To get temperature in Celsius
weat... | 9454a9ad4a2baacb7988216c486c497a0253056c | 26,554 |
def login() -> ApiResponse:
"""Login a member"""
member_json = request.get_json()
email = member_json["email"]
password = member_json["password"]
member = MemberModel.find_by_email(email)
if member and member.verify_password(password) and member.is_active:
identity = member_schema.dump... | 73122e8a52a420ed20c7f11eb63be1317a818c1d | 26,555 |
from typing import Sequence
from typing import Union
from typing import Iterator
def rhythmic_diminution(seq: Sequence, factor: Union[int, float]) -> Iterator[Event]:
"""Return a new stream of events in which all the durations of
the source sequence have been reduced by a given factor.
"""
return (Eve... | a2ce2982f487e228594ecf992b8d5ed01799f9e2 | 26,556 |
def get_line_offset():
"""Return number of characters cursor is offset from margin. """
user_pos = emacs.point()
emacs.beginning_of_line()
line_start = emacs.point()
emacs.goto_char(user_pos)
return user_pos - line_start | 6c2144699eec32f7f22991e8f12c4304024ca93f | 26,557 |
def test_scheduler_task(scheduler: Scheduler) -> None:
"""
scheduler_task decorator should allow custom evaluation.
"""
@scheduler_task("task1", "redun")
def task1(
scheduler: Scheduler, parent_job: Job, sexpr: SchedulerExpression, x: int
) -> Promise:
return scheduler.evaluate(... | 4b129d25a719019323905888649d8cec0e40513e | 26,558 |
def verse(day):
"""Produce the verse for the given day"""
ordinal = [
'first',
'second',
'third',
'fourth',
'fifth',
'sixth',
'seventh',
'eighth',
'ninth',
'tenth',
'eleventh',
'twelfth',
]
gifts = [
... | 027cedf0b1c2108e77e99610b298e1019629c880 | 26,559 |
import uuid
async def invite_accept_handler(
invite_id: uuid.UUID = Form(...),
current_user: models.User = Depends(get_current_user),
db_session=Depends(yield_db_session_from_env),
) -> data.GroupUserResponse:
"""
Accept invite request.
If the user is verified, adds user to desired group and m... | 4faf22d3f3f9c59d040961b25b1f1660a002f9bd | 26,561 |
def read_current_labels(project_id, label_history=None):
"""Function to combine label history with prior labels.
Function that combines the label info in the dataset and
the label history in the project file.
"""
# read the asreview data
as_data = read_data(project_id)
# use label history ... | 5676be04acc8dd2ab5490ec1223585707d65d834 | 26,562 |
import collections
def get_mindiff(d1, d2, d3):
""" This function determines the minimum difference from checkboxes 3, 5, and 7,
and counts the number of repetitions. """
min_diff = []
for i, _ in enumerate(d1):
diffs_list = [d1[i], d2[i], d3[i]]
md = min(diffs_list)
if md == ... | d2bf03b31712a15dbee45dbd44f3f937a3fd4a1a | 26,563 |
def mode(lyst):
"""Returns the mode of a list of numbers."""
# Obtain the set of unique numbers and their
# frequencies, saving these associations in
# a dictionary
theDictionary = {}
for number in lyst:
freq = theDictionary.get(number, None)
if freq == None:
# number... | bccf7955741ad4258dea7686559b9cb0bf934ab4 | 26,564 |
def project_permissions(project_id):
"""View and modify a project's permissions.
"""
# does user have access to the project?
project = helpers.get_object_or_exception(Project,
Project.id == project_id,
exceptions... | 45fda8e95394e8271ee03e9cc65bdbe03dc18f8b | 26,566 |
import pandas as pd
def fetch_community_crime_data(dpath=None):
"""Downloads community crime data.
This function removes missing values, extracts features, and
returns numpy arrays
Parameters
----------
dpath: str | None
specifies path to which the data files should be downloaded.
... | c85e74c647d70497479fabb43d78887bb55751f0 | 26,567 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.