content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def is_available():
"""Return true if a pdfjs installation is available."""
try:
get_pdfjs_res('build/pdf.js')
get_pdfjs_res('web/viewer.html')
except PDFJSNotFound:
return False
else:
return True | d345ca0b881ecc749fcea8ec4f579f9ba05f25c4 | 32,947 |
def reissueMissingJobs(updatedJobFiles, jobBatcher, batchSystem,
childJobFileToParentJob, childCounts, config,
killAfterNTimesMissing=3):
"""Check all the current job ids are in the list of currently running batch system jobs.
If a job is missing, we mark it as so, ... | 6ac051049f1e454fdc92a1a136ef4736e602d121 | 32,948 |
def all_children(wid):
"""Return all children of a widget."""
_list = wid.winfo_children()
for item in _list:
if item.winfo_children():
_list.extend(item.winfo_children())
return _list | ca52791b06db6f2dd1aeedc3656ecf08cb7de6d8 | 32,949 |
def logout():
"""------------- Log out -----------------------"""
# remove user session cookies
flash("You Have Been Logged Out")
session.pop("user")
return redirect(url_for("login")) | 66577a335a3e86c56c2aa78afacef4817786ac30 | 32,950 |
def listtodict(l: ty.Sequence) -> ty.Mapping:
"""Converts list to dictionary"""
return dict(zip(l[::2], l[1::2])) | 80e645c3b7834e4fd5980fdb3e5df75114e0da82 | 32,951 |
def sqrtspace(a, b, n_points):
"""
:return: Distribute n_points quadratically from point a to point b, inclusive
"""
return np.linspace(0, 1, n_points)**2*(b-a)+a | d88f3cd808dbab7447cf9609e3770a15e703e515 | 32,952 |
from datetime import datetime
def tstr2iso(input_string: str) -> datetime:
"""
Convert a specific type of ISO string that are compliant with file pathing requirement to ISO datetime.
:return:
"""
no_colon_input_string = input_string.replace(":", "")
iso_datetime = tstr2iso_nocolon(no_colon_inp... | bb591dceef294c36eb9c028b5e28979c37f05a16 | 32,953 |
def test_processing_hooks_are_inherited():
"""Processing hooks are inherited from base classes if missing.
"""
class TestView(DummyBase):
def __call__(self, *args, **kwargs):
return self.count
testview = create_view(TestView)
assert [testview(), testview(), testview()] == [2, 4, ... | 465303560f95c098c891361b504238dc4fe22adb | 32,954 |
def lesson(request, order, slug):
"""
One lesson can be viewed in two different ways:
(1) as independent lesson
(2) as part of one course
As (1) it is well, independent. And it is not really
important to jump to next in order lesson or not.
It is more important in this conetxt to d... | 7365179a033728f6208d26e666929f8b414c8d72 | 32,956 |
def _run_prospector(filename,
stamp_file_name,
disabled_linters,
show_lint_files):
"""Run prospector."""
linter_tools = [
"pep257",
"pep8",
"pyflakes"
]
if can_run_pylint():
linter_tools.append("pylint")
# ... | 393435da9d7d638be0e7461ec5251a1485649d7f | 32,958 |
def dEuler212(q, w):
"""
dEuler212(Q,W)
dq = dEuler212(Q,W) returns the (2-1-2) euler angle derivative
vector for a given (2-1-2) euler angle vector Q and body
angular velocity vector w.
dQ/dt = [B(Q)] w
"""
return np.dot(BmatEuler212(q), w) | 567a7a452c1e86a01854d63b0fd2efb0ea951fcd | 32,959 |
from typing import Callable
import functools
def with_zero_out_padding_outputs(
graph_net: Callable[[gn_graph.GraphsTuple], gn_graph.GraphsTuple]
) -> Callable[[gn_graph.GraphsTuple], gn_graph.GraphsTuple]:
"""A wrapper for graph to graph functions that zeroes padded d output values.
See `zero_out_padding` f... | 5f23defb49df229b2edec46f1f018a25401ca3f4 | 32,960 |
def as_bytes(x) -> bytes:
"""Convert a value to bytes by converting it to string and encoding in utf8."""
if _is_bytes(x):
return bytes(x)
if not isinstance(x, str):
x = str(x)
return x.encode('utf8') | 2c1c48bd1b02f290ec33dc427ebc4536ba2f2caf | 32,961 |
def getGeneCount(person, geneSetDictionary):
"""
determines how many genes a person is assumed to have based upon the query information provided
"""
if person in geneSetDictionary["no_genes"]:
gene_count = 0
elif person in geneSetDictionary["one_gene"]:
gene_count = 1
else:
... | 0fef236dd805ae77f04a22670752031af15ca5b2 | 32,962 |
import json
def merge_json(*args):
"""
Take a list of json files and merges them together
Input: list of json file
Output: dictionary of merged json
"""
json_out = dict()
for json_file in args:
try:
if isinstance(json_file, dict):
json_out = {**json_ou... | 37d5e29468d2de2aa11e5a92dc59b7b7b28a170d | 32,963 |
def get_KPP_PL_tag(last_tag, tag_prefix='T'):
""" Get the next P/L tag in a format T??? """
assert (len(last_tag) == 4), "Tag must be 4 characers long! (e.g. T???)"
last_tag_num = int(last_tag[1:])
return '{}{:0>3}'.format(tag_prefix, last_tag_num+1) | feb9cedce1fe4dd17aac3d28df25c951bb24cc3f | 32,965 |
from ibmsecurity.appliance.ibmappliance import IBMError
def update(isamAppliance, description, properties, check_mode=False, force=False):
"""
Update a specified Attribute Matcher
"""
id, update_required, json_data = _check(isamAppliance, description, properties)
if id is None:
raise IBMEr... | 2b7d90a15a65035aa623fc16dada0e76076221c1 | 32,966 |
def get_all_themes(config, brand_id):
"""
Get all themes for the given brand id.
:param config: context config
:param brand_id: the brand id for the relevant help center
:return list: list of all themes
"""
url = f"https://{config['subdomain']}.zendesk.com/api/guide/theming/{brand_id}/themes... | 54e846e8cfbafc418fae3b57818632d1ef8bbb42 | 32,968 |
import logging
def maximum_radius_test(gpu_memory=None, number_of_gpu=None):
"""
:return:
"""
if gpu_memory is None and number_of_gpu is None:
gpu_memory, number_of_gpu = tfu.client.read_gpu_memory()
logging.info('GPU Memory={:.2f} Number of GPU={}'.format(gpu_memory, number_of_gpu))
i... | a422dd94e8003e25a011ff6f604c20c6b75a203f | 32,969 |
def tca_plus(source, target):
"""
TCA: Transfer Component Analysis
:param source:
:param target:
:param n_rep: number of repeats
:return: result
"""
result = dict()
metric = 'process'
for src_name in source:
try:
stats = []
val = []
src... | 95242aa64db7b88a7f170abf619677c1d4acde57 | 32,971 |
def local_2d_self_attention_spatial_blocks(query_antecedent,
kv_channels,
heads,
memory_h_dim=None,
memory_w_dim=None,
... | 6295dff8753f4b577086fd414a386271ed6e1a1a | 32,972 |
def polling_locations_import_from_structured_json(structured_json):
"""
This pathway in requires a we_vote_id, and is not used when we import from Google Civic
:param structured_json:
:return:
"""
polling_location_manager = PollingLocationManager()
polling_locations_saved = 0
polling_loc... | 868062d4dac4a56073c832f7d2a2919a37a12203 | 32,973 |
def _mgSeqIdToTaxonId(seqId):
"""
Extracts a taxonId from sequence id used in the Amphora or Silva mg databases (ends with '|ncbid:taxonId")
@param seqId: sequence id used in mg databases
@return: taxonId
@rtype: int
"""
return int(seqId.rsplit('|', 1)[1].rsplit(':', 1)[... | 2ce74f453e3496c043a69b4205f258f06bfd0452 | 32,974 |
def has_progress(toppath):
"""Return `True` if there exist paths that have already been
imported under `toppath`.
"""
with progress_state() as state:
return len(state[toppath]) != 0 | 862c20336c7dd3b1b7d93022d4b633a9de89f336 | 32,975 |
def run_both_transfers(model: BiVAE, *args, **kwargs):
"""
Run both content-transfer and style-transfer on the each pair of the content-representative tensor images
:param model: Trained BiVAE model
:param class_reps: a dictionary of string class_id <-> a single 3dim Tensor (C,H,W)
:param log_dir: P... | 6d791931cda68b99701ccf407d78f1c470b124f0 | 32,976 |
def se_mobilenet_075():
"""
Construct SE_MobileNet.
"""
model = SE_MobileNet(widen_factor=0.75, num_classes=1000)
return model | 277d00141576f55dc6c41896725dcd2ee7c5a1d1 | 32,977 |
from pathlib import Path
def canonicalize_lookup_info(
lookup: SshPubKeyLookupInfo,
ssh_auth_dir_root: Path,
template_vars: SshPubKeyFileTemplateVars
) -> SshPubKeyLookupInfo:
"""Expand the template variables and ensure that paths are made absolute.
"""
ad_root = ssh_auth_dir_root
expd = e... | 24cb791ce5f0ea58daea268dc0e1804a3b056892 | 32,978 |
def reprojection_rms(impoints_known, impoints_reprojected):
"""
Compute root mean square (RMS) error of points
reprojection (cv2.projectPoints).
Both input NumPy arrays should be of shape (n_points, 2)
"""
diff = impoints_known - impoints_reprojected
squared_distances = np.sum(np.square(d... | 11bfbd994df21eb81581012313b838cf5e44424d | 32,979 |
import torch
def macro_accuracy_one_sub(**kwargs: dict) -> bool:
"""
Calculates whether the predicted output, after the postprocessing step of
selecting the single most 'changed' substation has been applied, wholly
matches the true output.
Differs from micro_accuracy_one_sub in that it doesn't che... | e21dcc6b2781abe9c7e5c0d03220d0624f68546c | 32,980 |
def modified_euler(f, y0, t0, t1, n):
""" Use the modified Euler method to compute an approximate solution
to the ODE y' = f(t, y) at n equispaced parameter values from t0 to t1
with initial conditions y(t0) = y0.
y0 is assumed to be either a constant or a one-dimensional numpy array.
t and t0 ... | c5549f194ee8fc446561967a49e89072abdad830 | 32,981 |
def read_tree(sha1=None, data=None):
"""Read tree object with given SHA-1 (hex string) or data, and return list
of (mode, path, sha1) tuples.
"""
if sha1 is not None:
obj_type, data = read_object(sha1)
assert obj_type == 'tree'
elif data is None:
raise TypeError('must specify... | 6d3fed787ba0e817ee67e9bfd99f5e2b6984684f | 32,982 |
def cluster(T, m):
"""
Runs PCCA++ [1] to compute a metastable decomposition of MSM states.
(i.e. find clusters using transition matrix and PCCA)
Parameters
----------
T: a probability transition matrix.
m : Desired number of metastable sets (int).
Notes
-----
The metastable de... | 7ba6f19d519d681b4b36c59409e617a9f1b385e5 | 32,983 |
def fine_tune_class_vector(nr_class, *, exclusive_classes=True, **cfg):
"""Select features from the class-vectors from the last hidden state,
softmax them, and then mean-pool them to produce one feature per vector.
The gradients of the class vectors are incremented in the backward pass,
to allow fine-tu... | 21359e128124f075ce4cf0768a24d1d5daaba4c2 | 32,984 |
def _recommend_aals_annoy(est, userid, R, n, filter_items,
recalculate_user, filter_previously_rated,
return_scores, recommend_function,
scaling_function, *args, **kwargs):
"""Produce recommendations for Annoy and NMS ALS algorithms"""
... | 76e258b64d080ef9804577c92bf41e4f4621f6c2 | 32,985 |
def url_to_filename(url):
"""Converts a URL to a valid filename."""
return url.replace('/', '_') | db3023c582590a47a6adc32501a2e3f5fd72f24f | 32,986 |
def _parallel_dict_from_expr_if_gens(exprs, opt):
"""Transform expressions into a multinomial form given generators."""
indices = {g: i for i, g in enumerate(opt.gens)}
zero_monom = [0]*len(opt.gens)
polys = []
for expr in exprs:
poly = {}
for term in Add.make_args(expr):
... | 81dec70ff041cb31062877e8b18823b8e4d283e0 | 32,987 |
def getMObjectHandle(value):
"""
Method used to get an MObjectHandle from any given value.
:type value: Union[str, om.MObject, om.MObjectHandle, om.MDagPath]
:rtype: om.MObjectHandle
"""
# Check for redundancy
#
if isinstance(value, om.MObjectHandle):
return value
else:
... | e41c7ccd48a5b8eb3b692730d4c6c8a74240f7dd | 32,988 |
def remove_dupes(inds1, inds2, inds3=None, inds4=None, tol=1e-6):
"""
Remove duplicates so as to not brake the interpolator.
Parameters
----------
inds1, inds2, inds3 : list or np.array()
to find unique values, must be same length
just_two : Bool [False]
do not include inds3
... | 6164e35d0b2c3b33d4e7a4f1737e356c096f2059 | 32,989 |
def filter_punctuation(fst: 'pynini.FstLike') -> 'pynini.FstLike':
"""
Helper function for parsing number strings. Converts common cardinal strings (groups of three digits delineated by 'cardinal_separator' - see graph_utils)
and converts to a string of digits:
"1 000" -> "1000"
"1.000.000" ... | 6e78d197fd4b05b66470622a0714bea0c4a935b4 | 32,990 |
def pixbuf2image(pix):
"""Convert gdkpixbuf to PIL image"""
data = pix.get_pixels()
w = pix.props.width
h = pix.props.height
stride = pix.props.rowstride
mode = "RGB"
if pix.props.has_alpha == True:
mode = "RGBA"
im = Image.frombytes(mode, (w, h), data, "raw", mode, stride)
r... | a44720fa3e40571d86e65b7f73cd660270919e67 | 32,991 |
def setup_s3_client(job_data):
"""Creates an S3 client
Uses the credentials passed in the event by CodePipeline. These
credentials can be used to access the artifact bucket.
Args:
job_data: The job data structure
Returns:
An S3 client with the appropriate credentia... | 98ff4d514734a5326dd709274bf0354e7d7cc255 | 32,992 |
import json
def unique_doc_key(doc):
"""
Creates a key that allows to check for record uniqueness
"""
keyparts = [doc['type']]
for attr in ('level', 'country', 'state', 'region', 'district', 'city'):
if attr in doc:
keyparts.append(doc[attr])
key = json.dumps(keyparts)
... | a2584c4628ffd4b0f433c2f85c8c4e7132ed05ea | 32,994 |
def parse_tag(vt):
"""
Get a VTag from a label
Parameters
----------
vt : str
A label that we want to get the VTag
Raises
------
UnknownTypeError
If the label is not known in VTag
"""
vt = vt.strip()
if vt == "C":
return TAG_CRITICAL
if vt == "L"... | ae551ca27f9c3cf542bf4c253c25731ffd8a6097 | 32,995 |
from datetime import datetime
import time
import random
def fetch_stock_revive_info(start_date: date = None, end_date: date = None, retry: int = 10) -> list:
"""
歷年上櫃減資資訊資料表
輸出格式: [{'code': '4153', 'name': '鈺緯', 'revive_date': date(2020-10-19), 'old_price': 27.20, 'new_price': 30.62}]
"""
result =... | 12e493accdcd8c6896e23a0c592c284c90e53de3 | 32,996 |
def _read_one(stream: BytesIO) -> int:
"""
Read 1 byte, converting it into an int
"""
c = stream.read(1)
if c == b"":
raise EOFError("Unexpected EOF while reading bytes")
return ord(c) | d3f8d22b2d2d3ff08cec42ffcf81cafe9192c707 | 32,997 |
def new_thread_mails(post, users_and_watches):
"""Return an interable of EmailMessages to send when a new thread is
created."""
c = {'post': post.content,
'post_html': post.content_parsed,
'author': post.creator.username,
'host': Site.objects.get_current().domain,
'thread... | 5a6e0bfbaf87f68d6010c84c0cb8c876042c0027 | 32,998 |
def known(words):
"""The subset of `words` that appear in the dictionary of WORDS."""
return set(w for w in words if w in WORDS) | c6665115d9cece679cef0cace8d4037aa4a8e47c | 32,999 |
import pprint
def load_transform_data(human_dataset, bot_dataset, drop_features, bins, logger, **kwargs):
"""
Load and preprocess data, returning the examples and labels as numpy.
"""
# Load data for humans.
df1 = pd.read_csv(human_dataset)
df1 = df1.drop("screen_name", axis=1) # remove scree... | 666b9161f1309f3e9765a123773318f55b9f6662 | 33,000 |
def latest():
"""
Latest route returns latest performed searches.
"""
return jsonify(get_latest_searches()) | a9cc69921566ecb9f97eab008ffc8f7fea167273 | 33,001 |
def actions(board):
"""
Returns set of all possible actions (i, j) available on the board.
"""
PossActions = []
# Find empty positions
for i in range(3):
for j in range(3):
if(board[i][j] == EMPTY):
PossActions.append((i,j))
return Po... | 51f8b37c7b50b655c33a9ea73ded5e175c21670c | 33,003 |
import re
import json
def getCity(html):
"""This function uses the ``html`` passed to it as a string to extract, parse and return a City object
Parameters
----------
html : str
the html returned when a get request to view the city is made. This request can be made with the following statement: ``s.get(urlCiudad... | 77af6a1c49f254f08ab226138b9a5ddc4abbc9b3 | 33,004 |
def server_hostname(config):
"""
Reads the ambari server name from the config or using the supplied script
"""
global cached_server_hostname
if cached_server_hostname is not None:
return cached_server_hostname
if config.has_option('server', 'hostname_script'):
scriptname = config.get('server', 'hos... | bb6f0311566d47b32be855bcd33964b28425143e | 33,005 |
from typing import Callable
import json
from pathlib import Path
import types
def cache_instance(get_instance_fn: Callable[..., data.TrainingInstance] = None, *, cache_dir, **instance_config):
"""Decorator to automatically cache training instances."""
if get_instance_fn is None:
return partial(cache_... | 50bab385439550eca541f4d18915c031c41a8107 | 33,006 |
def get_definitions_query_filter(request_args):
""" Get query_filter for alert_alarm_definition list route.
"""
query_filters = None
display_retired = False
valid_args = ['array_name', 'platform_name', 'instrument_name', 'reference_designator']
# Process request arguments
if 'retired' in req... | a087cbd9ca6ffe9b38afc2d8802c12e4dfd47e50 | 33,007 |
import io
def _read_dictionary_page(file_obj, schema_helper, page_header, column_metadata):
"""Read a page containing dictionary data.
Consumes data using the plain encoding and returns an array of values.
"""
raw_bytes = _read_page(file_obj, page_header, column_metadata)
io_obj = io.BytesIO(raw_b... | f4c0bf36b23238f79bfcc11821e47f88186524e0 | 33,008 |
def num_songs(t):
"""Return the number of songs in the pyTunes tree, t.
>>> pytunes = make_pytunes('i_love_music')
>>> num_songs(pytunes)
3
"""
"*** YOUR CODE HERE ***"
if is_leaf(t):
return 1
else:
sum_songs = 0
for subt in branches(t):
sum_songs += ... | ffba78cccbd98963daa6c1ba29650c624fdba29f | 33,009 |
def _get_parameter_value(potential: Potential, handler: str, parameter: str) -> float:
"""Returns the value of a parameter in its default units"""
return (
potential.parameters[parameter].to(_DEFAULT_UNITS[handler][parameter]).magnitude
) | 2fef58b3018737975e96deb4d58d54f55407c624 | 33,010 |
def triplets_in_range(mini, maxi):
"""
Finds all the triplets in a given range that meet the condition a ** 2 + b ** 2 = c ** 2
>>> triplets_in_range(2, 10)
{(3, 4, 5), (6, 8, 10)}
:param mini: The minimum in the range
:param maxi: Maximum in the rnage
:return: a set of tuples (with length... | 1dbe7c64d483d87b2eab1f652a77e346f0ffefec | 33,011 |
import re
def targetInCol(df, target):
"""
Return meta information (Line or Area) from information in a column of DF.
Arguments:
doc -- csv Promax geometry file
target -- meta information to get (Line or Area)
"""
c = list(df.columns)
ptarget = r''+re.escape(target)
i = [i for i, ... | 5d40cf251bd2a7593a46a5b63b5de3a56f8cec29 | 33,012 |
def default_monitor(verbose=1):
"""Returns very simple monitor object to summarize training progress.
Args:
verbose: Level of verbosity of output.
Returns:
Default monitor object.
"""
return BaseMonitor(verbose=verbose) | fbc5494d2545439daaeb12a4d3215295226b064e | 33,013 |
def pca(X, k = 30, optim = "fastest"):
"""Use PCA to project X to k dimensions."""
# Center/scale the data.
s = np.std(X, axis=0)
s = np.where(s==0, 1, s)
X = (X - np.mean(X, axis=0))/s
if optim == "none":
# Compute covariance eigenvectors with numpy.
#
# T... | 2e5e9b82ec770aa1cda80519f7d392d68c6949a6 | 33,014 |
def get_range(a_list):
"""
=================================================================================================
get_range(a_list)
This is meant to find the maximal span of a list of values.
=======================================================================================... | 36e0cc78d2f45b25af56c1af51292f00c2f2623b | 33,015 |
def create_config(solution, nodes, description_info):
"""Creates compact string representing input data file
Parameters:
solution (list) List of solutions
nodes (list) List of node specification
description_info (tuple) CSP description in form of tuple: (algorithm name, domains, constrai... | 3ccf76ca36b92ceb698aafea43414fe014258b0e | 33,016 |
def get_effective_option(metadata, settings, key):
"""
Return option with highest priority:
not-defined key < default < pelican config settings < file metadata
"""
return metadata.get(key, settings[DP_KEY].get(key)) | 4b617bd9c7fb0f0533014fae0533c0500f64c9bb | 33,017 |
def positions_sync_out_doc_view(request):
"""
Show documentation about positionsSyncOut
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = positions_sync_out_doc.positions_sync_out_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
r... | f775b6eddf1419a781e7a43d047f288c56566b3b | 33,018 |
import gettext
def __build_caj_q_html_view__(data: object) -> any:
"""
popup's table for Caju Quality Information
"""
satellite_est = gettext("Satellite Estimation")
tns_survey = gettext("TNS Survey")
nut_count_average = gettext("Nut Count Average")
defective_rate_average = gettext("Defec... | a4442f4ba486991ea3b1c75168f8ba921d9459c7 | 33,019 |
def code(email):
"""
Returns the one-time password associated with the given user for the
current time window. Returns empty string if user is not found.
"""
print("route=/code/<email> : email:", email)
u = User.get_user(email)
if u is None:
print("user not found, returning ''")
... | 4479f6af448f6c91ab6d1c563d6baa94542826a3 | 33,020 |
def blend_image_with_masks(image, masks, colors, alpha=0.5):
"""Add transparent colored mask to an image.
Args:
image: `np.ndarray`, the image of shape (width, height, channel) or (width, height).
masks: `np.ndarray`, the mask of shape (n, width, height).
colors: list, a list of RGB colors (from ... | 9a733d9a6721c2139a64e2e718c4bb5648dbb759 | 33,021 |
import functools
def get_trainee_and_group(func):
"""Decorator to insert trainee and group as arguments to the given function.
Creates new Trainee if did not exist in DB.
Creates new Group if did not exist in DB.
Adds the trainee to the group if it was not part of it.
Appends the trainee and grou... | 76fb80e90b36c0264e50510c7226587a131095f5 | 33,022 |
def generate_chromatogram(
ms_data: dict,
chromatogram: str,
ms_level: int = 1
) -> list:
"""
Generates a either a Base Peak Chromatogram (BPC) or Total Ion Chromatogram
(TIC) from ripper data.
Args:
ms_data (dict): mzml ripper data in standard ripper format.
chromatogram (s... | 901ab7c350ccb00ee277ec96c7496675274ac0f1 | 33,024 |
def get_tensor_batch_size(values):
"""Extracts batch size from tensor"""
return tf.gather(params=tf.shape(input=values), indices=tf.constant([0])) | c1a7d0cb789526310c332d1e2a24697d1357ceb5 | 33,025 |
def generate_particle_timestamp(time_2000):
"""
This function calculates and returns a timestamp in epoch 1900
based on an ASCII hex time in epoch 2000.
Parameter:
time_2000 - number of seconds since Jan 1, 2000
Returns:
number of seconds since Jan 1, 1900
"""
return int(time_200... | 9c05fc809953e371b756a389d98f3a74c1ea5975 | 33,026 |
def clip_histogram(hist, clip_limit):
"""Perform clipping of the histogram and redistribution of bins.
The histogram is clipped and the number of excess pixels is counted.
Afterwards the excess pixels are equally redistributed across the
whole histogram (providing the bin count is smaller than the clipl... | 0947568a36024dfdfd9fc37385676e924aedb603 | 33,027 |
from typing import Iterable
from typing import Callable
from typing import Tuple
def aggregate_precision_recall(
labels_pred_iterable: Iterable,
precision_recall_fn: Callable = buffered_precision_recall,
) -> Tuple[float, float]:
"""
Computes aggregate range-based precision recall metrics for the give... | d777832230ae84ff86c0ad60dced8a1c007ed90f | 33,028 |
def find_tag_for(t):
"""If transaction matches a rule, returns corresponding tuple
(tag, ruler, match).
"""
res = []
for (tag, rulers) in list(TAGS.items()):
for ruler in rulers:
m, matches = match(ruler, t)
if m:
res.append((tag, ruler, matches))
... | 1b0afd086f428606dfc993d61a0753da98ea176d | 33,029 |
from typing import Union
from typing import Dict
from typing import Any
import typing
def DOMWidget(
layout: Union[Dict[str, Any], Element[ipywidgets.widgets.widget_layout.Layout]] = {},
on_layout: typing.Callable[[Union[Dict[str, Any], Element[ipywidgets.widgets.widget_layout.Layout]]], Any] = None,
) -> Ele... | cee1f61b5eb57582fae65e28ca8823d13bcdff51 | 33,030 |
def load(path, element_spec=None, compression=None, reader_func=None):
"""Loads a previously saved dataset.
Example usage:
>>> import tempfile
>>> path = os.path.join(tempfile.gettempdir(), "saved_data")
>>> # Save a dataset
>>> dataset = tf.data.Dataset.range(2)
>>> tf.data.experimental.save(dataset, p... | d3ec8a97cab7897658758f42486e6f4f3b605e6d | 33,031 |
def test_confusion_PRFAS():
"""
Line=True class, column=Prediction
TR_B [[1585 109 4]
TR_I [ 126 1233 17]
TR_O [ 20 12 82]]
(unweighted) Accuracy score = 90.97 % trace=2900 sum=3188
precision recall f1-score support
TR_B 0.916 0.933 0.924 1698
... | 257736819e3dd6a1c4f2644a15bc74cde2f4c49b | 33,032 |
def wrap(x, m, M):
"""
:param x: a scalar
:param m: minimum possible value in range
:param M: maximum possible value in range
Wraps ``x`` so m <= x <= M; but unlike ``bound()`` which
truncates, ``wrap()`` wraps x around the coordinate system defined by m,M.\n
For example, m = -180, M = 180 (... | 274017550a39a79daacdcc96c76c09116093f47a | 33,033 |
from typing import Iterable
from typing import List
from typing import Any
import click
from typing import cast
from typing import Callable
def execute_processors(processors: Iterable[ProcessorType], state: State) -> None:
"""Execute a sequence of processors to generate a Document structure. For block handling,
... | 4af44e41c02184286c4c038143e1461d8fbe044d | 33,034 |
def date(repo, subset, x):
"""Changesets within the interval, see :hg:`help dates`.
"""
# i18n: "date" is a keyword
ds = getstring(x, _("date requires a string"))
dm = util.matchdate(ds)
return subset.filter(lambda x: dm(repo[x].date()[0]),
condrepr=('<date %r>', ds)) | 91d6cea81861791daed3220bc03e3002a47a959d | 33,035 |
def addAuthor(author):
"""
Creates an Author dictionary
:param author: Author instance
:return: Dict
"""
author_dict = dict()
# author_dict['id'] = "{}/api/{}".format(DOMAIN, author.id)
author_dict['id'] = "{}/api/author/{}".format(DOMAIN, author.id)
author_dict['host'] = "{}/api/".... | f6b35909e223987eb37178d1f6722eaffacc94cd | 33,036 |
def add_transformer_enc_hyperparams_args(parser):
"""Only applicable when args.model_name is 'transformer_enc'"""
parser.add_argument('--hid_dim', type=int, default=128)
parser.add_argument('--num_enc_layers', type=int, default=3)
parser.add_argument('--num_enc_heads', type=int, default=8)
parser.ad... | bc38c3cc1d9fc7e87cebfbf7bdc74f8e9d0a124e | 33,037 |
def make_length(value):
""" Make a kicad length measurement from an openjson measurement """
return int(round(float(value) * MULT)) | 1fe311b94eaaf123f7a028d3a06232185903179d | 33,038 |
def with_metaclass(meta, *bases):
"""copied from https://github.com/Byron/bcore/blob/master/src/python/butility/future.py#L15"""
class metaclass(meta):
__call__ = type.__call__
__init__ = type.__init__
def __new__(cls, name, nbases, d):
if nbases is None:
ret... | e0d9c4d580125cc60ab8319cc9a2ca918ef40291 | 33,040 |
import math
def calc_mupen_res(N,region_w,region_h):
"""find res to fit N mupen instances in region"""
results = []
for row_length in range(1,N+1):
col_length = math.ceil(N/float(row_length))
instance_width = int(math.floor( min(640, region_w/float(row_length) )))
instance_height = int(math.floor(... | 35b5e739102097d856b7c2e154516d4e866a1567 | 33,041 |
from typing import List
def pos_tag_wordnet(text: List) -> List:
"""Create pos_tag with wordnet format
:rtype: object
:param (List) text: string to be nltk_pos_tagged for syntactic similar synonyms
:return (List[List[str, 'pos_tag']]) tagged_text: str values with according nltk_pos_tag
... | 7da0081c37064678ce70590cecc313ee6ec60673 | 33,042 |
def create_app():
"""
Create an app with config file
:return: Flask App
"""
# init a flask app
app = Flask(__name__)
# 从yaml文件中加载配置,此加载方式有效加载
# 初始化APP
_config_app(app)
# 允许跨域请求
if app.config.get('CORS_ENABLE'):
CORS(app)
# 配置蓝图
configure_blueprints(app)
... | 74d7e7beab4e86faec1fbf8dc357791ac50874dd | 33,043 |
import json
def img_to_json(img, decimals=2, swap=False, save=None):
""" Convert an image volume to web-ready JSON format suitable for import into
the Neurosynth viewer.
Args:
img: An image filename.
round: Optional integer giving number of decimals to round values to.
swap: A temporary... | 18e1d92d73493e69efaf055616ccb2f5d55fc835 | 33,044 |
import ctypes
import typing
import array
def encode_float(
encoder_state: ctypes.Structure,
pcm_data: bytes,
frame_size: int,
max_data_bytes: int
) -> typing.Union[bytes, typing.Any]:
"""Encodes an Opus frame from floating point input"""
pcm_pointer = ctypes.cast(pcm_data, opus... | fc349b4eae1c330444114b3df86f1603c931a30a | 33,045 |
from datetime import datetime
def _login(use_cookie):
"""User login helper function.
The request data should contain at least 'email' and 'password'.
The cookie expiration duration is defined in flask app config.
If user is not authenticated, it raises Unauthorized exception.
"""
data = _get_... | 084238d593b95901fcb260088f730fd7e9ac3f64 | 33,046 |
def get_highlightjs_setting(setting, default=None):
"""
Read a setting
"""
return HIGHLIGHTJS.get(setting, default) | 86b3b52fc7e95448a2ce6e860d4b261d78d68a38 | 33,049 |
def package_dir_path(path):
"""Return package path to package install directory"""
return path + '/.pkg' | edd4b97256ccf02a3f1165b99cae746826e8aee0 | 33,051 |
def sort_cluster_data(cluster_data, cluster_accuracy):
"""
sort cluster data based on GDT_mean values of cluster_accuracy.
-> cluster 0 will have highest GDT_mean
-> cluster <max> will have lowest GDT_mean
.. Note :: if cluster_data has noise_label assigned, will move this label to the end of t... | 964e9a646da025ae6819bc902319f7f1b6c9ae9c | 33,052 |
import random
def reprintClean(pack):
"""
Helper function specifically for reprint packs.
:param pack: List, contains the 12 cards in a pack
:return: temppack, the pack with the higher rarity cards implanted in
"""
temppack = pack
rarity = random.randint(0, 12)
if rarity == 0:
... | 3b73ab930197e482699b340b4cb9c0f068e63985 | 33,053 |
def logout():
"""Logs the current user out"""
del session['user_id']
return redirect('/') | 7584ceceb2f6afa95a82d212ca4b9b537a1d4ad2 | 33,054 |
def main() -> int:
"""
Main function. Executed if script is called standalone.
"""
args = _parse_cmd_args()
try:
return _search_symantec(args.keyword, args.limit)
except KeyboardInterrupt:
_warn("Keyboard interrupt detected\n", True)
return 1 | b8f06d95ab08ca25b55a8f0256ac51902383dfe0 | 33,055 |
def _check_imgs_array(imgs):
"""Check input image if it is an array
Parameters
----------
imgs : array of str, shape=[n_subjects, n_sessions]
Element i, j of the array is a path to the data of subject i
collected during session j.
Data are loaded with numpy.load and ... | 43705a4467a27df3027d9ebed4b8f5eec2866916 | 33,056 |
def smoothline(xs, ys=None, interpol=3, window=1, verbose=3):
"""Smoothing 1D vector.
Description
-----------
Smoothing a 1d vector can be challanging if the number of data is low sampled.
This smoothing function therefore contains two steps. First interpolation of the
input line followed ... | 7e7d50e55f801a14394dc2c9fab4e8f392dee546 | 33,057 |
def prune_model(keras_model, prun_factor_dense=10, prun_factor_conv=10, metric='L1', comp=None, num_classes=None, label_one_hot=None):
"""
A given keras model get pruned. The factor for dense and conv says how many percent
of the dense and conv layers should be deleted.
Args:
keras_model: ... | 90e01b5e1de4acc4649f48f0931f8db5cdc6867c | 33,058 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.