content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def collect_subclasses(mod, cls, exclude=None):
"""Collecting all subclasses of `cls` in the module `mod`
@param mod: `ModuleType` The module to collect from.
@param cls: `type` or (`list` of `type`) The parent class(es).
@keyword exclude: (`list` of `type`) Classes to not include.
"""
out = []... | 30e64b93fca4d68c3621cae54bb256350875eb77 | 19,000 |
import typing
from typing import Counter
def check_collections_equivalent(a: typing.Collection, b: typing.Collection,
allow_duplicates: bool = False,
element_converter: typing.Callable = identity) -> typing.Tuple[str, list]:
"""
:param a: one ... | 61d78f522a6e87927db6b32b46637f0bb6a10513 | 19,001 |
def voting_classifier(*args, **kwargs):
"""
same as in gradient_boosting_from_scratch()
"""
return VotingClassifier(*args, **kwargs) | ed92138c23b699672197d1b436773a5250685250 | 19,002 |
import re
def replace_subject_with_object(sent, sub, obj):
"""Replace the subject with object and remove the original subject"""
sent = re.sub(r'{}'.format(obj), r'', sent, re.IGNORECASE)
sent = re.sub(r'{}'.format(sub), r'{} '.format(obj), sent, re.IGNORECASE)
return re.sub(r'{\s{2,}', r' ', sent, re... | 1c7f8115968c4e4ef10dcc3b83f0f259433f5082 | 19,003 |
def estimate_using_user_recent(list_type: str, username: str) -> int:
"""
Estimate the page number of a missing (entry which was just approved) entry
and choose the max page number
this requests a recent user's list, and uses checks if there are any
ids in that list which arent in the approved cach... | b6a7a5bf6c0fa6e13021f10bf2fe613c4186f430 | 19,004 |
def codegen_reload_data():
"""Parameters to codegen used to generate the fn_html2pdf package"""
reload_params = {"package": u"fn_html2pdf",
"incident_fields": [],
"action_fields": [],
"function_params": [u"html2pdf_data", u"html2pdf_data_type", u"htm... | 45a5e974f3e02953a6d121e37c05022c448adae6 | 19,005 |
def instrument_keywords(instrument, caom=False):
"""Get the keywords for a given instrument service
Parameters
----------
instrument: str
The instrument name, i.e. one of ['niriss','nircam','nirspec',
'miri','fgs']
caom: bool
Query CAOM service
Returns
-------
p... | 271f58615dbdbcde4fda9a5248d8ae3b40b90f6d | 19,006 |
from struct import unpack
from time import mktime, strftime, gmtime
def header_info(data_type, payload):
"""Report additional non-payload in network binary data.
These can be status, time, grapic or control structures"""
# Structures are defined in db_access.h.
if payload == None:
return ""
... | 6e83be0dff2d7f81a99419baf505e82957518c64 | 19,007 |
def dsa_verify(message, public, signature, constants=None):
"""Checks if the signature (r, s) is correct"""
r, s = signature
p, q, g = get_dsa_constants(constants)
if r <= 0 or r >= q or s <= 0 or s >= q:
return False
w = inverse_mod(s, q)
u1 = (bytes_to_num(sha1_hash(message)) * w) % q... | 9d6eeb9b5b2d84edd054cba01bdd47cb9bab120e | 19,008 |
def set_up_cgi():
"""
Return a configured instance of the CGI simulator on RST.
Sets up the Lyot stop and filter from the configfile, turns off science instrument (SI) internal WFE, and reads
the FPM setting from the configfile.
:return: CGI instrument instance
"""
webbpsf.setup_logging('ER... | 68559e88b9cebb5e2edb049f63d80c9545112804 | 19,009 |
def plot_line(
timstof_data, # alphatims.bruker.TimsTOF object
selected_indices: np.ndarray,
x_axis_label: str,
colorscale_qualitative: str,
title: str = "",
y_axis_label: str = "intensity",
remove_zeros: bool = False,
trim: bool = True,
height: int = 400
) -> go.Figure:
"""Plot... | 5db0468710e49158c4b13fc56446a23949544e57 | 19,010 |
def all_gather(data):
"""
Run all_gather on arbitrary picklable data (not necessarily tensors)
Args:
data: any picklable object
Returns:
list[data]: list of data gathered from each rank
"""
world_size = get_world_size()
if world_size == 1:
return [data]
data_list ... | 46f34975d89766c842b6c20e312ad3dea4f3d7ff | 19,011 |
import sys
def get_title_count(titles, is_folder):
""" Gets the final title count """
final_title_count = 0
if len(titles.all) == 0:
if is_folder == False:
sys.exit()
else:
return 0
else:
for group, disc_titles in titles.all.items():
for titl... | bdd239698f98c845cbecb27924725c38257547b6 | 19,012 |
from ..utils import check_adata
def draw_graph(
adata,
layout=None,
color=None,
alpha=None,
groups=None,
components=None,
legend_loc='right margin',
legend_fontsize=None,
legend_fontweight=None,
color_map=None,
palette=None,
... | 006121b0162afcf6b91703dac8c1ea3e6d1351bc | 19,013 |
def post_token():
"""
Receives authentication credentials in order to generate an access
token to be used to access protected models. Tokens generated
by this endpoint are JWT Tokens.
"""
# First we verify the request is an actual json request. If not, then we
# responded with ... | d51de9aa201fdb0d879190c5f08352b43f425be4 | 19,014 |
def judgement(seed_a, seed_b):
"""Return amount of times last 16 binary digits of generators match."""
sample = 0
count = 0
while sample <= 40000000:
new_a = seed_a * 16807 % 2147483647
new_b = seed_b * 48271 % 2147483647
bin_a = bin(new_a)
bin_b = bin(new_b)
la... | 9d778909ba6b04e4ca3adbb542fce9ef89d7b2b7 | 19,015 |
def GJK(shape1, shape2):
""" Implementation of the GJK algorithm
PARAMETERS
----------
shape{1, 2}: Shape
RETURN
------
: bool
Signifies if the given shapes intersect or not.
"""
# Initialize algorithm parameters
direction = Vec(shape1.center, shape2.center).direct... | 4e3b24ec9fab1d2625c3d99ae3ffc2325c1dcaf8 | 19,016 |
def _set_int_config_parameter(value: OZWValue, new_value: int) -> int:
"""Set a ValueType.INT config parameter."""
try:
new_value = int(new_value)
except ValueError as err:
raise WrongTypeError(
(
f"Configuration parameter type {value.type} does not match "
... | e9e168aa1959dfab141622a0d0f3751a1e042dfd | 19,017 |
def split_dataset(dataset_file, trainpct):
"""
Split a file containing the full path to individual annotation files into
train and test datasets, with a split defined by trainpct.
Inputs:
- dataset_file - a .txt or .csv file containing file paths pointing to annotation files.
(Expects that t... | 0f24d29efdf3645a743bbb6d9e2e27b9087552be | 19,018 |
def accession(data):
"""
Get the accession for the given data.
"""
return data["mgi_marker_accession_id"] | 132dcbdd0712ae30ce7929e58c4bc8cdf73aacb2 | 19,019 |
def get_phase_dir(self):
"""Get the phase rotating direction of stator flux stored in LUT
Parameters
----------
self : LUT
a LUT object
Returns
----------
phase_dir : int
rotating direction of phases +/-1
"""
if self.phase_dir not in [-1, 1]:
# recalculate ... | e335f78d6219f0db5a390cf47aaa7aa093f7c329 | 19,020 |
def atomic_number(request):
"""
An atomic number.
"""
return request.param | 6f1a868c94d0a1ee4c84a76f04b4cabc3e0356e0 | 19,021 |
def plot_metric(title = 'Plot of registration metric vs iterations'):
"""Plots the mutual information over registration iterations
Parameters
----------
title : str
Returns
-------
fig : matplotlib figure
"""
global metric_values, multires_iterations
fig, ax = plt.... | 488d96876a469522263f6c7118b94b35a25e36de | 19,022 |
from re import T
def cross_entropy(model, _input, _target):
""" Compute Cross Entropy between target and output diversity.
Parameters
----------
model : Model
Model for generating output for compare with target sample.
_input : theano.tensor.matrix
Input sample.
_target : th... | c65efe3185269d8f7132e23abbd517ca9273d481 | 19,023 |
def paste():
"""Paste and redirect."""
text = request.form['text']
# TODO: make this better
assert 0 <= len(text) <= ONE_MB, len(text)
with UploadedFile.from_text(text) as uf:
get_backend().store_object(uf)
lang = request.form['language']
if lang != 'rendered-markdown':
wi... | 079b9ccda1cd652034ea0f0c2f83e115ecd5f8a4 | 19,024 |
def get_groups_links(groups, tenant_id, rel='self', limit=None, marker=None):
"""
Get the links to groups along with 'next' link
"""
url = get_autoscale_links(tenant_id, format=None)
return get_collection_links(groups, url, rel, limit, marker) | 35188c3c6d01026153a6e18365ae0b4b596a8883 | 19,025 |
def over(expr: ir.ValueExpr, window: win.Window) -> ir.ValueExpr:
"""Construct a window expression.
Parameters
----------
expr
A value expression
window
Window specification
Returns
-------
ValueExpr
A window function expression
See Also
--------
ib... | e9c8f656403520d5f3287de38c139b8fd8446d13 | 19,026 |
def node_value(node: Node) -> int:
"""
Computes the value of node
"""
if not node.children:
return sum(node.entries)
else:
value = 0
for entry in node.entries:
try:
# Entries start at 1 so subtract all entries by 1
value += node_val... | c22ac3f73995e138f7eb329499caba3fc67175a5 | 19,027 |
import re
def load_mac_vendors() :
""" parses wireshark mac address db and returns dict of mac : vendor """
entries = {}
f = open('mac_vendors.db', 'r')
for lines in f.readlines() :
entry = lines.split()
# match on first column being first six bytes
r = re.compile(r'^([0-9A-F]{... | 361e9c79de8b473c8757ae63384926d266b68bbf | 19,028 |
def parse_time(s):
"""
Parse time spec with optional s/m/h/d/w suffix
"""
if s[-1].lower() in secs:
return int(s[:-1]) * secs[s[-1].lower()]
else:
return int(s) | 213c601143e57b5fe6cd123631c6cd562f2947e9 | 19,029 |
def resize_labels(labels, size):
"""Helper function to resize labels.
Args:
labels: A long tensor of shape `[batch_size, height, width]`.
Returns:
A long tensor of shape `[batch_size, new_height, new_width]`.
"""
n, h, w = labels.shape
labels = F.interpolate(labels.view(n, 1, h, w).float(),
... | 87c7127643e9e46878bc526ebed4068d40f25ece | 19,030 |
import re
def _extract_urls(html):
"""
Try to find all embedded links, whether external or internal
"""
# substitute real html symbols
html = _replace_ampersands(html)
urls = set()
hrefrx = re.compile("""href\s*\=\s*['"](.*?)['"]""")
for url in re.findall(hrefrx, html):
urls.... | 5303cf7b750926aa5919bbfa839bd227319aa9f7 | 19,031 |
def reorganize_data(texts):
"""
Reorganize data to contain tuples of a all signs combined and all trans combined
:param texts: sentences in format of tuples of (sign, tran)
:return: data reorganized
"""
data = []
for sentence in texts:
signs = []
trans = []
for sign,... | 27b4efd99bbf470a9f8f46ab3e34c93c606d0234 | 19,032 |
def client_new():
"""Create new client."""
form = ClientForm(request.form)
if form.validate_on_submit():
c = Client(user_id=current_user.get_id())
c.gen_salt()
form.populate_obj(c)
db.session.add(c)
db.session.commit()
return redirect(url_for('.client_view', ... | b355f43cd80e0f7fef3027f5f1d1832c4e4ece5a | 19,033 |
def query_schema_existence(conn, schema_name):
"""Function to verify whether the current database schema ownership is correct."""
with conn.cursor() as cur:
cur.execute('SELECT EXISTS(SELECT 1 FROM information_schema.schemata WHERE SCHEMA_NAME = %s)',
[schema_name])
return cu... | 9c556283d255f580fc69a9e41a4d452d15e1eb17 | 19,034 |
def get_number_of_params(model, trainable_only=False):
"""
Get the number of parameters in a PyTorch Model
:param model(torch.nn.Model):
:param trainable_only(bool): If True, only count the trainable parameters
:return(int): The number of parameters in the model
"""
return int(np.sum([np.pro... | 4e02e977e9fc2949a62ce433c9ff6d732d74a746 | 19,035 |
import time
import requests
def chart1(request):
"""
This view tests the server speed for transferring JSON and XML objects.
:param request: The AJAX request
:return: JsonResponse of the dataset.
"""
full_url = HttpRequest.build_absolute_uri(request)
relative = HttpRequest.get_full_path(... | 6eb88d3ef1aed85799832d5751ec4e30c54aaa07 | 19,036 |
def conv3x3(in_planes, out_planes, stride=1, dilation=1):
"""3x3 convolution with padding"""
return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride,
padding=dilation, bias=False) | 115dd9e8afdaa850293fa08c103ab2966eceedbf | 19,037 |
import mimetypes
def img_mime_type(img):
"""Returns image MIME type or ``None``.
Parameters
----------
img: `PIL.Image`
PIL Image object.
Returns
-------
mime_type : `str`
MIME string like "image/jpg" or ``None``.
"""
if img.format:
ext = "." + img.format
... | fe46af6e5c03a1ae80cb809c81ab358ac5c085fa | 19,038 |
import logging
def set_log_level(verbose, match=None, return_old=False):
"""Convenience function for setting the logging level
Parameters
----------
verbose : bool, str, int, or None
The verbosity of messages to print. If a str, it can be either DEBUG,
INFO, WARNING, ERROR, or CRITICA... | 62fbf9ad0639625073e6aff23f93389b1b0be24e | 19,039 |
def check_satisfy_dataset(w, D, involved_predicates=[]):
"""
This function is to check whether all facts in ``D'' have been installed in each of ruler intervals
of the given Window ``w'' if facts in ruler intervals holds in ``D''.
Args:
w (a Window instance):
D (dictionary of dictionary ... | b2715ca1eba03bbcf0581fdfeb97177cde8d12d7 | 19,040 |
def interp_at(d, g, varargs=None, dim=None, dask="parallelized"):
"""
Interpolates a variable to another.
Example : varargs = [THETA, mld] : THETA(t, z, y, x) is interpolated with Z=mld(t, y, x)
"""
var, coordvar = varargs
dim = (
dim if dim is not None else set(d[var].dims).difference(d... | a31cccee447deb2fd2612460471598d74e347c53 | 19,041 |
def get_history():
"""Get command usage history from History.sublime-project"""
f = open('%s/%s/%s' % (sublime.packages_path(),
"TextTransmute",
"History.sublime-project"), 'r')
content = f.readlines()
f.close()
return [x.strip() for x in conten... | fab11f52c2b90d1fb29ace944c8f80f67fc9170e | 19,042 |
from typing import Dict
from typing import Callable
from typing import Any
import asyncio
def inprogress(metric: Gauge, labels: Dict[str, str] = None) -> Callable[..., Any]:
"""
This decorator provides a convenient way to track in-progress requests
(or other things) in a callable.
This decorator func... | c10adbb07796c26fd59d1038a786b25b6346fd97 | 19,043 |
from typing import Optional
import base64
def b58_wrapper_to_b64_public_address(b58_string: str) -> Optional[str]:
"""Convert a b58-encoded PrintableWrapper address into a b64-encoded PublicAddress protobuf"""
wrapper = b58_wrapper_to_protobuf(b58_string)
if wrapper:
public_address = wrapper.publi... | a4c46800c0d22ef96d3fa622b6a37bf55e1960da | 19,044 |
def render_to_AJAX(status, messages):
"""return an HTTP response for an AJAX request"""
xmlc = Context({'status': status,
'messages': messages})
xmlt = loader.get_template("AJAXresponse.xml")
response = xmlt.render(xmlc)
return HttpResponse(response) | cb5ad3ead4d5bee9a710767d1f49c81b2b137441 | 19,045 |
def parse_params(environ, *include):
"""Parse out the filter, sort, etc., parameters from a request"""
if environ.get('QUERY_STRING'):
params = parse_qs(environ['QUERY_STRING'])
else:
params = {}
param_handlers = (
('embedded', params_serializer.unserialize_string, None),
('filter', params_serializer.unseri... | ff8d263e4495804e1bb30d0c4da352b2437fc8f8 | 19,046 |
def create_dict_facade_for_object_vars_and_mapping_with_filters(cls, # type: Type[Mapping]
include, # type: Union[str, Tuple[str]]
exclude, ... | cccdc19b43ca269cfedb4f7d6ad1d7b8abba78e1 | 19,047 |
import time
def now():
"""
此时的时间戳
:return:
"""
return int(time.time()) | 39c05a695bfe4239ebb3fab6f3a5d0967bea6820 | 19,048 |
def get_yourContactINFO(rows2):
"""
Function that returns your personal contact info details
"""
yourcontactINFO = rows2[0]
return yourcontactINFO | beea815755a2e6817fb57a37ccc5aa479455bb81 | 19,049 |
def hafnian(
A, loop=False, recursive=True, rtol=1e-05, atol=1e-08, quad=True, approx=False, num_samples=1000
): # pylint: disable=too-many-arguments
"""Returns the hafnian of a matrix.
For more direct control, you may wish to call :func:`haf_real`,
:func:`haf_complex`, or :func:`haf_int` directly.
... | 0e90f1d372bf7be636ae8eb333d2c59a387b58f1 | 19,050 |
def filter_out_nones(data):
"""
Filter out any falsey values from data.
"""
return (l for l in data if l) | 39eb0fb7aafe799246d231c5a7ad8a150ed4341e | 19,051 |
import IPython
import IPython.display
def start(args_string):
"""Launch and display a TensorBoard instance as if at the command line.
Args:
args_string: Command-line arguments to TensorBoard, to be
interpreted by `shlex.split`: e.g., "--logdir ./logs --port 0".
Shell metacharacters are ... | dae8ed95b7989af185b5681dfef79fcbd5d354ab | 19,052 |
def BytesToGb(size):
"""Converts a disk size in bytes to GB."""
if not size:
return None
if size % constants.BYTES_IN_ONE_GB != 0:
raise calliope_exceptions.ToolException(
'Disk size must be a multiple of 1 GB. Did you mean [{0}GB]?'
.format(size // constants.BYTES_IN_ONE_GB + 1))
retu... | 49bc846ce6887fd47ac7be70631bddd8353c72ed | 19,053 |
def build_report(drivers: dict, desc=False) -> [[str, str, str], ...]:
"""
Creates a race report: [[Driver.name, Driver.team, Driver.time], ...]
Default order of drivers from best time to worst.
"""
sorted_drivers = sort_drivers_dict(drivers, desc)
return [driver.get_stats for driver in sorted_d... | c8c84319c0a14867b21d09c8b66ea434d13786aa | 19,054 |
def add_sites_sheet(ws, cols, lnth):
"""
"""
for col in cols:
cell = "{}1".format(col)
ws[cell] = "='Capacity_km2_MNO'!{}".format(cell)
for col in cols[:2]:
for i in range(2, lnth):
cell = "{}{}".format(col, i)
ws[cell] = "='Capacity_km2_MNO'!{}"... | c1db2b585021e8eef445963f8c300d726600e12a | 19,055 |
import itertools
def testBinaryFile(filePath):
"""
Test if a file is in binary format
:param fileWithPath(str): File Path
:return:
"""
file = open(filePath, "rb")
#Read only a couple of lines in the file
binaryText = None
for line in itertools.islice(file, 20):
... | 809a962881335ce0a3a05e341a13b413c381fedf | 19,056 |
import psutil
import sys
import os
import subprocess
def launch_experiment(
script,
run_slot,
affinity_code,
log_dir,
variant,
run_ID,
args,
python_executable=None,
set_egl_device=False,
):
"""Launches one learning run using ``subprocess.... | 29acb675619943d88424231fbfb9d574e5fc03b2 | 19,057 |
def dup_max_norm(f, K):
"""
Returns maximum norm of a polynomial in ``K[x]``.
Examples
========
>>> from sympy.polys import ring, ZZ
>>> R, x = ring("x", ZZ)
>>> R.dup_max_norm(-x**2 + 2*x - 3)
3
"""
if not f:
return K.zero
else:
return max(dup_abs(f, K)) | 1ba4744781a3f5cb8e71b59bc6588579f88a6d43 | 19,058 |
def greedy_algorithm(pieces, material_size):
"""Implementation of the First-Fit Greedy Algorithm
Inputs:
pieces - list[] of items to place optimally
material_size - length of Boards to cut from, assumes unlimited supply
Output:
Optimally laid out BoardCollection.contents, which is a list[] of ... | f42b2372b50385c693765d65614d73a8b21f496b | 19,059 |
def start_tv_session(hypes):
"""
Run one evaluation against the full epoch of data.
Parameters
----------
hypes : dict
Hyperparameters
Returns
-------
tuple
(sess, saver, summary_op, summary_writer, threads)
"""
# Build the summary operation based on the TF coll... | f54cfa17871badf2cbe92200144a758d0fc2dc41 | 19,060 |
def factor_size(value, factor):
"""
Factors the given thumbnail size. Understands both absolute dimensions
and percentages.
"""
if type(value) is int:
size = value * factor
return str(size) if size else ''
if value[-1] == '%':
value = int(value[:-1])
return '{0}%... | 41b061fb368d56ba18b52cd7a6a3322292671d83 | 19,061 |
def categoryProfile(request, pk):
"""
Displays the profile of a :class:`gestion.models.Category`.
pk
The primary key of the :class:`gestion.models.Category` to display profile.
"""
category = get_object_or_404(Category, pk=pk)
return render(request, "gestion/category_profile.html", {"ca... | 87318332c7e317a49843f5becda8196951743ce5 | 19,062 |
def eoms(_x, t, _params):
"""Rigidy body equations of motion.
_x is an array/list in the following order:
q1: Yaw q2: Lean |-(Euler 3-1-2 angles used to orient A
q3: Pitch /
q4: N[1] displacement of mass center.
q5: N[2] displacement of mass center.
q6: ... | 3868411e2c082617311f59f3b39deec9d3a370fa | 19,063 |
def memoize_with_hashable_args(func):
"""Decorator for fast caching of functions which have hashable args.
Note that it will convert np.NaN to None for caching to avoid this common
case causing a cache miss.
"""
_cached_results_ = {}
hash_override = getattr(func, "__hash_override__", None)
i... | b5e55b35042688d9131e05e36a56bf0f6515f336 | 19,064 |
def orthogonalize(vec1, vec2):
"""Given two vectors vec1 and vec2, project out the component of vec1
that is along the vec2-direction.
@param[in] vec1 The projectee (i.e. output is some modified version of vec1)
@param[in] vec2 The projector (component subtracted out from vec1 is parallel to this)
... | aceca85edfc6ed4a6c3b21cb169f993b0b30c889 | 19,065 |
import re
def tokenize(text):
"""
Function to process text data taking following steps:
1) normalization and punctuation removal: convert to lower case and remove punctuations
2) tokenization: splitting each sentence into sequence of words
3) stop words removal: removal of words which ... | 769949bc2d4a23d4064b8addcaa7dbfc29346549 | 19,066 |
def extract_text(bucketname, filepath):
"""Return OCR data associated with filepaths"""
textract = boto3.client('textract')
response = textract.detect_document_text(
Document={
'S3Object': {
'Bucket': bucketname,
'Name': filepath
}
})
... | fde7c1bc99003bf8f094538d402a66b6d0c8bcb4 | 19,067 |
def box1_input(input):
"""uses above to return input to player 1"""
return get_input(1, input) | c619be2f73fc124eb3198c27542af014eeffd3f8 | 19,068 |
def _get_xy_from_geometry(df):
"""
Return a numpy array with two columns, where the
first holds the `x` geometry coordinate and the second
column holds the `y` geometry coordinate
"""
# NEW: use the centroid.x and centroid.y to support Polygon() and Point() geometries
x = df.geometry.centroi... | 6a1345607d3c75190dd9fd22ea45aad82901282a | 19,069 |
def create_styled_figure(
title,
name=None,
tooltips=None,
plot_width=PLOT_WIDTH,
):
"""Return a styled, empty figure of predetermined height and width.
Args:
title (str): Title of the figure.
name (str): Name of the plot for later retrieval by bokeh. If not given the
... | caeb7eb887d84c5e1ebaf83b01a71ce15917a27f | 19,070 |
def render_text(string, padding=5, width=None, height=None,
size=12, font="Arial", fgcolor=(0, 0, 0), bgcolor=None):
"""
Render text to an image and return it
Not specifying bgcolor will give a transparent image, but that will take a *lot* more work to build.
Specifying a bgcolor, width... | 9402aa9cbcbb920b73723d74b944f5940db9e0e0 | 19,071 |
def pretty_spectrogram(d,log = True, thresh= 5, fft_size = 512, step_size = 64):
"""
creates a spectrogram
log: take the log of the spectrgram
thresh: threshold minimum power for log spectrogram
"""
specgram = np.abs(stft(d, fftsize=fft_size, step=step_size, real=False,
compute_onesided=... | eaae2893944df28dcefb607bac3e8648db265acf | 19,072 |
def check_for_win(position, board, player):
"""
check for wins on 3x3 board on rows,cols,diag,anti-diag
args: position (int 1-9, user input)
board (np.array 2d)
player ("X" or "O")
"""
#initialize win to False
win = False
#check win on rows
for row in board:
... | fad580912f3a281ce605fd743732481915c352ea | 19,073 |
def wrap_http_exception(app: FastAPI):
"""
https://doc.acrobits.net/api/client/intro.html#web-service-responses
"""
@app.exception_handler(StarletteHTTPException)
async def http_exception_handler(request, exc):
return JSONResponse({'message': exc.detail}, exc.status_code) | b43eea9b59eb50eaefd3d52a5569d6952518f61b | 19,074 |
import random
def perm_2sample(group1, group2, nrand=10000, tail=0, paired=True):
# Take from JW's functions
"""
non-parametric permutation test (Efron & Tibshirani, 1998)
tail = 0 (test A~=B), 1 (test A>B), -1 (test A<B)
"""
a = group1
b = group2
ntra = len(a)
ntrb = len(b)
... | afb3c56d277c583eeb34089bcd808e7e6e662ec7 | 19,075 |
def softmax_op(node):
""" This function computes its softmax along an axis.
Parameters:
----
node : Node
Input variable.
Returns:
----
A new Node instance created by Op.
"""
return SoftmaxOp()(node) | 42004658214b7b7c083d40fe43393f1cf450175b | 19,076 |
def full_chain():
"""
:return: Returns entire blockchain in memory (current_chain.blockchain)
"""
response = {
'chain': current_chain.blockchain,
'length': len(current_chain.blockchain),
}
return response, 200 | 0161195e3dc28b9157ee824f8d3103029f058498 | 19,077 |
def normalizer(x, mi, ma, eps=1e-20, dtype=np.float32):
"""
Number expression evaluation for normalization
Parameters
----------
x : np array of Image patch
mi : minimum input percentile value
ma : maximum input percentile value
eps: avoid dividing by zero
dtype: type of numpy array... | 0f39a4d02bc3f3897d0b2070567a45eb68ade2d4 | 19,078 |
def do(args):
""" Main Entry Point. """
build_worktree = qibuild.parsers.get_build_worktree(args)
sourceme = build_worktree.generate_sourceme()
print(sourceme)
return sourceme | d706fe7f8a277f58dd8f184212851d087b7890d1 | 19,079 |
import json
import traceback
def policy_action(module,
state=None,
policy_name=None,
policy_arn=None,
policy_document=None,
path=None,
description=None):
"""
Execute the actions needed to bring the poli... | 5da4c4649170e81569cc3e77fa102fd0043cebd9 | 19,080 |
def GET_v1_metrics_location(days=1):
"""Return some data about the locations users have reported from.
"""
if days > 7:
days = 7
from_time = f'-{days}d'
locations = fetch_graphite_sum('*.geoip.*', from_time=from_time)
return jsonify(locations=locations) | e9765f338c1adbbb46e203024b7637af45e2f217 | 19,081 |
def add_default_to_usage_help(
usage_help: str, default: str or int or float or bool
) -> str:
"""Adds default value to usage help string.
Args:
usage_help (str):
usage help for click option.
default (str or int or float):
default value as string for click option.
... | a40cf9a68f18beeafcb965c51e0329b4e8216fb4 | 19,082 |
def describe_deformation(el_disps, bfg):
"""
Describe deformation of a thin incompressible 2D membrane in 3D
space, composed of flat finite element faces.
The coordinate system of each element (face), i.e. the membrane
mid-surface, should coincide with the `x`, `y` axes of the `x-y`
plane.
... | e748a8ecf3cc369fb03ba835b6f0c762eeafbf07 | 19,083 |
import re
def remove_emails(text):
"""Returns A String with the emails removed """
result = re.sub(EMAIL_REGEX, "", text)
return result | 08d30119f5e32a92c3df3a7b5612ba99390e7df9 | 19,084 |
def _fit_model_residual_with_radial(lmparams, star, self, interpfunc):
"""Residual function for fitting individual profile parameters
:param lmparams: lmfit Parameters object
:param star: A Star instance.
:param self: PSF instance
:param interpfunc: The interpolation function
... | 77f4031dbf7522236c36a8e096c965766df16ccb | 19,085 |
def _whoami():
# type: () -> Tuple[str,str]
"""
Return the current operating system account as (username, fullname)
"""
username = getuser()
fullname = username
if GET_PW_NAM:
pwnam = getpwnam(username)
if pwnam:
fullname = pwnam.pw_gecos.split(",", 1)[0]
retu... | 508189e4798e83425b754ad6cde617a3b0d1ec9f | 19,086 |
from typing import Sequence
def text_set_class(
set_class: Sequence,
) -> str:
"""Converts a set class into a string representing its interval vector.
"""
id_dict = {0: "one",
1: "two",
2: "three",
3: "four",
4: "five",
5: "six"}
... | f430ddf4b32f64f37df5fb9ec984ce5a809b09a1 | 19,087 |
def Span_read(stream):
"""Read a span from an 88.1 protocol stream."""
start = Address_read(stream)
width = Offset_read(stream)
return Span(start, width) | 0bbd5d62a1111dd056a939ee272ea200e1f7abd9 | 19,088 |
def temp_database(tmpdir_factory):
""" Initalize the Database """
tmpdb = str(tmpdir_factory.mktemp('temp'))+"/testdb.sqlite"
return tmpdb | 5cfcb27e6ac76766e21a1612691dbe79d1713abd | 19,089 |
import ast
def get_classes(pyfile_path):
"""
Obtiene las clases que están dentro de un fichero python
:param str pyfile_path: nombre del fichero a inspeccionar
:return: devuelve una lista con todas las clases dentro de un fichero python
:rtype: list
.. code-block:: python
>> get_cla... | 72f376d10fd02574085a0236e10ea8901033ebd0 | 19,090 |
from typing import List
def transpose_outer_dimensions(outer_dimensions: ST_Type, diff_dimensions: ST_Type, ports_to_transpose: List) -> Kind:
"""
Transpose the outer dimensions of a set of ports, move them inside the diff dimensions. The outer dimensions
that are sseqs are the same for all elements, so t... | ca51943223bbca58f871a9cb4c6b296ae941e87d | 19,091 |
def pad_or_clip_nd(tensor, output_shape):
"""Pad or Clip given tensor to the output shape.
Args:
tensor: Input tensor to pad or clip.
output_shape: A list of integers / scalar tensors (or None for dynamic dim)
representing the size to pad or clip each dimension of the input tensor.
Ret... | a22b6872b4af4424411d26232af0c21fda7c55df | 19,092 |
def dynamic_lstm(x, n_neuron, act_fn=tanh, seq_len=None):
""" assert x is batch_major, aka [batch, time, ...] """
cell_class = lstm
with tf.variable_scope("fw"):
cell_fw = cell_class(n_neuron, activation=act_fn, cell_clip=15.0)
o, s = tf.nn.dynamic_rnn(
cell_fw, x, seq_len, ... | 4f2df8155281e3664d5d8521918af5c84a211a34 | 19,093 |
def ho2ax_single(ho):
"""Conversion from a single set of homochoric coordinates to an
un-normalized axis-angle pair :cite:`rowenhorst2015consistent`.
Parameters
----------
ho : numpy.ndarray
1D array of (x, y, z) as 64-bit floats.
Returns
-------
ax : numpy.ndarray
1D a... | 50ec25eb488ea894f6a5c6a00feab27b93954200 | 19,094 |
import json
def task_export_commit(request):
"""提交导出任务"""
try:
datas = json.loads(request.body.decode())
taskSetting = PlTaskSetting.objects.get(id=datas["params"]["id"])
try:
exportJob = PlExportJob.objects.get(task_setting_id=taskSetting.id)
except ObjectDoesNotEx... | 4ec543af62e9abab9194b22cf54e22de2551ce24 | 19,095 |
def getExceptionMessage(exceptionDetails: dict) -> str:
"""Get exception message from `exceptionDetails` object."""
exception = exceptionDetails.get('exception')
if exception:
return exception.get('description')
message = exceptionDetails.get('text', '')
stackTrace = exceptionDetails.get('st... | ba3d15aa383de9f55600a72ba113c37fd042d3a4 | 19,096 |
def evaluate_by_net(net, input_fn, **kwargs):
"""encapsulate evaluate
"""
ret = evaluate(
graph=net.graph, sess=net.session,
fea_ph=net.features_ph, label_ph=net.labels_ph, outputs=net.outputs,
input_fn=input_fn, **kwargs
)
return ret | a58b80b5e93dbb4251eb71393f8a9f70ddff813b | 19,097 |
import array
def ordinate(values,maxrange,levels):
"""Ordinate values given a maximum data range and number of levels
Parameters:
1. values: an array of continuous values to ordinate
2. maxrange: the maximum data range. Values larger than this will be saturated.
3. levels: the number of level... | 4db4a26579d9208cd90ec630cf82e54a4a7ec3fe | 19,098 |
def is_start_state(state):
"""
Checks if the given state is a start state.
"""
return (state.g_pos.value == 0) and (state.theta.value == 'N') | 0f58e7a193533ba3d5db15c4e79ed98e190fa1be | 19,099 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.