content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
import traceback
def get_axes_texts(img, axis_entities):
"""The function for getting the texts in the axis"""
try:
data = []
# No axes in the image
if img is None or axis_entities is None:
return data
(img_height, img_width) = img.shape[:2]
for axis_id, axis... | 1f1bd3f7b5a6561df27c57bf95ccdf3e8700deee | 3,614,145 |
import typing
import torch
def mixture_component_selection_embedding_(subset_embeds: typing.Mapping[str, Tensor], s_key: str, flags,
weight_joint: bool = True) -> Tensor:
"""
For each element in batch select an expert from subset.
subset_embeds: embeddings of eac... | 970d3413356ffeb45be6c96cc31f137a2ce160d6 | 3,614,146 |
def filter_same_smiles(dset):
"""
Filter out species whose conformers don't all have the same SMILES. Can happen
because, for example, CREST simulations can be reactive. This won't happen if
conformers are generated using RDKit.
Args:
dset (nff.data.dataset): NFF dataset
Returns:
... | 968ffa6de9c3dd4c09620b4aa6bd94ac2f191b27 | 3,614,148 |
import logging
def user_popup(request):
"""/user_popup - Pop up to show the user info."""
try:
return _user_popup(request)
except Exception as err:
logging.exception('Exception in user_popup processing:')
# Return HttpResponse because the JS part expects a 200 status code.
return HttpHtmlRespons... | 0daa09fb4f6b173af0794e37b7276638f732fa0e | 3,614,149 |
from nltk.tokenize import RegexpTokenizer
from nltk.corpus import stopwords
from nltk.stem.wordnet import WordNetLemmatizer
def tokenize_word(text,
normalise_case=True,
keep_numerics=False,
shortwords=3,
remove_stopwords=True,
l... | 83790a61a2d17cb3442d9388c58e13f3b8339b66 | 3,614,150 |
def read_video(fname):
"""
Parameters
----------
fname
Returns
-------
"""
cap = cv2.VideoCapture(fname)
frames = []
it = 0
while True:
retval, image = cap.read()
if image is not None:
frames.append(image)
it += 1
if no... | 3a857ee51a5e04a3159a550c6652214203aef8ee | 3,614,151 |
def build_bankruptcy_definition(years):
"""Build a bankruptcy definition
Notes:
This function is set according to a line of best fit from Year 0 at -10% ROI to 10% ROI by Year 7.
Args:
years (int): No. of years for analysis
Returns:
Bankruptcy definitio... | c2364bd97eec587e57bc0d701d83b304631a8bd2 | 3,614,152 |
import textwrap
def run_pylint(source, msg_ids, *cmd_args):
"""Run pylint on some source, collecting specific messages.
`source` is the literal text of the program to check. It is
dedented and written to a temp file for pylint to read.
`msg_ids` is a comma-separated string of msgids we are intereste... | b7dd29571b85f607d36b4986e798de6dcda85e31 | 3,614,153 |
def compute_rot_scale_skew(lazAC, i=0, scaleFactor=1.):
"""
same as displayRotScaleSkew but without text output
"""
xshift = lazAC.Alm[i, 0] * scaleFactor
yshift = lazAC.Alm[i, lazAC.Nalm] * scaleFactor
if lazAC.k > 2:
idx_forXterm = np.where(lazAC.polynomialTermOrder == 'x')[0]
... | 4e3fa5ac0d3b1a0402cbebf7994eb0fb5acb286a | 3,614,156 |
import tempfile
import struct
import zlib
def readsav(file_name, idict=None, python_dict=False,
uncompressed_file_name=None, verbose=False):
"""
Read an IDL .sav file
Parameters
----------
file_name : str
Name of the IDL save file.
idict : dict, optional
Dictionary... | 1f056375d04bf8adddca86569c98f7d18708c351 | 3,614,157 |
import pickle
def top_results_overall(databases= 'all', n_entries= 10):
"""
Creates a table summarizing the overall performances
Args:
databases (str): 'all'/'high_ir'/'low_ir'/'high_n_min'/'low_n_min'/'high_n_attr'/'low_n_attr'
n_entries (int): number of entries to show
"""
result... | 04feeeef502b4b01c12574351aaa3b83d17c1066 | 3,614,158 |
def clean_data(data):
"""
Clean data from Kobo
:param data: Pandas DataFrame containing data from Kobo
:return: Pandas DataFrame
"""
# Remove unnecessary columns
drop_cols = ['subscriberid', 'deviceid', '_uuid', '_submission_time', '_validation_status', '_id', 'start', 'end',
... | 3defebabca1fdcd8bef96c1bec830d13cd63a571 | 3,614,159 |
def ignore_sparse_panel_future_warning(func):
"""
decorator to ignore FutureWarning if we have a SparsePanel
can be removed when SparsePanel is fully removed
"""
@wraps(func)
def wrapper(self, *args, **kwargs):
if isinstance(self.panel, SparsePanel):
with assert_produces_w... | 01d946c958f887008cdced6b62015b847393de2e | 3,614,160 |
def bad_unpacking():
""" one return isn't unpackable """
if True:
return None
return [1, 2] | dd241b5aa49b58300fd883d61b5eb41b1eb92aa1 | 3,614,161 |
def build_slices_from_list_of_arrays(list_of_arrays, n_his, n_feat, verbose=0):
"""
This function creates a list of slices of shape (n_his + 1, n_feat)
"""
assert list_of_arrays[0].shape[1] == n_feat, "list_of_arrays[0].shape[1]={} but n_feat={}".format( list_of_arrays[0].shape[1], n_feat)
X_sl... | bfec73928e84a07eab9fc00f2cf9c8b1d5ca31cb | 3,614,162 |
def most_similar(text, topn=10):
"""检索最相近的topn个句子
"""
token_ids, segment_ids = tokenizer.encode(text, maxlen=maxlen)
vec = encoder.predict([[token_ids], [segment_ids]])[0]
vec /= (vec**2).sum()**0.5
sims = np.dot(a_vecs, vec)
return [(kkk_all[i], sims[i]) for i in sims.argsort()[::-1][:topn]... | 1368a3f0c05fe8761be226c3a696e98bbaadf034 | 3,614,163 |
import types
def orient_by_rois(streamlines, roi1, roi2, in_place=False,
as_generator=False, affine=None):
"""Orient a set of streamlines according to a pair of ROIs
Parameters
----------
streamlines : list or generator
List or generator of 2d arrays of 3d coordinates. Each... | b0c3a25528d2f2a6a325161f9621e604541e9176 | 3,614,164 |
def luhn_checksum(check_number):
"""http://en.wikipedia.org/wiki/Luhn_algorithm ."""
def digits_of(n):
return [int(d) for d in str(n)]
digits = digits_of(check_number)
odd_digits = digits[-1::-2]
even_digits = digits[-2::-2]
checksum = 0
checksum += sum(odd_digits)
for d in even_... | 4209fd2f77acb240e7e2adfca63d638bb6f79187 | 3,614,165 |
import importlib
def _data_api():
"""Returns a Data API.
This relies on Django settings to find the appropriate data API.
"""
# We retrieve the settings in-line here (rather than using the
# top-level constant), so that @override_settings will work
# in the test suite.
api_path = getattr(... | 7a5b7bb3be6d86bd8bb3872a6bc0a9934b84f001 | 3,614,166 |
def get_system_log_queue():
"""
Json格式为:
{'alias':'w01'
'host':'192.168.1.100'
'timestamp':123213123
'type': 'reboot' or 'shutdown' or 'power' 三个值中其中一个
}
"""
system__log_queue ='ztq:queue:system_log'
return get_limit_queue(system__log_queue, 200) | 46329d3f5765b7fc07add5b2cec7b0978b8b6873 | 3,614,168 |
def blockchain_timeframe_summary(final_df, config) -> dict:
"""
Get summary statistics
:param final_df: The full dataframe of address information from the blockchain
:param config: configuration file for including start/end times in output dataframe
"""
print("Getting summary counts of analysi... | eedbb4e33bfdb937426ace26eba10427694356ec | 3,614,169 |
def user_has_custom_top_menu(domain_name, couch_user):
"""
This is currently used for a one-off custom case (ewsghana, ilsgateway)
that required to be a toggle instead of a custom domain module setting
"""
return (toggles.CUSTOM_MENU_BAR.enabled(domain_name) and
not couch_user.is_superus... | 735d119a5875cbf96b3f753fac334a51583f7477 | 3,614,170 |
import binascii
def b2x(b):
"""Convert bytes to a hex string"""
return binascii.hexlify(b).decode('utf8') | fded3635120d44436159908ed04e4384be1e5b47 | 3,614,171 |
import itertools
import logging
def get_size_k_subgraphs(graph, min_region_count, k=1, keep_grammars=[]):
"""for size k, get all unique subgraphs
"""
total = 0
subgraphs = []
current_subgraph_len = 0
for node_subset in itertools.combinations(graph, k):
subgraph = graph.subgraph(node_su... | 28b2df2256d0e337f0905c183c6a0a41dc68bf1b | 3,614,172 |
import numbers
def list_to_blackbird(A, var_name):
"""Converts a Python nested list to a Blackbird script array type.
Args:
A (list[list]): 2-dimensional nested list
var_name (str): the array variable name
Returns:
list[str]: list containing each line representing the
... | 80babac6cb03dfe0b0ef396e4dba45fb2fb4692a | 3,614,173 |
def CreateOptim(parameters, lr=0.001, betas=(0.5, 0.999), weight_decay=0,
factor=0.2, patience=5, threshold=1e-03, eps=1e-08):
""" Creates optimizer and associated learning rate scheduler for a model
Paramaters
----------
parameters : torch parameters
Pytorch network parameters ... | 95041c17f613d98dfbadb063c7117b4202e59ee3 | 3,614,174 |
def prepare_images_tensorflow(images: np.ndarray) -> np.ndarray:
"""
Prepares an image ndarray to fit into the tensorflow NHWC
Args:
images: The images in an nxmxm format
Returns:
The images in the NHWC tensorflow format.
"""
return images.reshape(*images.shape, 1) | b8be86bc6efb9ad076a61779a35e9bda98aa3f24 | 3,614,177 |
import click
def line_width_option(**kwargs):
"""Get line width option for the plots"""
def custom_line_width_option(func):
def callback(ctx, param, value):
ctx.meta["line_width"] = value
return value
return click.option(
"--line-width",
type=F... | ef846fc4c8ba54891aac166aaf09d31816d83934 | 3,614,178 |
import ctypes
def make_array_ctype(ndim):
"""Create a ctypes representation of an array_type.
Parameters
-----------
ndim: int
number of dimensions of array
Returns
-----------
a ctypes array structure for an array with the given number of
dimensions
"""
c_int... | c83ab386d40043d49d1b86c21c2789c461999fc5 | 3,614,179 |
def get_popular_article():
"""Get top 3 most popular articles"""
query_command = "SELECT * from popular_posts LIMIT 3"
query_data = run_query(query_command)
return query_data | 1a2416746f8a74e5fa1028266a5bdf619f97aff8 | 3,614,180 |
def get_json_request_header():
"""
Return the header for JSON request
:return:
"""
return {'Accept': 'application/json', 'Authorization': 'Token sessionTokenHere==', 'Accept-Language': 'en'} | 9767910ae8e4c1fe8993ab45fa2331e9ea6efad1 | 3,614,181 |
def diffraction_limited_mtf(fno, wavelength, frequencies=None, samples=128):
"""Give the diffraction limited MTF for a circular pupil and the given parameters.
Parameters
----------
fno : `float`
f/# of the lens.
wavelength : `float`
wavelength of light, in microns.
frequencies ... | 003c578ff0a19b98e4d7658515f53eecd8a87f82 | 3,614,182 |
def warrior2_label_csv(pose_df, side='right'):
"""
takes averages of all rows (2d_points)
OLD order: head_front, sholders, arms, torso forward,
torso backward hips, knee acute, knee obtuse, step wider
1 - needs to be adjusted
0 - good
Order for 9 digit labeling:
1. arms
2. front_knee... | b9e8cfbd974607fb25ec5e27054674680f8c8ca1 | 3,614,183 |
from unittest.mock import Mock
import json
def check_client_method():
"""
Helper to test an API method -- returns a tuple of
(test_api_client, check_assertions) where check_assertions will
verify that the API method returned the data from http.request,
and that http.request was called with the cor... | 20c49495861a509c97c007009423a3ecabeabfb5 | 3,614,185 |
def CMDdiff(parser, args):
"""Displays local diff for every dependencies."""
parser.add_option('--deps', dest='deps_os', metavar='OS_LIST',
help='override deps for the specified (comma-separated) '
'platform(s); \'all\' will process all deps_os '
... | 7fd2c16e3ed63d4b39f1a35d969f6da76bf6a868 | 3,614,186 |
def Pwr(a, b):
"""
a to the power of b
:param a the base
:param b the power value
:return a^b
"""
c = 0
if a == 0:
c = 0
elif b == 0:
c = 1
else:
i = 0
c = 1
while i < b:
c = Mul(c, a)
i = i + 1
return c | fc560d6ec568f5297dc9d8fdfae2e938ecaee98f | 3,614,188 |
def random(pages : int = 1, wiki : str = WIKI, language : str = LANG):
"""
Get a list of random fandom article titles.
Returns the results as tuples with the title and page id.
.. note:: Random only gets articles from namespace 0, meaning only articles
:param pages: the number of random pages returned (max... | 785aa1179113367c6f1e565c8a2ef1f092898f60 | 3,614,189 |
def xilogxi(x):
""" x: scalar """
if 0 == x:
return 0
else:
return x*np.log(x) | 3baf0e2165c7d8b290d46705f1f333c47227d573 | 3,614,190 |
import requests
import logging
def remove_ipfs(ipfs_hash):
""" Removes pin from IPFS hash in Blockfrost """
ipfs_remove_url = f"https://ipfs.blockfrost.io/api/v0/ipfs/pin/remove/{ipfs_hash}"
headers = {"project_id": f"{config.BLOCKFROST_IPFS}"}
res = requests.post(ipfs_remove_url, headers=headers)
... | 28b148b91a3943041d549bec7fa7ae590c40a4ab | 3,614,191 |
def solution_list(request, cc_biz_id):
"""
套餐列表
"""
solution_list = Solution.objects.filter(cc_biz_id=cc_biz_id, ).order_by('-id')
solution_types = dict(fta_std.SOLUTION_TYPE_CHOICES)
now = timezone.now()
last_week = now - timedelta(days=7)
date_range = '%s to %s' % (last_week.strftime... | c18032502e268af54be0c3c8c408d9e33ce0f106 | 3,614,193 |
import platform
def get_uname():
"""Get uname."""
# Preferable to running a system command
uname = " ".join(platform.uname())
return uname | 18b7fc9ae6c51c0c5087ed67586a7fc358697405 | 3,614,195 |
import re
def find_run_tap_log_file(stdout, sync_engine=None):
"""Pipelinewise creates log file per running tap instances in a dynamically created directory:
~/.pipelinewise/<TARGET_ID>/<TAP_ID>/log
Every log file matches the pattern:
<TARGET_ID>-<TAP_ID>-<DATE>_<TIME>.<SYNC_ENGINE>.log.<... | e6ddad6fc64574e9306188285d91033d28eae442 | 3,614,196 |
def _kim_cnn_model(params, args, nb_classes, embedding_matrix):
"""
fully functional API style so that we can see all model details.
params will obtain model related parameters
:param params:
:param args:
:param nb_classes: # of labels to classify
:param embedding_matrix:
:return: a com... | 2cf777d0dfd9e6900776f0cf281010bc7d1d8bdf | 3,614,197 |
def everything_except(excluded_types):
"""hypothesis utility to generate everything but the types in excluded_types"""
return everything().filter(lambda x: not isinstance(x, tuple(excluded_types))) | e0b789cb8637e6bed2669f17cf33b4327a20d22c | 3,614,198 |
def get_country_names() -> list[str]:
"""Return country names."""
return [country.name for country in get_countries()] | a3118df56f3fd18ca74a7047a4e91448e07a06db | 3,614,199 |
def reindent(str, spaces=''):
"""
Removes any leading empty columns of spaces
"""
lines = str.splitlines()
lspace = [len(l) - len(l.lstrip()) for l in lines if l.lstrip()]
margin = len(lspace) and min(lspace)
return '\n'.join((spaces + l[margin:]) for l in lines) | af46a4440839fb38850d973df0d62abe02213755 | 3,614,200 |
def legal_dissonances(a_list, b_list):
"""
Takes two NoteList objects.
Return format is identical to vertical_intervals() above.
Returned tuples here, however, will only represent intervals that are
illegal in first species counterpoint, but legal in second species.
Second Species Exception:
... | dcec0a759d5f46d3d7d9a4ef1b8606ff15be3516 | 3,614,201 |
def mass2_batch(ts, query, batch_size, top_matches=3, n_jobs=1):
"""
MASS2 batch is a batch version of MASS2 that reduces overall memory usage,
provides parallelization and enables you to find top K number of matches
within the time series. The goal of using this implementation is for very
large tim... | 67de00132a15f0bedfd5ce0145249743a7dcb0a9 | 3,614,202 |
import torch
def getPretrainedModel(loss_module='ArcFace', model_path=CFG.model_path_arcface, device=CFG.device):
"""
Method to get pretrained model from file path
Args:
loss_module (string): loss function Arcface, softmax
model_path (nn.Modiule): Model path
device (torch.devic... | ce617fa49dc9e6ea1ead17cc83efc7e10a88ebd9 | 3,614,203 |
def handle_topic_data(json_data):
"""
- check if user start new topic
- check if user still talk about same topic
"""
intent = json_data['outcomes'][0]['intent']
"""
if session.expected_saying == intent:
#get last topic handler
#handle old topic
msg = handle_intent(se... | 04e610f341ba663841831cb7faa9b4e2d6bfa542 | 3,614,204 |
def get_closest_parameter(driver_name, curve_name, normalize=False):
"""
for nurbs curves only. get the closest parameter value.
:param driver_name: <str> the driving object.
:param curve_name: <str> the mesh object.
:param normalize: <bool> if set True, returns a normalized parameter value.
:r... | 41f71d0a306f0dacb884be79fc5e2893ea75f4d6 | 3,614,205 |
from re import A
def apply_mlp_svd_voting(object_id="M 79", topk=10, return_df=False, ignore_articles=None): # "* sig Ori"
"""
combines both results from above (MLP and SVD) to deliver a final scoring on most probably intersting
papers related to a given object
:param object_id:
:param t... | c6ae7a936a0150f30f7e43f8131dcc9c936c0f74 | 3,614,206 |
def income_percentiles(row, percentiles, prefix="total"):
"""
Estimate income percentiles from counts in the census income ranges.
Parameters
==========
row: pandas.Series
A series that contains binned incomes in the ranges given by
CENSUS_INCOME_RANGES.
percentiles: List[float... | ca44ef180f13c730a2eea10c4c4b576e8d54819e | 3,614,208 |
import socket
def process_zabbix(target):
"""Process a Zabbix target
Args:
target: the config file portion for this specific target.
Returns: None
"""
mm = MetricManager(target['name'])
zbxapi = SimpleZabbix(
url=target['api_url'],
user=target['api_user'],
pas... | 61525700697147892a6363e660bb04e6649d9540 | 3,614,209 |
import urllib
import yaml
def _fetch_global_config(config_url):
"""
Fetch the index_runner_spec configuration file from a URL to a yaml file.
"""
logger.info(f'Fetching config from url: {config_url}')
# Fetch the config directly from config_url
with urllib.request.urlopen(config_url) as res: ... | 5332deff7ad2e96ba4129942912efc775a8d363e | 3,614,211 |
import numpy
def readColorLUT(infile, distance_modulus, mag_1, mag_2, mag_err_1, mag_err_2):
"""
Take in a color look-up table and return the signal color evaluated for each object.
Consider making the argument a Catalog object rather than magnitudes and uncertainties.
"""
reader = pyfits.open(in... | 6bd281bf6434cc14f4a83b7257e24fb165483f90 | 3,614,212 |
def parse_config(conf, env):
"""Get the specific environment, expand any relative paths, and return
a url for create_engine
:param str conf: Name of config file without the file extension
:param str env: Name of the environment within the config file
"""
if env not in conf:
raise Config... | f54398f02a90bbbcc398cbe0cd9b7633ad614650 | 3,614,213 |
def train_model_if_possible(data_df:pd.DataFrame):
"""
add knowledge to skimind
:retrn: bool
"""
if not list(data_df.values):
# aucune nouvelle donnee a apprendre
return True
print(f"preprocessing build")
# train (learning) request object
request_train = preproc... | c89915b2bdd92efd83e51cd8a3bf21880691694f | 3,614,214 |
def eq_xtl(
Cl, D, F,
):
"""
eq_xtl calculates the composition of a trace element in the remaining liquid after a certain amount of
crystallization has occured from a source melt when the crystal remeains in equilibrium with the melt
as described by White (2013) Chapter 7 eq. 7.81. It then calculate... | 298a5557775a953a645aade70f41818e42e761ac | 3,614,215 |
def quantity_label(quantity):
"""Returns formatted string of parameter label
"""
labels = {
'accrate': r'$\dot{m}$',
'alpha': r'$\alpha$',
'd_b': r'$d \sqrt{\xi_\mathrm{b}}$',
'dt': r'$\Delta t$',
'fluence': r'$E_\mathrm{b}$',
'length': 'Burst length',
... | 467baf8f3d2ae72474e6f65e6990779e7cb10034 | 3,614,216 |
def main(inputs: str):
"""Run anagram function as a main method."""
text, check = inputs.split(" ")
return anagram(text=text, check=check) | ff417e95010aed0fd961ec37357af217c3466a23 | 3,614,217 |
def spreadsheet(service, id):
"""Fetch and return spreadsheet meta data with Google sheets API."""
request = service.spreadsheets().get(spreadsheetId=id)
try:
response = request.execute()
except apiclient.errors.HttpError as e:
if e.resp.status == 404:
raise KeyError(id)
... | 17412f8a05c1718bcc6259d3e4809122d6acd2c6 | 3,614,218 |
def fix_labels(mnist_label, add_num):
"""
Args:
label: [[int]] arary, class labels
n: int, number of add data
Returns:
[[int]] array
"""
c_num = len(mnist_label[0])
# add one dimention
fixed_label = np.c_[mnist_label, np.zeros(len(mnist_label))]
assert len(fixed_label[0])... | c721ecb285009f61d4a97b2217ceb97afc6ca717 | 3,614,219 |
from typing import Optional
def get_global_reach_connection(global_reach_connection_name: Optional[str] = None,
private_cloud_name: Optional[str] = None,
resource_group_name: Optional[str] = None,
opts: Optional[pulumi.Inv... | 28ea55e472b98f6333b9bfa38daab51367382bb5 | 3,614,220 |
def parseInertial(link_xml):
"""Parses the URDF xml definition of inertial data.
Args:
link_xml(ElementTree.Element): xml representation of 'inertial' field of URDF link
Returns:
: dict -- of inertial data
"""
inertial_dict = {}
inertial_data = link_xml.find('inertial')
if ine... | 307feba0a36a58c505c2249ef2f2c49ff180d788 | 3,614,221 |
def hexdump(data, start_address=0, compress=True, length=16, sep='.'):
""" Return string array in hex-dump format
:param data: The data array of bytes
:param start_address: Absolute Start Address
:param compress: Compressed output (remove duplicated content, rows)
:param length: ... | 5ea51c95dd297f140c2b96ad1ce10952e3b6e33e | 3,614,222 |
def precipitation():
"""Return the JSON representation of dictionary for the last year."""
# To find the last day:
lastday = list(np.ravel(session.query(Measurement.date).order_by(Measurement.date.desc()).first()))[0]
lastday = lastday.split("-")
year = int(lastday[0])
month = int(lastday[... | 20b92228c7bcc2bc18660b6e0f0545e8ace7ad86 | 3,614,223 |
def get_all_shared_user_info(user, includeCurrentSite=True):
"""Queries all nodes (including local node) for projects and groups the user belongs to.
Returns two lists of dictionaries but does NOT update the local database.
Example of JSON data retrieved from each node:
{
"users": {
... | 2810ce0a67653911aea9c57fd1e339d154073101 | 3,614,224 |
import torch
def binary_accuracy(output: torch.Tensor, target: torch.Tensor) -> float:
"""Computes the accuracy for binary classification"""
# 传入的output是batch x 1的tensor
with torch.no_grad():
batch_size = target.size(0)
pred = (output >= 0.5).float().t().view(-1)
correct = pred.eq(... | 17bfe60acc120c6d3d1578d7d3aff5231a860ff7 | 3,614,225 |
import asyncio
async def healthcheck_task1():
"""A healthcheck representing a database check."""
await asyncio.sleep(0.1)
return ("database is good!", HTTPStatus.OK) | 0e7a968349c26fc28a51781b8dc03c2184981563 | 3,614,227 |
def get_response(request):
"""
Fake view-like callback to use in middleware tests.
"""
return None | 711106895c1aa21847152763bdd05a1f9a367ed6 | 3,614,228 |
def set_proper_dtypes(df):
"""
forgot to save integers as integers. Only the distances feature columns have true floats.
"""
potential_integer_cols = df.columns.difference(list(df.filter(regex='distances.*', axis=1)))
for col in potential_integer_cols:
if str(df[col].dtype) != 'object':
... | 2a7d5f615c666d9a1778dfda1ba427c87541e34b | 3,614,229 |
def has_prefix(sub_s: str) -> bool:
"""
:param sub_s: (str) A substring that is constructed by neighboring letters on a 4x4 square grid
:return: (bool) If there is any words with prefix stored in sub_s
"""
if len(sub_s) > 1:
sub_str = sub_s[:2]
else:
sub_str = sub_s[0]
if s... | c873c2a1a03d6a892c1a043c521415f838d60a8c | 3,614,230 |
def stop(syncplan_name, p5_connection=None):
"""
Syntax: SyncPlan <name> stop
Description: Removes the plan <name> from the scheduler
Return Values:
-On Success: the string "1" (the plan was successfully removed)
the string "0" (the plan was not removed or running)
"""
... | 2cec430d9d23079e235c5c0fcfbd94bf1b51d6bb | 3,614,231 |
import torch
def global_nms(boxes, scores, iou_threshold):
# type: (Tensor, Tensor, float) -> Tensor
"""
Performs non-maximum suppression globally (regardless of category).
Parameters
----------
boxes : Tensor[N, 4]
boxes where NMS will be performed. They
are expected to be in... | 7a2529b16f4b887a3730609aeffeef9f1fc19b81 | 3,614,233 |
def calculate_stats(answers, predictions, cm):
"""
Prints the Stats for a given class label
:param answers: an array of answers
:param predictions: an array of predictions
:param cm: confusion matrix of form [[TP, FN], [FP, TN]]
"""
# confusion matrix looks like this [[ 23, 63], [ 40, 260]]... | f6c5e2fc54b69aa7bd48bd7e472fdcb64678b5af | 3,614,235 |
def auto_rotate(img):
"""
Automatically rotate the given image to put the eyes on top
:param img: The image to rotate
:type img: 1D numpy array, shape: (1, IMAGE_WIDTH**2)
:returns: The rotated image
:rtype: 2D numpy array, shape: (IMAGE_WIDTH, IMAGE_WIDTH)
"""
#Rotate the image in all ... | 7ef0497d8d6607b2e56ac5e2c51f627b1cc17062 | 3,614,236 |
def AddInstanceCommunicationNetworkOp(network):
"""Create an OpCode that adds the instance communication network.
This OpCode contains the configuration necessary for the instance
communication network.
@type network: string
@param network: name or UUID of the instance communication network
@rtype: L{gan... | 52d9b6f76b5f8723cf25db18edb74581c4942503 | 3,614,238 |
def get_expanding_count(datecol, idcol, targetcol=None):
"""
expanding counts
"""
unq_ids, idcol_inv = np.unique(idcol, return_inverse=True)
unq_dates, date_cnts = np.unique(datecol, return_counts=True)
n = len(idcol)
nunq = len(unq_ids)
learned_dict = np.zeros((nunq, ))
tmp_cnts = ... | 3ae06cca4796aae66db1ebec8273541de2f37927 | 3,614,240 |
from typing import Optional
from typing import List
def text_l(
content: str,
width: Optional[str] = None,
visible: Optional[bool] = None,
tooltip: Optional[str] = None,
commands: Optional[List[Command]] = None,
name: Optional[str] = None,
) -> Component:
"""Create ... | 609b0f7280a6b1aa2999f68d270da3cf5651843c | 3,614,241 |
def null_hurst_measure(measure):
"""Hurst computation parameter from some slope fit.
Parameters
----------
measure: float
the slope of the fit using some method.
Returns
-------
H: float
the Hurst parameter.
"""
# Compute measure
return float(measure) | 5cc8fc8efdf7901ef7af85e4014def95ebee164f | 3,614,242 |
def natSettings(ctx, mach, nicnum, nat, args):
"""This command shows/alters NAT settings.
usage: nat <vm> <nicnum> settings [<mtu> [[<socsndbuf> <sockrcvbuf> [<tcpsndwnd> <tcprcvwnd>]]]]
mtu - set mtu <= 16000
socksndbuf/sockrcvbuf - sets amount of kb for socket sending/receiving buffer
tcpsndwnd/tc... | 2b3e60e68f7c04e8f46b63acf3713297d781d852 | 3,614,243 |
def reduce_loss(loss, reduction):
"""Reduce loss compute.
:param loss: losses
:param reduction: reduce funtion
:return: loss
"""
reduction_function = F._Reduction.get_enum(reduction)
if reduction_function == 0:
return loss
elif reduction_function == 1:
return loss.mean()... | 2e0530b187dd1a59898eb347df7895a6454bbe96 | 3,614,244 |
def cek_filter(data, bound):
""" Check if convergence checks ceke and ceki are within bounds"""
ceke = ceke_filter(data, bound)
ceki = ceki_filter(data, bound)
cek = ceke & ceki
return cek | 2a8d2d8b34e54454c796d1cb50f35e6d75f36493 | 3,614,245 |
import logging
def load_model(dataset):
""" Builds/load a model appropriate for the dataset """
retinanet = RetinaNet(num_classes=dataset.get_num_classes()).train().cuda(DEVICE_IDX)
logging.info('Model loaded')
return retinanet | a20147018c32ba09fb262d1fd69ffa33a57045a1 | 3,614,246 |
def sample(ignition, connection, local_features_path=None):
"""
Pulls in dataframe of relevant observations and columns from PSQL.
Parameters
==========
ignition : yaml with all information necessary
connection : SQLConn connection class
local_features_path : str
Path to locally sto... | 15f0d555bea6b0963f547960beede6224fe7aced | 3,614,247 |
import json
def check_response(response):
"""Check the given HTTP response, returning the result if everything went
fine"""
code, body = response
if code != httplib.OK:
raise Exception('Received http response code %d' % (code))
data = json.loads(body)
if data['error']:
raise E... | a77b1c2e9c714341072c37e69e305529a0825241 | 3,614,248 |
def _strip_value(value, lookup='exact'):
"""
Helper function to remove the branch and version information from the given value,
which could be a single object or a list.
"""
if lookup == 'in':
stripped_value = [_strip_object(el) for el in value]
else:
stripped_value = _strip_obje... | 5dc8c1c02bba50d87bbd15dd89fd3be4ef499c7d | 3,614,249 |
def refactor_levels(
level: Level | list[Level] | None,
obj: Index,
) -> list[int]:
"""
Returns a consistent levels arg for use in ``hide_index`` or ``hide_columns``.
Parameters
----------
level : int, str, list
Original ``level`` arg supplied to above methods.
obj:
Eith... | 699cf16fd3036f6b669da2db758efcd21bdb5eca | 3,614,251 |
def compare_cards(card1, card2):
""" Compare the two given cards and return success if successful """
success = False
if card1.symbol == card2.symbol:
success = True # Success
return success | 27ee184305bd725af2dd1a4a3ef90ef72c815fbf | 3,614,252 |
def get_f_sw_C(washbowl_watersaving_C, Theta_wtr_d):
"""# 洗面水栓の水優先吐水機能における節湯の保温効果係数
Args:
washbowl_watersaving_C(bool): 洗面水栓の水優先吐水機能の有無
Theta_wtr_d(ndarray): 日平均給水温度 (℃)
Returns:
ndarray: 洗面水栓の水優先吐水機能における節湯の効果係数 (-)
"""
f_sw_C_d = np.ones(365)
if washbowl_watersaving_C:
... | 7c51b022c7b0ac3530b7fc2b351d2d9e83f09b5e | 3,614,253 |
def binary(f):
"""Wraps a function of any arity (including nullary) in a function that accepts
exactly 2 parameters. Any extraneous parameters will not be passed to the
supplied function"""
return n_ary(2, f) | 77d14cb4052c0faa1d0fc67e0462d275a0edd234 | 3,614,254 |
from typing import Tuple
def get_maxes_and_argmaxes(
data: jnp.array, labels: jnp.array, num_labels: int
) -> Tuple[jnp.ndarray, jnp.ndarray]:
"""
Given a flattened sequence of elements and their corresponding labels,
returns the maxes and argmaxes of each label.
Args:
data: Array of shap... | 9d6fc68e5034e7a89dd0eecf2649a43877a74322 | 3,614,256 |
import _uuid
def _uuid_inventory() -> str:
"""Create uuid for inventory."""
return _uuid() | 4acdb6825bba53804d8140f71175777ce0f89adc | 3,614,259 |
def local_overrides_git(install_req, existing_req):
"""Check whether we have a local directory and a Git URL
:param install_req: The requirement to install
:type install_req: pip.req.req_install.InstallRequirement
:param existing_req: An existing requirement or constraint
:type existing_req: pip.re... | 5c031506ddee4d05332421f8470026fbceb0978d | 3,614,260 |
def merge_same_price(df: pd.DataFrame, prec: float=5) -> pd.DataFrame:
"""
Process a collection of bids by merging in each
side (buying or selling) all players with the same
price into a new user with their aggregated quantity
Parameters
----------
df
Collection of bids to process
... | 4d8c841de3759ac3e5775296cbbb97c412d07b1f | 3,614,261 |
def normalize_latents(z, epsilon=1e-8):
"""Pixel norm implementation in NumPy."""
return z / np.sqrt(np.mean(np.square(z), axis=1, keepdims=True) + epsilon) | 39f19136176754824328f05f809e02c327b8efc6 | 3,614,262 |
def unite(iterable):
"""Turns a two dimensional array into a one dimensional."""
return list(chain.from_iterable(iterable)) | 10b4445d380061f23f71c66742d0c0312ebd3c97 | 3,614,265 |
import io
def s3_path_to_bytes_io(path):
"""
Example usage:
bytes_io = s3_path_to_bytes_io("s3://bucket/file.csv")
for line in bytes_io.readlines():
print(line.decode("utf-8"))
"""
bucket, key = s3_path_to_bucket_key(path)
obj = s3_client.get_object(Bucket=bucket, Key=key)
retu... | 9b20e8120781182519a486ec0bb9f3204758215a | 3,614,267 |
def posts_list(request):
"""Logic to handle requests and return responses."""
queryset = Post.objects.all()
context_data = {
"title": "Posts",
"object_list": queryset
}
return render(request, "posts_list.html", context_data)
#return HttpResponse("<h1>List<h1>") | 732dcf5f40f439271c4cfa4db0d5e7e1619bcf45 | 3,614,268 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.