content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
import torch
def rotation_matrix_to_quaternion(rotation_matrix, eps=1e-6):
"""Convert 3x4 rotation matrix to 4d quaternion vector
This algorithm is based on algorithm described in
https://github.com/KieranWynn/pyquaternion/blob/master/pyquaternion/quaternion.py#L201
Args:
rotation_matrix (Te... | 994f1d728502c0298c02f3d74d7a7d39bceab891 | 68,658 |
import json
import re
def change_user_surname(request):
"""
Create response with prompting user to give his new surname
:param request: POST request from "Change user surname" Dialogflow intent
:return: JSON with response prompting user to give his new surname
"""
language = request.data['quer... | e37744262858b7ca197ee42e6f8acb34b40d6bc5 | 68,659 |
import re
def split_authors(authors_list):
"""
:param authors_list A list of authors to further split
:return A cleaner version of the authors list
"""
test_split = re.split(",", authors_list)
# Remove 'and' or & symbol from the last author if it exists
splits = [re.split("and |& | ", x) f... | 57f8f8c52ab07baddf9f3410c5be58ef482536ab | 68,660 |
from typing import Callable
from typing import Tuple
import asyncio
def juxt(*funcs: Callable) -> Callable[..., Tuple]:
"""Create a function that applies each function in :funcs: to its arguments and returns a tuple of the results.
>>> inc = lambda x: x + 1
>>> double = lambda x: x * 2
>>> juxt(inc, ... | fd75972b988fa0577ce3e4a9cea38207e10f35b9 | 68,661 |
def vectorized_result(j):
"""Return a 10-dimensional unit vector with a 1.0 in the jth
position and zeroes elsewhere. This is used to convert a digit
(0...9) into a corresponding desired output from the neural
network."""
output_result = np.zeros((10, 1))
output_result[j] = 1.0
return outp... | 0b35bb4f6d0172412757fce9d3d05a8eab39410f | 68,662 |
def speed_convert(size):
"""
Hi human, you can't read bytes?
"""
power = 2**10
zero = 0
units = {0: "", 1: "Kb/s", 2: "Mb/s", 3: "Gb/s", 4: "Tb/s"}
while size > power:
size /= power
zero += 1
return f"{round(size, 2)} {units[zero]}" | 19f6b9dea0c0d151c7a44d7554f42132dedcb29e | 68,663 |
import re
def _parse_extract(extract_url: str):
"""
Parses information from extract.
:param extract_url: extract url
:type extract_url: str
:return: capital base and insolvency
"""
bs = _open_url(extract_url)
capital_base_row = bs.find('span', text=re.compile('(ákladní kapitál|Kmenov... | 15a4ca189a16fde3a7fd0feb32bb785111bd21ab | 68,664 |
import collections
def sequence_example_batch(mode, batch_size, shuffle=True):
"""Generates a padded batch of (negated_conjecture, clause, label) examples.
Each batch is organized into (positive, negative) pairs of examples from the
same proof.
Args:
mode: Either 'train' or 'eval'.
batch_size: Integ... | 0fabc9bf42890bd5076dc6887ec6d07f8a353849 | 68,665 |
def validate_calculation(calculation):
""" Validate that all of the symbols needed for a calculation are defined
Args:
expression (:obj:`Calculation`)
Returns:
:obj:`tuple`:
* nested :obj:`list` of :obj:`str`: nested list of errors (e.g., required ids missing or ids not unique... | a7596a0ea4b65f30c93c58e3da3d2c4b295e45fc | 68,666 |
def associate_detections_to_trackers_fusion(detections, trackers, iou_threshold):
"""
Assigns detections to tracked object (both represented as bounding boxes)
detections: N x 8 x 3
trackers: M x 8 x 3
Returns 3 lists of matches, unmatched_detections and unmatched_trackers
"""
dets_8corner = [convert_3dbo... | b24c2e3956cc5bf9e355d13ed207a265e7f4e011 | 68,667 |
def get_expected_name(logfile):
"""get the name of the file with the expected json"""
return logfile.with_name(logfile.stem + "-expected.json") | 7bc886fdbc23a53610817391db3fccbe53fbab81 | 68,668 |
def get_derivative(top_field, bottom_field, ws):
"""
Return the W object corresponding to a particular derivative in the general covariance equations, with a flag for W-
due to its different symmetry and a multiplier (+/- 1).
"""
# Extract field index and type
top_field_idx, top_field_type = to... | 434215401c24e8f23cb400825e6621690de67c47 | 68,669 |
def string_formulation(model, feature_names, number_words, number_topics, similar_words, levenshtein_distance,
pub_year_one, pub_year_two, bert_model, bert_tokenizer, author):
"""Formulate the search string based on the input parameters.
Args:
model: Return of the lda_algorithm()... | 67e3188cc5fe5b2792132c060945453b1d3af3ab | 68,670 |
def temp_file_name(name=""):
"""Return string of a full path to a new temporary file name.
Args:
name: str of name to include in temporary file name.
Returns:
str of full path to new file name in TMP_DIR
"""
t = int(time.time())
x = random.randint(0, 1000000)
filename = "tmp.%s.%d.%d" % (name, t,... | 563d772abe85c964686f0a11e35ddd37371d0f58 | 68,671 |
def get_target(name):
"""Returns the module of the target going by the given name. Returns `None`
if the target does not exist."""
return _TARGETS.get(name, None) | 819c8417b820a762fbf5f2c1d9419b4584bd8b2a | 68,673 |
def make_login(name: str):
""" Makes a login route for an Oauth API. """
def login() -> Response:
oauth = cube.make_oauth(name)
authorization_url, state = oauth.authorization_url(cube.CONFIG[cube.make_key(name, "url")] + "oauth/authorize")
# State is used to prevent CSRF, keep this for ... | 356c8c755942367e03de4cb68e943cc1e34b556a | 68,674 |
def figure_to_image(figure):
"""
@brief Convert a Matplotlib figure to a vtkImageData with RGBA unsigned char channels
@param figure A matplotlib figure.
@return a vtkImageData with the Matplotlib figure content
"""
buf = figure_to_data(figure)
# Flip rows to be suitable for vtkImageData.
buf = buf[::-... | 502f61cfd1f9a553da71487aa81e062c57909c4f | 68,675 |
def decode(obj):
"""
Decodes JSON / msgpack objects into the corresponding PhaseMap types.
"""
return obj | 821d72ed0c1fe51441f3ac40e1389ee450241087 | 68,677 |
def byte_instruction(name, bytecode, offset):
#
"""
"""
slot = bytecode.code[offset + 1]
print("{:16s} {:4d}".format(name, slot))
return offset + 2 | 5a1a95f2d2a7cb6bad05ed3941efdb15c0ec5969 | 68,678 |
def conv_with_pools(inputs, output_size, kernel_size, pool_sizes, pooling_type,
**kwargs):
"""Convolution plus 1x1 convolution applied to specified pools.
For example we might do a regular convolution with kernel size (3, 1),
and pools of sizes [(9, 1), (27, 1)].
Args:
inputs: a Tensor... | dd0a2affed21388096963d2029a094611281d206 | 68,679 |
def get_free_symbols(s, symbols, free_symbols=None):
"""
Returns free_symbols present in `s`.
"""
free_symbols = free_symbols or []
if not isinstance(s, list):
if s in symbols:
free_symbols.append(s)
return free_symbols
for i in s:
free_symbols = get_free_sym... | 873d0bac2fa24db3b4ded6d9d867ca703d0a2314 | 68,680 |
def dth_dp(theta_in, data_in):
"""
Calculate vertical derivative on even (theta) levels.
Parameters
----------
theta_in : array_like, 1D
Vertical coordinate (potential temperature)
data_in : array_like, ND, where data_in.shape[1] == theta_in.shape[0]
Data on theta levels
Re... | 1ad77261410b3f4c927ff6ba0987616effe2c495 | 68,681 |
import logging
def heartbeat_batch(heartbeats):
"""Extends build leases in a batch.
Args:
heartbeats (list of dict): list of builds to update. Each dict is kwargs
for heartbeat() method.
Returns:
List of (build_id, build, exception) tuples.
"""
build_ids = [h['build_id'] for h in heartbeats]
... | 8d800521910ccc48c5e83089d2f3669d1dbfe623 | 68,682 |
import pathlib
def _check_data(data):
"""Ensure that data is of appropriate type and return numpy array"""
if isinstance(data, np.ndarray):
return data.astype(float)
elif isinstance(data, (str, pathlib.PosixPath)):
data = nib.load(data)
elif isinstance(data, (nib.Cifti2Image, nib.Gifti... | 9644d4cf570b387049d5cda121ef5470757c35f2 | 68,683 |
import tqdm
def global_alignment(train_frame, test_frame):
"""
Calculates the global alignment metric proposed in the paper Smolak et al. (2022) through the application of the
Needleman-Wunsch algorithm on sequences for pairwise matching.
Returns normalised values.
:param train_frame: TrajectoriesFrame class obj... | 04d37a3146969dfb6232687abdbbd883e726abf7 | 68,684 |
def resnet_v2_152_separable(input_shape,
kernel_size=3,
include_root=True,
weight_decay=1e-4,
kernel_initializer="he_normal",
bn_epsilon=1e-3,
bn_moment... | 1bebdde79c66afef44c319de5df3b53caea5879f | 68,685 |
async def aio_wcheck(url: str, timeout: int = 5) -> bool:
"""If the http status is 200 return true."""
try:
async with ClientSession() as session:
async with session.get(url, allow_redirects=True, timeout=timeout) as res:
return res.status == 200
except ClientError:
... | d375de749080e02a6625e79f4e86febdaa6a8996 | 68,687 |
def aggregateGeolevels(spark_session, spark_df, geolevels, verbose=True):
"""
Take a spark dataframe and aggregate blocks to get geounits at higher geolevels
Parameters
==========
spark_session : SparkSession
Needed for accessing the crosswalk file that joins to the dataframe (if not alread... | 748fe5158588579e5a377a5186c7b9e75ddae499 | 68,688 |
def new(params={}, lan=None, language=None):
"""
"""
user_object = User(params=params,
lan=lan,
language=language)
user_object.new()
if user_object.success:
data = {
"success": True,
"message": user_object.message,
... | b0d54380f5524f9df1268c67bb56c3b6ad86e82f | 68,689 |
import torch
def hflip(input):
"""
Horizontally flip a tensor image or a batch of tensor images.
"""
w = input.shape[-1]
return input[..., torch.arange(w - 1, -1, -1, device=input.device)] | 0d0606cc5c1858e574c6ba41130c1feba612aa37 | 68,690 |
import ast
from typing import List
def check_for_unstack(node: ast.Call) -> List:
"""
Check occurence of the `.unstack()` method on the pandas data frame.
Error/warning message to recommend use of `.pivot_table()` method.
"""
if isinstance(node.func, ast.Attribute) and node.func.attr == "unstack"... | a2796059429486024faa68b930bf1f32ecc9db5c | 68,691 |
def healpixMap(nside, lon, lat, fill_value=0., nest=False):
"""
Input (lon, lat) in degrees instead of (theta, phi) in radians.
Returns HEALPix map at the desired resolution
"""
lon_median, lat_median = np.median(lon), np.median(lat)
max_angsep = np.max(ugali.utils.projector.angsep(lon, lat, l... | c17ab5bce748309a24bc16838db24d2dca87cc9b | 68,692 |
from presqt.targets.gitlab.functions.fetch import gitlab_fetch_resource
import requests
import base64
import json
def gitlab_fetch_keywords(token, resource_id):
"""
Fetch the keywords of a given resource id.
Parameters
----------
token: str
User's GitLab token
resource_id: str
... | 019628d43a5be648b3af2a57fbce9b37f8e178cf | 68,693 |
def add_sp2_hydrogen(site, neighbors, length: float = 1):
"""convert x-C=z to x-CH-z"""
assert len(neighbors) == 2
vector0 = make_vec(neighbors[0].site.coords, site.coords)
vector1 = make_vec(neighbors[1].site.coords, site.coords)
summed = vector0 + vector1
summed = summed / np.linalg.norm(summ... | 937fa93d780addc59524d0c4fe06ef35f744c509 | 68,694 |
def ok_resp(data, message=None):
"""Return a SuccessResponse with success=True and data"""
return BasicResponse(True, message=message, data=data) | b1c9f2aff61df4a135c9531e467d297b9a252bbf | 68,697 |
def compute_prediction_interval(model, data_eval, percentile=95):
"""
A function that compute the prediction interval based on the predictions of each trees of a random forest.
Parameters
----------
model: a fitted RandomForestRegressor.
data_eval: A panda or numpy matrix of da... | dc7aae7283847b64437d78e9b7d1649b9b32b3a1 | 68,698 |
def logistic(y):
"""
Function for calculating sigmoid activation.
"""
try:
return 1. / (1. + cumath.exp(-y))
except RuntimeWarning:
raise Exception("Overflow Encountered. Check your model!") | 2eb7ba05fee8e2121b7863ad418a894fa4140a69 | 68,699 |
def check_fitler_domain(http_url):
"""
domain过滤检测,仅检测二级或者三级域名
返回值:
True:过滤
False:不过滤单
"""
uri = urlparse(http_url)
domain_name = f"{uri.netloc}"
domain_list = domain_name.split(':')[0].split('.')
if len(domain_list) < 2:
return True
elif len(domain_list) > 2 and domai... | 8a768785b865260e65e79065457ddc27dec3cc1e | 68,700 |
def two_equations_system_guess(x0A, eqA, eqB, verbosity=False, niter_max=100, tolerance=1e-8):
"""
"""
iterate = True
it_counter = 0
residual0 = 0
while iterate:
it_counter += 1
xiB_guess = eqA(x0A)
xiA = eqB(xiB_guess)
residual = ((xiA - x0A)/x0A)
... | d5a4fea9250b473150a658fef46ef8fd1c16ee41 | 68,701 |
def zeropad_1501(name):
""" Arxiv IDs after yymm=1501 are padded to 5 zeros """
if not '/' in name: # new ID
yymm, num = name.split('.')
if int(yymm) > 1500 and len(num) < 5:
return yymm + ".0" + num
return name | d2a46fccf649a59194b55ff0542bd6bfbe0d8629 | 68,703 |
def performSA(
initLabels,
initRegionList,
initRegionSpatialAttr,
threshold_array,
weight,
distance_matrix,
threshold,
alpha,
tabuLength,
max_no_move,
):
"""perform the tabu list integrated simulated annealing algorithm
Parameters
----------
initLabe... | 45cb617eb2b85440d97e34c40dd7c40fdd295f06 | 68,704 |
def split_locale(locale):
"""Returns a tuple (language, TERRITORY) or just (language, )
from a a :class:`babel.core.Locale` instance or a string like `en-US` or
`en_US`.
"""
if isinstance(locale, Locale):
tloc = [locale.language.lower()]
if locale.territory:
tloc.append(l... | 6f2766818a9815d5d4c8a27597e8cd3bf894f89c | 68,706 |
def value(a):
"""
Returns a.value if a is a Variable, or just a otherwise.
"""
if isinstance(a,Variable):
return a.value
else:
return a | af45a6223ccd885fe04d51ec40cac52010f6b023 | 68,707 |
from typing import Dict
from typing import Any
import requests
def add_builds(base_url: str, body: Dict[str, Any]) -> Any:
"""
Add IIB build
Args:
base_url (str): Base URL of IIB API
body (Dict[str, Any]): Add build request payload
Returns:
Any: IIB api response
"""
s... | 272b066a5e96d65499477e9c5123af06f8b868f6 | 68,708 |
def seq2seq_model(input_data, target_data, keep_prob, batch_size,
source_sequence_length, target_sequence_length,
max_target_sentence_length,
source_vocab_size, target_vocab_size,
enc_embedding_size, dec_embedding_size,
rnn_size, ... | e6ab4f68267ac19fdec0226d43b8b9620d3a3cfd | 68,711 |
def encode_categorical_classes_v2(events):
"""
velocities = 0 - velocity_bins
times = (velocity_bins + 1) - (velocity_bins + time_bins + 1); (+ velocity_bins + 1)
notes = (time_bins + velocity_bins + 2) - (prev + 87) (+ time_bins + velocity_bins - 19)
note_off = (time_bins + velocity_bins + 90) - (p... | e04a27e16622e28cd9c1075fa9a1561a0b7d9fab | 68,712 |
def get_person_applications(person_id: str = None):
"""
Returns all applications for a particular person.
:param person_id: The numeric ID of the person you're interested in.
:returns: String containing xml or an lxml element.
"""
return get_anonymous('getPersonApplications', person_id=person_... | f97dff319e27f256ac2dff10747a0bc1ff594b08 | 68,713 |
def get_bounding_box(X_masked, Y_masked):
""" Get Bounding Box.
# Arguments
X_masked: tuple of size (crop_size, 1).
Y_masked: tuple of size (crop_size, 1).
# Returns
bounding_box: List of length (4).
"""
x_min, x_max = np.min(X_masked), np.max(X_masked)
y_min, y_max = n... | bede349c5b558bd763c9a999f758e27d96242847 | 68,714 |
def __labels(known_labels, trans, labels):
"""Convert list of label names to label dictionaries with all info.
"""
return {
lbl: {
"title": trans.gettext(known_labels[lbl]['title']),
"description": trans.gettext(known_labels[lbl]['description']),
"severity": known... | 55652386496f1312ae66f64ae7673ad43d1e1879 | 68,715 |
from typing import Tuple
from typing import Optional
import json
def extract_hive_extra_setting(
connection: Connection,
) -> Tuple[Optional[str], Optional[str], Optional[int], Optional[bool]]:
"""Extract extra settings.
# Parameters:
connection (Connection): airflow connection
# Returns
... | 9ccb5d1e16b9fec1fb57f54fe8a1a7365dc7d6c4 | 68,716 |
def matrix_factory(m, n, number_generator, formula):
"""
A factory for generating matrices.
The factory takes parameters controlling the size of the matrix to be
generated, as well as the iterator to generate the number sequence and the
formula to use to compute each element of the matrix.
The... | 24f90a84b303d80e3cf89d1a588b1e151839567b | 68,717 |
def typechecker(in_=(), out_=(type(None),), msg_=None):
"""
Util function wrapper to check the type of the parameters passed to a
function.
Parameters
----------
in_ : tuple(tuple(type))
Reference of ingoing parameters' types.
out_ : tuple(tuple(type))
Reference of outgo... | 3bafe4db441b6c6a9cfb3f6322b8176f611f2f9c | 68,718 |
from typing import OrderedDict
def make_fits_objects(this_directory, fits_filenames):
""" Assemble valid, time-sorted FITS objects into (1) a list and (2) an OrderedDict by filename:
:param this_directory:
:param fits_filenames:
:return:
"""
all_fits_objects = [FITS(this_directory, '', fn) for... | 34c58cc0b94c1a420791318eb12d381d189b0159 | 68,719 |
def val_midpoint_of_line_cluster(array_line_cluster):
"""
Gets a center point of a line cluster
Hadfield and Lasenby AGACSE2018
"""
# Allocate some space for our finished matrix
accumulator_matrix = np.zeros((32, 32))
# Loop over our lines and construct the matrix
for i in range(array_l... | cdf674ababaa58e604553a80d2e3cbd8eaadcc24 | 68,720 |
def get_top_by_activity(activity: str) -> list:
"""
возвращает кол-во завершённых активностей по ТИПУ активности
:param activity: str ID в телеграма
:return: list
"""
return list(User.select(fn.COUNT(Activity.id).alias('totalcount'), User.username)
.join(Activities).join(Activity... | be86a3f134cddc4e24a7af6894c97cac6b4138ad | 68,721 |
def get_conf(splunkd_uri, session_key, owner, app_name, conf_name, stanza=None):
"""
:param splunkd_uri: splunkd uri, e.g. https://127.0.0.1:8089
:param session_key: splunkd session key
:param owner: the owner (ACL user), e.g. "-", "nobody"
:param app_name: the app"s name, e.g. "Splunk_TA_aws"
:... | 2a21a7fbb599215418d1efe863f6b2e884053e2f | 68,722 |
import binascii
def hexlify(data):
"""The binascii.hexlify function returns a bytestring in
Python3, but sometimes we want to use its output to
show a log message. This function returns an unicode
str, which is suitable for it."""
return binascii.hexlify(data).decode('ascii') | a24bf82a71a15dab12b2f683833c8a250a63097e | 68,723 |
import types
def stringToName(sname):
"""stringToName(string) -> CosNaming.Name
Convert a stringified name to a CosNaming.Name"""
# Try to understand this at your peril... :-)
#
# It works by splitting the input string into a list. Each item in
# the list is either a string fragment, or a single... | 76b0c1d279d100ea436ae0599bcf3c4d9278649e | 68,725 |
def pm_verify(request, state="NOP"):
"""This method can be used to verify the SUT is in a specified PM state."""
pm = Pm()
pm.verify()
return HttpResponse("Verified in %s" %state, mimetype="text/plain") | 74db962bd5d7e6940816784170ee09f6b29c5829 | 68,726 |
def create(**kwargs):
"""
Creates a new API Key.
:param kwargs:
:return:
"""
api_key = ApiKey(**kwargs)
database.create(api_key)
return api_key | 8047267a5ab8a3c4f119ba4149431d022403553e | 68,727 |
def aggAcceleration(x):
"""Aggregate acceleration inside a segment of data
Args:
x: Position values in a segment
Returns:
Aggregated velocity (single value)
"""
a = np.gradient(np.gradient(x))
# Return the highest absolute peak
return a[np.argmax(np.abs(a))... | 2c6b514ecf7fe7649f73fa2343d825df300393f0 | 68,728 |
def _make_head_map():
"""Hardcoded Head variables mapping."""
return {"predictions/kernel:0": "dense/kernel", "predictions/bias:0": "dense/bias"} | 1fde16e3ccabc4afa7764a2240be16719d146368 | 68,730 |
def calculate_cosine_similarity_matrix(v1, v2):
"""Calculate the cosine similarity matrix between two
sentences.
"""
# Shape: (batch_size, 1, num_sentence_words1, rnn_hidden_size)
expanded_v1 = tf.expand_dims(v1, 1)
# Shape: (batch_size, num_sentence_words2, 1, rnn_hidden_size)
expanded_v2 =... | 82b33a98d5ed1384c09bceb56631643328f480d1 | 68,731 |
def site_config_processor(request):
"""Context processor to make SITE_CONFIG available to all templates."""
return {'SITE_CONFIG': SITE_CONFIG} | a948804c30ed5f1b73b69527624642f7dd39762d | 68,732 |
def not_number_message(*numbers) -> str:
"""
Формирует сообщение о неправильности чисел
:param numbers: Список чисел
:return: Отформатированное сообщение о ошибке
"""
return md.text(
md.hbold('[Ошибка]'), md.hcode(*numbers, sep=' или '), NOT_DIGIT
) | bffcb89053e81a0e62301b193ed2e46d5a3f8d56 | 68,733 |
def subclass(bases, name, suite={}, doc=None):
"""Return a class that inherits from bases
bases is the base class or classes, name is the name of the class, suite is a mapping of
attributes that the subclass should have.
Unfortunately only the metaclass of the first base class will be used at class c... | 8633b24c6b4bc9ef2eda802981a8b817d427cbb4 | 68,734 |
def call_c_function(c_function, descriptor):
"""Call a C function in a dynamic library. The descriptor is a dictionary
that contains that parameters and describes how to use them. """
# set the return type
c_function.restype = c_int
# parse the descriptor, determine the types and instantiate variab... | 4f28fd0b25b3e52d5d5a1740cf64c144dad60bbc | 68,735 |
def get_controller_in_cloud(cloud):
""" Returns a controller that is bootstrapped on the named cloud
Arguments:
cloud: cloud to check for
Returns:
available controller or None if nothing available
"""
controllers = get_controllers()['controllers'].items()
for controller_name, controlle... | 3408ef10fbb3bca8e254ebf0820454306f7193ec | 68,736 |
import time
import socket
def wait_for_dns_resolution(fqdn, timeout=30):
"""Wait for DNS to resolve a required FQDN"""
start = time.time()
end = start + timeout
while time.time() < end:
try:
socket.gethostbyname(fqdn)
return True
except socket.error:
... | ec558d8645bd202dde2510bac382e294080057dd | 68,737 |
def extract_token_argument(args):
"""Return token specified on command line.
"""
if args.token_from is None:
return args.token
return args.token_from.read().rstrip() | 63f640282cc723ea9df9b802857c4d4b68b1ddec | 68,738 |
def get_vlan(username):
"""Obtain all the different vLANs given person owns. The returned dictionary
maps the vLAN name to its tag id.
:Returns: Dictionary
:param username: The owner of the vLANs
:type username: String
"""
# Order of vlan_name, tag matters
get_sql = """SELECT vlan_name... | 0f8b4532dede2f335279cb753e47be1efd92ac1b | 68,739 |
import re
def format_condition_value(conditions):
"""
@summary:
['111', '222'] -> ['111', '222']
['111', '222\n333'] -> ['111', '222', '333']
['111', '222\\n333'] -> ['111', '222', '333']
['', '222\n', ' 333 '] -> ['', '222', '333']
[111, 222, 333] -> [111, 222, 333]
... | a62083b65a9b887ed4f1285a68cfe6ecce628613 | 68,740 |
async def generate_token(
user_gen: UserGen,
user: UserInDB = Depends(get_root_user)
):
"""Generaate user token
Note:
- In real application, once we generate a token for a user, we should
save it in a database.
- However, here we just return the token. This is the case where y... | f38ae7a3d7d67b51b478cd9ddf3642e38cc84c7e | 68,741 |
def train_example(model, image_tensor, criterion, optimizer=None,
num_chains=1, backprop=True):
""" Trains the model on a single image tensor and returns the loss """
# Require optimizer if backprobagating gradients
if backprop:
assert optimizer is not None
image_variable = Variable(im... | bc7ca744309413d982b867850b6bdce800ec7262 | 68,742 |
def report_volume( input, hdr=None, label=None, mask=None ):
"""Report (just print) the approximate volume of the input (convert to binary first).
This wrapper for get_binary_volume() allows one to call that function to report (print) the current working volume, and return the input rather than the volumes... | 6eae94ddbb51e45db1b6b7e574e4652f53975d4f | 68,743 |
import re
def non_ag_mismatches(read_seq, md, sense):
"""
Given a read sequence, MD tag, and 'sense' (look for AG if sense,
look for TC if antisense), return the number of non-AG/TC mismatches
seen in the read.
:param read_seq: string
:param md: string
:param sense: boolean
:return no... | 5c57d0b4f9f880bf1da51865b3afe43a5a02dc30 | 68,745 |
def atom_van_der_waals_radius(gra, key):
""" van der waals radius for an atom in the graph (in angstroms)
"""
symb_dct = atom_symbols(gra)
symb = symb_dct[key]
rad = ptab.van_der_waals_radius(symb) * phycon.BOHR2ANG
return rad | f7a91e769e547718846d7165655c8dad523b59cf | 68,746 |
def _get_envelopes_min_maxes(envelopes):
"""
Returns the extrema of the inputted polygonal envelopes. Used for setting chart extent where appropriate. Note
tha the ``Quadtree.bounds`` object property serves a similar role.
Parameters
----------
envelopes : GeoSeries
The envelopes of the... | 36657377957e51ae374bf288348ce682d493a4e7 | 68,747 |
def new_whip(game_state):
"""
A composite component representing a Sword item.
"""
c = Composite()
set_item_components(c, game_state)
set_melee_weapon_component(c)
c.set_child(Description("Whip",
"An unusual weapon, most often used for torture."))
c.set_child(... | 0b76d89b14b14f09b46ea339d15792725d969a94 | 68,749 |
def output_add(fhandle):
"""
Set the current default output target filehandle for output routines in this module.
This sets the output destination in a stack so that the prior output can be restored
using the associated routine output_pop
Parameters:
fhandle (file): the new output destinati... | 94cc348089c03fec4ba9758fd2f5f52e96705dff | 68,750 |
def calc_ol_terms(b_xyz, j_xyz, moments_i, moments_e):
"""Compute terms of the Ohm's law.
Parameters
----------
b_xyz : xarray.DataArray
Time series of the magnetic field.
j_xyz : xarray.DataArray
Time series of the current density.
moments_i : list of xarray.DataArray
... | 48d34876e0b185e95e654f103304036c17f6ea3c | 68,751 |
def brailleify(data):
"""
>>> brailleify([0b_1000_1000, 0b_0001_0001, 0b_1111_0000, 0b_0000_1111])
'⠉⣀⡇⢸'
>>> brailleify([0b_1010_1010, 0b_0101_0101, 0b_1111_0110, 0b_0110_1111])
'⠭⣒⡷⢾'
>>> brailleify([0b_1100_1001, 0b_1001_1100, 0b_1001_0011, 0b_0011_1001])
'⢋⡙⣡⣌'
"""
return ''.join... | 4eff70272f2a28900b8b154d4c5ec183cee271e4 | 68,752 |
def y_flip_var():
"""
Label noise:
- float for global label noise
- tuple for separate label noise for every class
"""
return [0.01] | 11c0dfefa1c475794416e0559cc50e026a5244c5 | 68,753 |
def games():
"""load the select game dificulty page"""
return render_template("games.html", name=current_user.name) | 578906cca6114e689841a1e2375a3cf04cb374a9 | 68,754 |
def aggregateByGrid(df, field, summary, gridSize):
"""
Aggregates the specified field with chosen summary type and user
defined grid size. returns aggregated grids with summary
Parameters
----------
df : geopandas dataframe
field : string
field to be summarized.
summary : st... | 04c3c9774baa8212a68c59722858d9c83f157aba | 68,756 |
def vote_comment(_sub, _pid, cid):
""" Logs an upvote to a post. """
uid = get_jwt_identity()
value = request.json.get("upvote", None)
if type(value) is not bool:
return jsonify(msg="Upvote must be true or false"), 400
return misc.cast_vote(uid, "comment", cid, value) | 0246bf0f0f6f42439a3c50fdd574f82415c8cb4d | 68,757 |
def scalar_to_tensor(x):
"""Convert a scalar to a tensor"""
return Tensor(x) | 84f055ef07da2f704e37f08bd95f37ca4b7ab600 | 68,758 |
def getMissingCounties(counties: pd.DataFrame, drought: pd.DataFrame):
"""Checks counties that do not have a match to the drought data
These are the counties that we have, but are not in the data
Parameters:
counties: DataFrame
drought: DataFrame
Returns:
missingCounties[county_fips]: np.a... | 2f9327bd87b0963d0f1e848f80e158adf9597a6d | 68,759 |
def sum_combiner(key, value, buf, done, params):
"""
Sums the values for each key.
This is a convenience function for performing a basic sum in the combiner.
"""
if not done:
buf[key] = buf.get(key, 0) + value
else:
return buf.items() | c3cb2567efe78b4e35ffadc72ffa69a6305aa05c | 68,760 |
from datetime import datetime
import json
def hello(name: str):
"""Create a new message and send it to Rabbitmq"""
try:
json_message = {
'uid': str(uuid4()),
'creation_date': datetime.utcnow().strftime("%Y-%m-%dT%H:%M:%S.%fZ"),
'say hello to': name
}
... | b6f395ee59caad2d352ea6fffe2b68a6938287f7 | 68,761 |
from typing import Dict
def get_all_excel_sheets_as_dataframes(filepath: str) -> Dict[str, pd.DataFrame]:
"""
Takes `filepath` to an Excel file. Returns dictionary having keys = sheet names, and
values = DataFrame corresponding to respective sheet name.
"""
sheet_names = get_all_excel_sheet_names(... | ac38d506fbb9c67a6dfaca08baaabffeb87ed25f | 68,762 |
import tokenize
def build_model():
"""
Function used to create the ML pipeline and parameters to validate.
Returns: Model Object.
"""
# Model Pipeline.
pipeline = Pipeline([
('vect', CountVectorizer(tokenizer=tokenize)),
('tfidf', TfidfTransformer()),
('clf', MultiOutputClassi... | 882ca9e596feaeb539892de202f6ef3183645007 | 68,763 |
def get_mitigations_table_data(technique, reference_list, next_reference_number):
"""Given a technique a reference list, find mitigations that mitigate
technique and return list with mitigation data. Also modifies the
reference list if it finds a reference that is not on the list
"""
mitigat... | ef03d94e97bc9322c7e625f0ed00eccbd629a3a6 | 68,764 |
def int_to_str(num):
"""takes num e.g. 123 and outputs 'one hundred and twenty three'"""
b = strip(num)
c = []
length = len(b)
count = length-1
temp = 0
while count >= 0:
if temp == 3:
temp = 0
if temp == 0:
c.append([])
c[-1].append(b[co... | ba714c527eb0368d9ab8dca24e8d28e1074879f2 | 68,766 |
def config_flask_globals(app):
"""Configure a Flask app to use all functions as template_globals."""
app = _inject_template_globals(app, _get_funcs(filters))
return app | 9c5f237a2af030b2c4391cb6e975aa01ef7096e5 | 68,767 |
import copy
def update_fits_header(
header: hint.Header, entries: dict, comments: dict = {}
) -> hint.Header:
"""This appends entries from a dictionary to an Astropy header.
This function is preferred to adding using standard methods as it performs
checks to make sure it only uses header keys reserve... | 83303aac4b44c9519d7d4e4c96504d9cfa425d19 | 68,768 |
def from_continuous_prediction(prediction, width, height):
"""Construct an instance from an instance of
:class:`ContinuousPrediction` using the grid size and offset specified
in that instance. This is more efficient as we sample each grid cell
once and then store the result.
:param prediction: An ... | 2e969b837386878cbe2ca7a632aaf8f3756d2cc3 | 68,769 |
from typing import Optional
def A_star(start: Node, end: Node, neighbours: Neighbour, heuristic: Optional[Heuristic]=None, draw=None):
"""Priority-search. Perform an A-star or Dijkstra search on the graph. If heuristic is not provided, will perform standard
Dijkstra search. If heuristic is provided, perform A... | 833cd564d7713bea4a8f9182e843cc0679468e90 | 68,770 |
from typing import Set
def get_s2_patches_with_seasonal_snow() -> Set[str]:
"""List all patches with seasonal snow from **original** BigEarthNet-S2 dataset."""
return _conv_single_col_csv_resource_to_set(Resource.patches_with_seasonal_snow) | 97a646664dc7e2b2dcc5dd30ab9ab4d71ee7e2aa | 68,771 |
def extract_atoms_from_residue_group(residue_group):
"""
Given a residue_group object, which may or may not have multiple
conformations, extract the relevant atoms for each conformer, taking into
account any atoms shared between conformers. This is implemented
separately from the main validation routine, whi... | 1c68f45c739db1fbbe1999b8a59bcfbd1d329f03 | 68,773 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.