text stringlengths 81 112k |
|---|
Compute crosstalk inversion matrix
The spillover matrix is
| | c11 c12 c13 |
| | c21 c22 c23 |
| | c31 c32 c33 |
The diagonal elements are set to 1, i.e.
ct11 = c22 = c33 = 1
Parameters
----------
cij: float
Spill from channel i to channel j
Returns
-------
... |
Perform crosstalk correction
Parameters
----------
fli: int, float, or np.ndarray
Measured fluorescence signals
fl_channel: int (1, 2, or 3)
The channel number for which the crosstalk-corrected signal
should be computed
cij: float
Spill (crosstalk or bleed-through) f... |
Compute the moments of a contour
The moments are computed in the same way as they are computed
in OpenCV's `contourMoments` in `moments.cpp`.
Parameters
----------
cont: array of shape (N,2)
The contour for which to compute the moments.
flt_epsilon: float
The value of ``FLT_EPS... |
Compute the inertia ratio of the convex hull of a contour
The inertia ratio is computed from the central second order of moments
along x (mu20) and y (mu02) via `sqrt(mu20/mu02)`.
Parameters
----------
cont: ndarray or list of ndarrays of shape (N,2)
A 2D array that holds the contour of an... |
Compute principal inertia ratio of a contour
The principal inertia ratio is rotation-invariant, which
makes it applicable to reservoir measurements where e.g.
cells are not aligned with the channel.
Parameters
----------
cont: ndarray or list of ndarrays of shape (N,2)
A 2D array that ... |
Compute the inertia ratio of a contour
The inertia ratio is computed from the central second order of moments
along x (mu20) and y (mu02) via `sqrt(mu20/mu02)`.
Parameters
----------
cont: ndarray or list of ndarrays of shape (N,2)
A 2D array that holds the contour of an event (in pixels)
... |
Compute tilt of raw contour relative to channel axis
Parameters
----------
cont: ndarray or list of ndarrays of shape (N,2)
A 2D array that holds the contour of an event (in pixels)
e.g. obtained using `mm.contour` where `mm` is an instance
of `RTDCBase`. The first and second colum... |
Constructs a decorator that tags a function with specified
strings (@tags). The tags on the decorated function are
available via fn.tags
def tag(*tags):
'''
Constructs a decorator that tags a function with specified
strings (@tags). The tags on the decorated function are
available via fn.tags
... |
Constructs a decorator that marks the fn
as raw response format
def raw(mime='application/octet-stream'):
'''
Constructs a decorator that marks the fn
as raw response format
'''
def dfn(fn):
tags = getattr(fn, 'tags', set())
tags.add('raw')
fn.tags = tags
fn.mime... |
Called when client opens connection. Initialization
is done here.
def open(self, pysession_id):
'''
Called when client opens connection. Initialization
is done here.
'''
self.id = id(self)
self.funcserver = self.application.funcserver
self.pysession_id = ... |
Called when client sends a message.
Supports a python debugging console. This forms
the "eval" part of a standard read-eval-print loop.
Currently the only implementation of the python
console is in the WebUI but the implementation
of a terminal based console is planned.
def on... |
Called when client closes this connection. Cleanup
is done here.
def on_close(self):
'''
Called when client closes this connection. Cleanup
is done here.
'''
if self.id in self.funcserver.websocks:
self.funcserver.websocks[self.id] = None
ioloop ... |
Remove unexpected keyword arguments from the
set of received keyword arguments.
def _clean_kwargs(self, kwargs, fn):
'''
Remove unexpected keyword arguments from the
set of received keyword arguments.
'''
# Do not do the cleaning if server config
# doesnt ask to ... |
Dumps the stack of all threads. This function
is meant for debugging. Useful when a deadlock happens.
borrowed from: http://blog.ziade.org/2012/05/25/zmq-and-gevent-debugging-nightmares/
def dump_stacks(self):
'''
Dumps the stack of all threads. This function
is meant for debug... |
adds a hook to send to websocket if the run command was selected
def define_log_pre_format_hooks(self):
"""
adds a hook to send to websocket if the run command was selected
"""
hooks = super(Server, self).define_log_pre_format_hooks()
# NOTE enabling logs only on debug mode
... |
prepares the api and starts the tornado funcserver
def run(self):
""" prepares the api and starts the tornado funcserver """
self.log_id = 0
# all active websockets and their state
self.websocks = {}
# all active python interpreter sessions
self.pysessions = {}
... |
Returns the contents of the sql file from the given ``filename``.
def _get_sql(filename):
"""Returns the contents of the sql file from the given ``filename``."""
with open(os.path.join(SQL_DIR, filename), 'r') as f:
return f.read() |
Given an ``id`` and ``version``, verify the identified content exists.
def verify_id_n_version(id, version):
"""Given an ``id`` and ``version``, verify the identified content exists.
"""
stmt = _get_sql('verify-id-and-version.sql')
args = dict(id=id, version=version)
with db_connect() as db_conn:... |
From the given ``ident_hash`` return the id and version.
def get_id_n_version(ident_hash):
"""From the given ``ident_hash`` return the id and version."""
try:
id, version = split_ident_hash(ident_hash)
except IdentHashMissingVersion:
# XXX Don't import from views... And don't use httpexcept... |
Return the database type for the given ``ident_hash``
As of now, this could either be a 'Module' or 'Collection'.
def get_type(ident_hash):
"""Return the database type for the given ``ident_hash``
As of now, this could either be a 'Module' or 'Collection'.
"""
id, version = get_id_n_version(ident_... |
Return the dictionary of metadata from the database.
This data is keyed using the cnx-epub data structure.
def get_metadata(ident_hash):
"""Return the dictionary of metadata from the database.
This data is keyed using the cnx-epub data structure.
"""
id, version = get_id_n_version(ident_hash)
... |
Returns the content for the given ``ident_hash``.
``context`` is optionally ident-hash used to find the content
within the context of a Collection ident_hash.
def get_content(ident_hash, context=None):
"""Returns the content for the given ``ident_hash``.
``context`` is optionally ident-hash used to fin... |
Returns information about the file, identified by ``hash``.
If the `context` (an ident-hash) is supplied,
the information returned will be specific to that context.
def get_file_info(hash, context=None):
"""Returns information about the file, identified by ``hash``.
If the `context` (an ident-hash) is ... |
Return the contents of the file as a ``memoryview``.
def get_file(hash):
"""Return the contents of the file as a ``memoryview``."""
stmt = _get_sql('get-file.sql')
args = dict(hash=hash)
with db_connect() as db_conn:
with db_conn.cursor() as cursor:
cursor.execute(stmt, args)
... |
Returns a list SHA1 hashes for registered file entries
identified by the given module ``ident_hash``.
Note, it's possible for a module to reference a file without having
a registered file entry for it.
Note, all files are included, including the raw form of the content.
def get_registered_files(ident... |
Return a tree structure of the Collection
def get_tree(ident_hash, baked=False):
"""Return a tree structure of the Collection"""
id, version = get_id_n_version(ident_hash)
stmt = _get_sql('get-tree.sql')
args = dict(id=id, version=version, baked=baked)
with db_connect() as db_conn:
with d... |
Returns the media-type of the file at the given ``filepath``
def guess_media_type(filepath):
"""Returns the media-type of the file at the given ``filepath``"""
o = subprocess.check_output(['file', '--mime-type', '-Lb', filepath])
o = o.strip()
return o |
Return the ``module_ident`` for the given ``id`` &
major and minor version as a tuple.
def lookup_module_ident(id, version):
"""Return the ``module_ident`` for the given ``id`` &
major and minor version as a tuple.
"""
with db_connect() as db_conn:
with db_conn.cursor() as cursor:
... |
Upsert the ``file`` and ``media_type`` into the files table.
Returns the ``fileid`` and ``sha1`` of the upserted file.
def insert_file(file, media_type):
"""Upsert the ``file`` and ``media_type`` into the files table.
Returns the ``fileid`` and ``sha1`` of the upserted file.
"""
resource_hash = ge... |
Upsert a file associated with ``fileid`` with ``filename``
as a module_files entry associated with content at ``module_ident``.
def upsert_module_file(module_ident, fileid, filename):
"""Upsert a file associated with ``fileid`` with ``filename``
as a module_files entry associated with content at ``module_i... |
Injects the contents of ``file`` (a file-like object) into the database
as ``filename`` with ``media_type`` in association with the content
at ``ident_hash``.
def inject_resource(ident_hash, file, filename, media_type):
"""Injects the contents of ``file`` (a file-like object) into the database
as ``fil... |
Compute the image contour from a mask
The contour is computed in a very inefficient way using scikit-image
and a conversion of float coordinates to pixel coordinates.
Parameters
----------
mask: binary ndarray of shape (M,N) or (K,M,N)
The mask outlining the pixel positions of the event.
... |
Scans the local network for TVs.
def scan(self, stop_on_first=True, base_ip=0):
"""Scans the local network for TVs."""
tvs = []
# Check if base_ip has been passed
if base_ip == 0:
# Find IP address of computer pymitv is running on
sock = socket.socket(soc... |
Attempts a connection to the TV and checks if there really is a TV.
def check_ip(ip, log=False):
"""Attempts a connection to the TV and checks if there really is a TV."""
if log:
print('Checking ip: {}...'.format(ip))
request_timeout = 0.1
try:
tv_url =... |
Obtain the type name of a GRPC Message field.
def get_field_type(f):
"""Obtain the type name of a GRPC Message field."""
types = (t[5:] for t in dir(f) if t[:4] == 'TYPE' and
getattr(f, t) == f.type)
return next(types) |
Get the type description of a GRPC Message field.
def get_field_description(f):
"""Get the type description of a GRPC Message field."""
type_name = get_field_type(f)
if type_name == 'MESSAGE' and \
{sf.name for sf in f.message_type.fields} == {'key', 'value'}:
return 'map<string, string... |
Creates a request from a static method function call.
def make_static_request(method, *args, **kwargs):
"""Creates a request from a static method function call."""
if args and not use_signature:
raise NotImplementedError("Only keyword arguments allowed in Python2")
if use_signature:
new_kw... |
Creates a request from a method function call.
def make_request(self, method, *args, **kwargs):
"""Creates a request from a method function call."""
if args and not use_signature:
raise NotImplementedError("Only keyword arguments allowed in Python2")
new_kwargs = {kw: unwrap(value) for kw, value i... |
Generates a method from a `GrpcMethod` definition.
def method_wrapper(m):
"""Generates a method from a `GrpcMethod` definition."""
if m.is_simple:
def simple_method(self):
"""TODO: no docstring!"""
return apply_transform(
self.__service__, m.output_transform,
... |
Generate the name of the request.
def request_name(self):
"""Generate the name of the request."""
if self.static and not self.uses_request:
return 'Empty'
if not self.uses_request:
return None
if isinstance(self.uses_request, str):
return self.uses_... |
Retrieve the type of the request, by fetching it from
`xenon.proto.xenon_pb2`.
def request_type(self):
"""Retrieve the type of the request, by fetching it from
`xenon.proto.xenon_pb2`."""
if self.static and not self.uses_request:
return getattr(xenon_pb2, 'Empty')
i... |
Create a signature for this method, only in Python > 3.4
def signature(self):
"""Create a signature for this method, only in Python > 3.4"""
if not use_signature:
raise NotImplementedError("Python 3 only.")
if self.static:
parameters = \
(Parameter(name=... |
Generate a doc-string.
def docstring(self, servicer):
"""Generate a doc-string."""
s = getattr(servicer, to_lower_camel_case(self.name)).__doc__ \
or "TODO: no docstring in .proto file"
if self.uses_request:
s += "\n"
for field in get_fields(self.request_typ... |
Return a slug for the unicode_string.
(lowercase, only letters and numbers, hyphens replace spaces)
def slugify(string):
"""Return a slug for the unicode_string.
(lowercase, only letters and numbers, hyphens replace spaces)
"""
filtered_string = []
if isinstance(string, str):
string =... |
Change all python2 str/bytes instances to unicode/python3 str.
def utf8(item):
"""Change all python2 str/bytes instances to unicode/python3 str."""
if isinstance(item, list):
return [utf8(i) for i in item]
if isinstance(item, tuple):
return tuple([utf8(i) for i in item])
if isinstance(i... |
Update the filters according to `self.rtdc_ds.config["filtering"]`
Parameters
----------
force : list
A list of feature names that must be refiltered with
min/max values.
def update(self, force=[]):
"""Update the filters according to `self.rtdc_ds.config["filter... |
Find iso-valued contours in a 2D array for a given level value.
Uses the "marching squares" method to compute a the iso-valued contours of
the input 2D array for a particular level value. Array values are linearly
interpolated to provide better precision for the output contours.
Parameters
-------... |
Return the moduleid for a given ``ident_hash``.
def get_module_ident_from_ident_hash(ident_hash, cursor):
"""Return the moduleid for a given ``ident_hash``."""
try:
uuid, (mj_ver, mn_ver) = split_ident_hash(
ident_hash, split_version=True)
except IdentHashMissingVersion as e:
uu... |
Return a JSON representation of the binder tree for ``ident_hash``.
def get_tree(ident_hash, cursor, as_collated=False):
"""Return a JSON representation of the binder tree for ``ident_hash``."""
uuid, version = split_ident_hash(ident_hash)
cursor.execute(SQL['get-tree-by-uuid-n-version'],
... |
Return collated content for ``ident_hash``.
def get_collated_content(ident_hash, context_ident_hash, cursor):
"""Return collated content for ``ident_hash``."""
cursor.execute(SQL['get-collated-content'],
(ident_hash, context_ident_hash,))
try:
return cursor.fetchone()[0]
exce... |
Retrieve page uuid from legacy moduleid.
def get_module_uuid(plpy, moduleid):
"""Retrieve page uuid from legacy moduleid."""
plan = plpy.prepare("SELECT uuid FROM modules WHERE moduleid = $1;",
('text',))
result = plpy.execute(plan, (moduleid,), 1)
if result:
return resu... |
Retrieve module_ident for a given moduleid.
Note that module_ident is used only for internal database relational
associations, and is equivalent to a uuid@version for a given document.
def get_current_module_ident(moduleid, plpy):
"""Retrieve module_ident for a given moduleid.
Note that module_ident ... |
Retrieve minor version only given module_ident.
def get_minor_version(module_ident, plpy):
"""Retrieve minor version only given module_ident."""
# Make sure to always return the max minor version that is already in the
# database, in case the given module_ident is not the latest version
plan = plpy.pre... |
Get all the collections that the module is part of.
def get_collections(module_ident, plpy):
"""Get all the collections that the module is part of."""
# Make sure to only return one match per collection and only if it is the
# latest collection (which may not be the same as what is in
# latest_modules)... |
Get all the sub-collections that the module is part of.
def get_subcols(module_ident, plpy):
"""Get all the sub-collections that the module is part of."""
plan = plpy.prepare('''
WITH RECURSIVE t(node, parent, path, document) AS (
SELECT tr.nodeid, tr.parent_id, ARRAY[tr.nodeid], tr.documentid
... |
Create a new tree for the collection based on the old tree.
This uses new document ids, replacing old ones.
def rebuild_collection_tree(old_collection_ident, new_document_id_map, plpy):
"""Create a new tree for the collection based on the old tree.
This uses new document ids, replacing old ones.
"""
... |
Insert a new row for collection_ident with a new version.
Returns the module_ident of the row inserted.
def republish_collection(submitter, submitlog, next_minor_version,
collection_ident, plpy, revised=None):
"""Insert a new row for collection_ident with a new version.
Returns t... |
Set the major_version and minor_version if they are not set.
def set_version(portal_type, legacy_version, td):
"""Set the major_version and minor_version if they are not set."""
modified = 'OK'
legacy_major, legacy_minor = legacy_version.split('.')
if portal_type == 'Collection':
# For collect... |
When a module is republished, create new minor versions of collections.
All collections (including subcollections) that this module is contained
in part of will need to be updated (a minor update).
e.g. there is a collection c1 v2.1, which contains a chapter sc1 v2.1,
which contains a module m1 v3. Wh... |
Trigger called from postgres database when republishing a module.
When a module is republished, the versions of the collections that it is
part of will need to be updated (a minor update).
e.g. there is a collection c1 v2.1, which contains module m1 v3
m1 is updated, we have a new row in the modules... |
Trigger to fill in legacy ``moduleid`` when publishing.
This correctly assigns ``moduleid`` value to
cnx-publishing publications. This does NOT include
matching the ``moduleid`` to previous revision by way of ``uuid``.
This correctly updates the sequence values when a legacy publication
specifies ... |
Trigger to fill in legacy data fields.
A compatibilty trigger to fill in legacy data fields that are not
populated when inserting publications from cnx-publishing.
If this is not a legacy publication the ``version`` will be set
based on the ``major_version`` value.
def assign_version_default_trigger(... |
Trigger to fill in document_controls when legacy publishes.
A compatibilty trigger to fill in ``uuid`` and ``licenseid`` columns
of the ``document_controls`` table that are not
populated when inserting publications from legacy.
This uuid default is not on ``modules.uuid`` column itself,
because th... |
Trigger for filling in acls when legacy publishes.
A compatibility trigger to upsert authorization control entries (ACEs)
for legacy publications.
def upsert_document_acl_trigger(plpy, td):
"""Trigger for filling in acls when legacy publishes.
A compatibility trigger to upsert authorization control e... |
A compatibility trigger to upsert users from legacy persons table.
def upsert_users_from_legacy_publication_trigger(plpy, td):
"""A compatibility trigger to upsert users from legacy persons table."""
modified_state = "OK"
authors = td['new']['authors'] and td['new']['authors'] or []
maintainers = td['n... |
Trigger to update users from optional roles entries.
A compatibility trigger to insert users from moduleoptionalroles
records. This is primarily for legacy compatibility, but it is not
possible to tell whether the entry came from legacy or cnx-publishing.
Therefore, we only insert into users.
def inse... |
Database trigger for adding a module file.
When a legacy ``index.cnxml`` is added, this trigger
transforms it into html and stores it as ``index.cnxml.html``.
When a cnx-publishing ``index.cnxml.html`` is added, this trigger
checks if ``index.html.cnxml`` exists before
transforming it into cnxml an... |
Transform abstract, bi-directionally.
Transforms an abstract using one of content columns
('abstract' or 'html') to determine which direction the transform
will go (cnxml->html or html->cnxml).
A transform is done on either one of them to make
the other value. If no value is supplied, the trigger r... |
Build and retrieve json tree representation of a book.
def get_collection_tree(collection_ident, cursor):
"""Build and retrieve json tree representation of a book."""
cursor.execute('''
WITH RECURSIVE t(node, parent, document, path) AS (
SELECT tr.nodeid, tr.parent_id, tr.documentid, ARRAY[tr.nodei... |
Return userids allowed to publish this book.
def get_module_can_publish(cursor, id):
"""Return userids allowed to publish this book."""
cursor.execute("""
SELECT DISTINCT user_id
FROM document_acl
WHERE uuid = %s AND permission = 'publish'""", (id,))
return [i[0] for i in cursor.fetchall()] |
Assembles ``tree`` nodes into object models.
If ``context`` is supplied, it will be used to contextualize
the contents of the nodes. Metadata will pass non-node identifying
values down to child nodes, if not overridden (license, timestamps, etc)
def tree_to_nodes(tree, context=None, metadata=None):
"""... |
Creates an epub from an ``ident_hash``, which is output to the given
``file`` (a file-like object).
Returns None, writes to the given ``file``.
def create_epub(ident_hash, file, format='raw'):
"""Creates an epub from an ``ident_hash``, which is output to the given
``file`` (a file-like object).
Ret... |
Retrieve an export file.
def get_export(request):
"""Retrieve an export file."""
settings = get_current_registry().settings
exports_dirs = settings['exports-directories'].split()
args = request.matchdict
ident_hash, type = args['ident_hash'], args['type']
id, version = split_ident_hash(ident_ha... |
Retrieve files associated with document.
def get_export_files(cursor, id, version, types, exports_dirs, read_file=True):
"""Retrieve files associated with document."""
request = get_current_request()
type_info = dict(request.registry.settings['_type_info'])
metadata = get_content_metadata(id, version, ... |
Return metadata related to the content from the database.
def get_content_metadata(id, version, cursor):
"""Return metadata related to the content from the database."""
# Do the module lookup
args = dict(id=id, version=version)
# FIXME We are doing two queries here that can hopefully be
# con... |
Find iso-valued density contours for a given level value
Parameters
----------
density: 2d ndarray of shape (M, N)
Kernel density estimate for which to compute the contours
x: 2d ndarray of shape (M, N) or 1d ndarray of size M
X-values corresponding to `kde`
y: 2d ndarray of shape (... |
Compute density levels for given quantiles by interpolation
For a given 2D density, compute the density levels at which
the resulting contours contain the fraction `1-q` of all
data points. E.g. for a measurement of 1000 events, all
contours at the level corresponding to a quantile of
`q=0.95` (95t... |
Find density level for a given data quantile by iteration
Parameters
----------
density: 2d ndarray of shape (M, N)
Kernel density estimate for which to compute the contours
x: 2d ndarray of shape (M, N) or 1d ndarray of size M
X-values corresponding to `kde`
y: 2d ndarray of shape ... |
Write data to an RT-DC file
Parameters
----------
path: path or h5py.File
The path or the hdf5 file object to write to.
data: dict-like
The data to store. Each key of `data` must be a valid
feature name (see `dclab.dfn.feature_names`). The data
type must be given accordi... |
:param tup: a list of tuples
:param di: a dictionary converted from tup
:return: dictionary
def _convert(tup, dictlist):
"""
:param tup: a list of tuples
:param di: a dictionary converted from tup
:return: dictionary
"""
di = {}
for a, b in tup:
di.setdefault(a, []).append(b... |
:param val_list: a list of strings
:return: a list of upper-cased strings
def _upper(val_list):
"""
:param val_list: a list of strings
:return: a list of upper-cased strings
"""
res = []
for ele in val_list:
res.append(ele.upper())
return res |
Construct search statment for db execution.
Produces the search statement and argument dictionary to be executed
by the DBAPI v2 execute method.
For example, ``cursor.execute(*_build_search(query, weights))``
:param query: containing terms, filters, and sorts.
:type query: Query
:param weights... |
Search database using parsed query.
Executes a database search query from the given ``query``
(a ``Query`` object) and optionally accepts a list of search weights.
By default, the search results are ordered by weight.
:param query: containing terms, filters, and sorts.
:type query: Query
:retu... |
Heuristic attempt to fix unbalanced quotes in query_string.
def fix_quotes(cls, query_string):
"""Heuristic attempt to fix unbalanced quotes in query_string."""
if query_string.count('"') % 2 == 0:
# no unbalanced quotes to fix
return query_string
fields = [] # contain... |
Parse raw string to query.
Given a raw string (typically typed by the user),
parse to a structured format and initialize the class.
def from_raw_query(cls, query_string):
"""Parse raw string to query.
Given a raw string (typically typed by the user),
parse to a structured form... |
Highlight the found terms in the abstract text.
def highlighted_abstract(self):
"""Highlight the found terms in the abstract text."""
abstract_terms = self.fields.get('abstract', [])
if abstract_terms:
sql = _read_sql_file('highlighted-abstract')
else:
sql = _rea... |
Highlight the found terms in the fulltext.
def highlighted_fulltext(self):
"""Highlight the found terms in the fulltext."""
terms = self.fields.get('fulltext', [])
if not terms:
return None
arguments = {'id': self['id'],
'query': ' & '.join(terms),
... |
r"""
Evaluate the probability density function.
Parameters
----------
data_predict: array_like, optional
Points to evaluate at. If unspecified, the training data is used.
Returns
-------
pdf_est: array_like
Probability density function e... |
Find the Xenon-GRPC jar-file, windows version.
def find_xenon_grpc_jar():
"""Find the Xenon-GRPC jar-file, windows version."""
prefix = Path(sys.prefix)
locations = [
prefix / 'lib',
prefix / 'local' / 'lib'
]
for location in locations:
jar_file = location / 'xenon-grpc-{}... |
Kill the process group associated with the given process. (posix)
def kill_process(process):
"""Kill the process group associated with the given process. (posix)"""
logger = logging.getLogger('xenon')
logger.info('Terminating Xenon-GRPC server.')
os.kill(process.pid, signal.SIGINT)
process.wait() |
Start the server.
def start_xenon_server(port=50051, disable_tls=False):
"""Start the server."""
jar_file = find_xenon_grpc_jar()
if not jar_file:
raise RuntimeError("Could not find 'xenon-grpc' jar file.")
cmd = ['java', '-jar', jar_file, '-p', str(port)]
if not disable_tls:
crt_... |
Connects to TV and sends keystroke via HTTP.
def send_keystrokes(ip, keystrokes, wait=False):
"""Connects to TV and sends keystroke via HTTP."""
tv_url = 'http://{}:6095/controller?action=keyevent&keycode='.format(ip)
for keystroke in keystrokes:
if keystroke == 'wait' or wait... |
Polyfill for muting the TV.
def mute(ip):
"""Polyfill for muting the TV."""
tv_url = 'http://{}:6095/controller?action=keyevent&keycode='.format(ip)
count = 0
while count > 30:
count = count + 1
request = requests.get(tv_url + 'volumedown')
... |
Full text, in-book search.
def in_book_search(request):
"""Full text, in-book search."""
results = {}
args = request.matchdict
ident_hash = args['ident_hash']
args['search_term'] = request.params.get('q', '')
query_type = request.params.get('query_type', '')
combiner = ''
if query_typ... |
In-book search - returns a highlighted version of the HTML.
def in_book_search_highlighted_results(request):
"""In-book search - returns a highlighted version of the HTML."""
results = {}
args = request.matchdict
ident_hash = args['ident_hash']
page_ident_hash = args['page_ident_hash']
try:
... |
Returns an array of shape (nobs, k_vars) for use with `gpke`.
def _adjust_shape(dat, k_vars):
""" Returns an array of shape (nobs, k_vars) for use with `gpke`."""
dat = np.asarray(dat)
if dat.ndim > 2:
dat = np.squeeze(dat)
if dat.ndim == 1 and k_vars > 1: # one obs many vars
nobs = 1
... |
r"""
Returns the non-normalized Generalized Product Kernel Estimator
Parameters
----------
bw: 1-D ndarray
The user-specified bandwidth parameters.
data: 1D or 2-D ndarray
The training data.
data_predict: 1-D ndarray
The evaluation points at which the kernel estimation i... |
Computes the bandwidth of the data.
Parameters
----------
bw: array_like or str
If array_like: user-specified bandwidth.
If a string, should be one of:
- cv_ml: cross validation maximum likelihood
- normal_reference: normal reference rule... |
Sets the default values for the efficient estimation
def _set_defaults(self, defaults):
"""Sets the default values for the efficient estimation"""
self.n_res = defaults.n_res
self.n_sub = defaults.n_sub
self.randomize = defaults.randomize
self.return_median = defaults.return_med... |
Return package version from setup.cfg
def get_version():
"""Return package version from setup.cfg"""
config = RawConfigParser()
config.read(os.path.join('..', 'setup.cfg'))
return config.get('metadata', 'version') |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.