text stringlengths 81 112k |
|---|
Update this application configuration.
To create or update a property provide its key-value
pair in `properties`.
To delete a property provide its key with the value ``None``
in properties.
Args:
properties (dict): Property values to be updated. If ``None`` the pro... |
Delete this application configuration.
def delete(self):
"""Delete this application configuration.
"""
res = self.rest_client.session.delete(self.rest_self)
_handle_http_errors(res) |
Normalize a schema.
def _normalize(schema, allow_none=True):
"""
Normalize a schema.
"""
if allow_none and schema is None:
return schema
if isinstance(schema, CommonSchema):
return schema
if isinstance(schema, StreamSchema):
return schema
if isinstance(schema, bases... |
Is `schema` an common schema.
Args:
schema: Scheme to test.
Returns:
bool: ``True`` if schema is a common schema, otherwise ``False``.
def is_common(schema):
"""
Is `schema` an common schema.
Args:
schema: Scheme to test.
Returns:
bool: ``True`` if schema is ... |
Set a schema from another schema
def _set(self, schema):
"""Set a schema from another schema"""
if isinstance(schema, CommonSchema):
self._spl_type = False
self._schema = schema.schema()
self._style = self._default_style()
else:
self._spl_type = s... |
Create a structured schema that will pass stream tuples into callables as ``tuple`` instances.
If this instance represents a common schema then it will be returned
without modification. Stream tuples with common schemas are
always passed according to their definition.
**Passing as tupl... |
Extend a structured schema by another.
For example extending ``tuple<rstring id, timestamp ts, float64 value>``
with ``tuple<float32 score>`` results in ``tuple<rstring id, timestamp ts, float64 value, float32 score>``.
Args:
schema(StreamSchema): Schema to extend this schema by.
... |
Set an operator's parameter representing the style of this schema.
def _fnop_style(schema, op, name):
"""Set an operator's parameter representing the style of this schema."""
if is_common(schema):
if name in op.params:
del op.params[name]
return
if _is_pe... |
Saves all changed values to the database.
def save(self) -> None:
"""
Saves all changed values to the database.
"""
for name, field in self.fields.items():
value = self.cleaned_data[name]
if isinstance(value, UploadedFile):
# Delete old file
... |
Returns the file name to use based on the original filename of an uploaded file.
By default, the file name is constructed as::
<model_name>-<attribute_name>/<primary_key>/<original_basename>.<random_nonce>.<extension>
def get_new_filename(self, name: str) -> str:
"""
Return... |
Stop the service if no jobs are running unless force is set
def _stop(sas, cmd_args):
"""Stop the service if no jobs are running unless force is set"""
if not cmd_args.force:
status = sas.get_instance_status()
jobs = int(status['job_count'])
if jobs:
return status
return... |
Performs an action against a Streaming Analytics service.
def main(args=None):
""" Performs an action against a Streaming Analytics service.
"""
streamsx._streams._version._mismatch_check('streamsx.topology.context')
try:
sr = run_cmd(args)
sr['return_code'] = 0
except:
sr =... |
Argument parsing
def _parse_args(args):
""" Argument parsing
"""
cmd_parser = argparse.ArgumentParser(description='Control commands for a Streaming Analytics service.')
cmd_parser.add_argument('--service-name', help='Streaming Analytics service name')
cmd_parser.add_argument('--full-response', acti... |
Get information from the user's code (two frames up)
to leave breadcrumbs for file, line, class and function.
def _source_info():
"""
Get information from the user's code (two frames up)
to leave breadcrumbs for file, line, class and function.
"""
ofi = inspect.getouterframes(inspect.currentfra... |
Internal method.
def spl_json(self):
"""Internal method."""
return streamsx.spl.op.Expression.expression('com.ibm.streamsx.topology.topic::' + self.name).spl_json() |
Declare a source stream that introduces tuples into the application.
Typically used to create a stream of tuple from an external source,
such as a sensor or reading from an external system.
Tuples are obtained from an iterator obtained from the passed iterable
or callable that returns ... |
Subscribe to a topic published by other Streams applications.
A Streams application may publish a stream to allow other
Streams applications to subscribe to it. A subscriber matches a
publisher if the topic and schema match.
By default a stream is subscribed as :py:const:`~streamsx.topo... |
Add a file or directory dependency into an Streams application bundle.
Ensures that the file or directory at `path` on the local system
will be available at runtime.
The file will be copied and made available relative to the
application directory. Location determines where the file
... |
Add a Python package dependency for this topology.
If the package defined by the requirement specifier
is not pre-installed on the build system then the
package is installed using `pip` and becomes part
of the Streams application bundle (`sab` file).
The package is expected to b... |
Create a submission parameter.
A submission parameter is a handle for a value that
is not defined until topology submission time. Submission
parameters enable the creation of reusable topology bundles.
A submission parameter has a `name`. The name must be unique
within the to... |
Generate the info to create requirements.txt in the toookit.
def _generate_requirements(self):
"""Generate the info to create requirements.txt in the toookit."""
if not self._pip_packages:
return
reqs = ''
for req in self._pip_packages:
reqs += "{}\n".format... |
Add a JobControlPlane operator to the topology, if one has not already
been added. If a JobControlPlane operator has already been added,
this has no effect.
def _add_job_control_plane(self):
"""
Add a JobControlPlane operator to the topology, if one has not already
been added. ... |
Create an alias of this stream.
Returns an alias of this stream with name `name`.
When invocation of an SPL operator requires an
:py:class:`~streamsx.spl.op.Expression` against
an input port this can be used to ensure expression
matches the input port alias regardless of the nam... |
Defines a view on a stream.
A view is a continually updated sampled buffer of a streams's tuples.
Views allow visibility into a stream from external clients such
as Jupyter Notebooks, the Streams console,
`Microsoft Excel <https://www.ibm.com/support/knowledgecenter/SSCRJU_4.2.0/com.ibm... |
Maps each tuple from this stream into 0 or 1 stream tuples.
For each tuple on this stream ``result = func(tuple)`` is called.
If `result` is not `None` then the result will be submitted
as a tuple on the returned stream. If `result` is `None` then
no tuple submission will occur.
... |
Maps and flatterns each tuple from this stream into 0 or more tuples.
For each tuple on this stream ``func(tuple)`` is called.
If the result is not `None` then the the result is iterated over
with each value from the iterator that is not `None` will be submitted
to the return stream.
... |
Split stream into channels and start a parallel region.
Returns a new stream that will contain the contents of
this stream with tuples distributed across its channels.
The returned stream starts a parallel region where all
downstream transforms are replicated across `width` channels.
... |
Ends a parallel region by merging the channels into a single stream.
Returns:
Stream: Stream for which subsequent transformations are no longer parallelized.
.. seealso:: :py:meth:`set_parallel`, :py:meth:`parallel`
def end_parallel(self):
"""
Ends a parallel region by mer... |
Set this source stream to be split into multiple channels
as the start of a parallel region.
Calling ``set_parallel`` on a stream created by
:py:meth:`~Topology.source` results in the stream
having `width` channels, each created by its own instance
of the callable::
... |
Indicates that the stream is the start of a consistent region.
Args:
consistent_config(consistent.ConsistentRegionConfig): the configuration of the consistent region.
Returns:
Stream: Returns this stream.
.. versionadded:: 1.11
def set_consistent(self, consistent_conf... |
Declares a slding window containing most recent tuples
on this stream.
The number of tuples maintained in the window is defined by `size`.
If `size` is an `int` then it is the count of tuples in the window.
For example, with ``size=10`` the window always contains the
last (most... |
Creates a stream that is a union of this stream and other streams
Args:
streamSet: a set of Stream objects to merge with this stream
Returns:
Stream:
def union(self, streamSet):
"""
Creates a stream that is a union of this stream and other streams
... |
Prints each tuple to stdout flushing after each tuple.
If `tag` is not `None` then each tuple has "tag: " prepended
to it before printing.
Args:
tag: A tag to prepend to each tuple.
name(str): Name of the resulting stream.
When `None` defaults to a gener... |
Publish this stream on a topic for other Streams applications to subscribe to.
A Streams application may publish a stream to allow other
Streams applications to subscribe to it. A subscriber
matches a publisher if the topic and schema match.
By default a stream is published using its sc... |
Starts an autonomous region for downstream processing.
By default IBM Streams processing is executed in an autonomous region
where any checkpointing of operator state is autonomous (independent)
of other operators.
This method may be used to end a consistent region by starting a... |
Declares a stream converting each tuple on this stream
into a string using `str(tuple)`.
The stream is typed as a :py:const:`string stream <streamsx.topology.schema.CommonSchema.String>`.
If this stream is already typed as a string stream then it will
be returned (with no additional pr... |
Declares a stream converting each tuple on this stream into
a JSON value.
The stream is typed as a :py:const:`JSON stream <streamsx.topology.schema.CommonSchema.Json>`.
Each tuple must be supported by `JSONEncoder`.
If `force_object` is `True` then each tuple that not a `dict`
... |
Internal method to change a schema.
def _change_schema(self, schema, action, name=None, func=None):
"""Internal method to change a schema.
"""
if self.oport.schema.schema() == schema.schema():
return self
if func is None:
func = streamsx.topology.functions.ident... |
Used to initialize the View object on first use.
def _initialize_rest(self):
"""Used to initialize the View object on first use.
"""
if self._submit_context is None:
raise ValueError("View has not been created.")
job = self._submit_context._job_access()
self._view_ob... |
Display a view within a Jupyter or IPython notebook.
Provides an easy mechanism to visualize data on a stream
using a view.
Tuples are fetched from the view and displayed in a table
within the notebook cell using a ``pandas.DataFrame``.
The table is continually updated with the... |
Complete the pending stream.
Any connections made to :py:attr:`stream` are connected to `stream` once
this method returns.
Args:
stream(Stream): Stream that completes the connection.
def complete(self, stream):
"""Complete the pending stream.
... |
Declare a window with this window's size and a trigger policy.
When the window is triggered is defined by `when`.
If `when` is an `int` then the window is triggered every
`when` tuples. For example, with ``when=5`` the window
will be triggered every five tuples.
If `when` is ... |
Aggregates the contents of the window when the window is
triggered.
Upon a window trigger, the supplied function is passed a list containing
the contents of the window: ``function(items)``. The order of the window
items in the list are the order in which they were each receive... |
Get the root URL for the IBM Streams REST API.
def get_rest_api():
"""
Get the root URL for the IBM Streams REST API.
"""
assert _has_local_install
url=[]
ok = _run_st(['geturl', '--api'], lines=url)
if not ok:
raise ChildProcessError('streamtool geturl')
return url[0] |
Gets the package name given a module object
Returns:
str: If the module belongs to a package, the package name.
if the module does not belong to a package, None or ''.
def _get_package_name(module):
"""
Gets the package name given a module object
Returns:
str: I... |
Gets the function's module name
Resolves the __main__ module to an actual module name
Returns:
str: the function's module name
def _get_module_name(function):
"""
Gets the function's module name
Resolves the __main__ module to an actual module name
Returns:
str: the function's m... |
Is builtin or part of standard library
def _is_builtin_module(module):
"""Is builtin or part of standard library
"""
if (not hasattr(module, '__file__')) or module.__name__ in sys.builtin_module_names:
return True
if module.__name__ in _stdlib._STD_LIB_MODULES:
return True
amp = os... |
Return the set of dependent modules for used modules,
classes and routines.
def _find_dependent_modules(self, module):
"""
Return the set of dependent modules for used modules,
classes and routines.
"""
dms = set()
for um in inspect.getmembers(module, inspect.ism... |
Adds a module and its dependencies to the list of dependencies.
Top-level entry point for adding a module and its dependecies.
def add_dependencies(self, module):
"""
Adds a module and its dependencies to the list of dependencies.
Top-level entry point for adding a module and its depe... |
See if a module should be included or excluded based upon
included_packages and excluded_packages.
As some packages have the following format:
scipy.special.specfun
scipy.linalg
Where the top-level package name is just a prefix to a longer package name,
we don't want t... |
Adds a module to the list of dependencies
without handling the modules dependences.
Modules in site-packages are excluded from being added into
the toolkit. This mimics dill.
def _add_dependency(self, module, mn):
"""
Adds a module to the list of dependencies
without ha... |
Returns a dictionary of all settings set for this object, including
any values of its parents or hardcoded defaults.
def freeze(self) -> dict:
"""
Returns a dictionary of all settings set for this object, including
any values of its parents or hardcoded defaults.
"""
set... |
Get a setting specified by key ``key``. Normally, settings are strings, but
if you put non-strings into the settings object, you can request unserialization
by specifying ``as_type``. If the key does not have a harcdoded default type,
omitting ``as_type`` always will get you a string.
I... |
Stores a setting to the database of its object.
The write to the database is performed immediately and the cache in the cache backend is flushed.
The cache within this object will be updated correctly.
def set(self, key: str, value: Any) -> None:
"""
Stores a setting to the da... |
Deletes a setting from this object's storage.
The write to the database is performed immediately and the cache in the cache backend is flushed.
The cache within this object will be updated correctly.
def delete(self, key: str) -> None:
"""
Deletes a setting from this object's s... |
Retrieves the VCAP Services information from the `ConfigParams.VCAP_SERVICES` field in the config object. If
`vcap_services` is not specified, it takes the information from VCAP_SERVICES environment variable.
Args:
vcap_services (str): Try to parse as a JSON string, otherwise, try open it as a file.
... |
Retrieves the credentials of the VCAP Service of the specified `service_name`. If
`service_name` is not specified, it takes the information from STREAMING_ANALYTICS_SERVICE_NAME environment
variable.
Args:
vcap_services (dict): A dict representation of the VCAP Services information.
servic... |
Retrieves the Streams REST API URL from the provided credentials.
Args:
session (:py:class:`requests.Session`): A Requests session object for making REST calls
credentials (dict): A dict representation of the credentials.
Returns:
str: The remote Streams REST API URL.
def _get_rest_api_... |
Retrieves the Streams REST API URL from the provided credentials using iam authentication.
Args:
rest_client (:py:class:`rest_primitives._IAMStreamsRestClient`): A client for making REST calls using IAM authentication
credentials (dict): A dict representation of the credentials.
Returns:
... |
str: Root URL for IBM Streams REST API
def resource_url(self):
"""str: Root URL for IBM Streams REST API"""
self._resource_url = self._resource_url or st.get_rest_api()
return self._resource_url |
Get a single element matching an id
def _get_element_by_id(self, resource_name, eclass, id):
"""Get a single element matching an id"""
elements = self._get_elements(resource_name, eclass, id=id)
if not elements:
raise ValueError("No resource matching: {0}".format(id))
if len... |
Retrieves available domains.
Returns:
:py:obj:`list` of :py:class:`~.rest_primitives.Domain`: List of available domains
def get_domains(self):
"""Retrieves available domains.
Returns:
:py:obj:`list` of :py:class:`~.rest_primitives.Domain`: List of available domains
... |
Retrieves a list of all known Streams high-level REST resources.
Returns:
:py:obj:`list` of :py:class:`~.rest_primitives.RestResource`: List of all Streams high-level REST resources.
def get_resources(self):
"""Retrieves a list of all known Streams high-level REST resources.
Retur... |
Create a connection to a Streaming Analytics service.
The single service is defined by `service_def` which can be one of
* The `service credentials` copied from the `Service credentials` page of the service console (not the Streams console). Credentials are provided in JSON format. They contain ... |
str: Root URL for IBM Streams REST API
def resource_url(self):
"""str: Root URL for IBM Streams REST API"""
if self._iam:
self._resource_url = self._resource_url or _get_iam_rest_api_url_from_creds(self.rest_client, self.credentials)
else:
self._resource_url = self._reso... |
Verify 2-legged oauth request. Parameters accepted as
values in the "Authorization" header, as a GET request parameter,
or in a POST body.
def is_authenticated(self, request, **kwargs):
"""
Verify 2-legged oauth request. Parameters accepted as
values in the "Authorization" heade... |
The required scope is either a string or an iterable. If string,
check if it is allowed for our access token otherwise, iterate through
the required_scopes to see which scopes are allowed
def check_scope(self, token, request):
http_method = request.method
if not hasattr(self, http_metho... |
Check if input matches type: renderer.eightbit.
def _is_args_eightbit(*args) -> bool:
"""
Check if input matches type: renderer.eightbit.
"""
if not args:
return False
elif args[0] is 0:
return True
elif isinstance(args[0], int):
return True
else:
return Fa... |
Export color register as dict.
def as_dict(self) -> Dict[str, str]:
"""
Export color register as dict.
"""
items: Dict[str, str] = {}
for k, v in self.items():
if type(v) is str:
items.update({k: v})
return items |
Export color register as namedtuple.
def as_namedtuple(self):
"""
Export color register as namedtuple.
"""
d = self.as_dict()
return namedtuple('ColorRegister', d.keys())(*d.values()) |
Extracts attributes for an image. n is the index where the
attributes begin. Extracted elements are deleted from the element
list x. Attrs are returned in pandoc format.
def _extract_attrs(x, n):
"""Extracts attributes for an image. n is the index where the
attributes begin. Extracted elements are... |
Processes the figure. Returns a dict containing figure properties.
def _process_figure(value, fmt):
"""Processes the figure. Returns a dict containing figure properties."""
# pylint: disable=global-statement
global Nreferences # Global references counter
global has_unnumbered_figures # ... |
Processes the figures.
def process_figures(key, value, fmt, meta): # pylint: disable=unused-argument
"""Processes the figures."""
global has_unnumbered_figures # pylint: disable=global-statement
# Process figures wrapped in Para elements
if key == 'Para' and len(value) == 1 and \
value[0]['t']... |
Filters the document AST.
def main():
"""Filters the document AST."""
# pylint: disable=global-statement
global PANDOCVERSION
global Image
# Get the output format and document
fmt = args.fmt
doc = json.loads(STDIN.read())
# Initialize pandocxnos
# pylint: disable=too-many-functio... |
Displays the i18n JavaScript that the Django admin requires.
This takes into account the USE_I18N setting. If it's set to False, the
generated JavaScript will be leaner and faster.
def i18n_javascript(self, request):
"""
Displays the i18n JavaScript that the Django admin requires.
... |
Turns a (optionally nested) list of FileNode objects into a list of
strings, linking to the associated files.
def file_links(items, opts=None):
"""
Turns a (optionally nested) list of FileNode objects into a list of
strings, linking to the associated files.
"""
result = []
kwargs = get_kwargs_for_file_link(op... |
Temporarily decreases the `level` attribute of all search results in
order to prevent indendation when displaying them.
def get_results(self, request):
"""
Temporarily decreases the `level` attribute of all search results in
order to prevent indendation when displaying them.
"""... |
Write your forwards methods here.
def forwards(self, orm):
"Write your forwards methods here."
for node in orm.FileNode.objects.all():
node.save() |
Returns the MediaBackend subclass that is configured for use with
media_tree.
def get_media_backend(fail_silently=True, handles_media_types=None,
handles_file_extensions=None, supports_thumbnails=None):
"""
Returns the MediaBackend subclass that is configured for use with
media_t... |
Returns a pre-configured thumbnail size, or assigns it to a context
variable.
Basic tag syntax::
{% thumbnail_size [size_name] [as var_name] %}
The ``size`` parameter can be any of the size names configured using the
setting ``MEDIA_TREE_THUMBNAIL_SIZES``. If omitted, the default size... |
method - HTTP method. e.g. get, put, post, etc.
path - Path to resource. e.g. /loss_sets/1234
params - Parameter to pass in the query string
data - Dictionary of parameters to pass in the request body
def request(method, path, params=None, data=None, auto_retry=True):
"""
method - HTTP method. e.g.... |
Returns the length in bytes of a given file object.
Necessary because os.fstat only works on real files and not file-like
objects. This works on more types of streams, primarily StringIO.
def file_length(file_obj):
"""
Returns the length in bytes of a given file object.
Necessary because os.fstat o... |
Generator to read a file piece by piece.
def read_in_chunks(file_obj, chunk_size):
"""Generator to read a file piece by piece."""
offset = 0
while True:
data = file_obj.read(chunk_size)
if not data:
break
yield data, offset
offset += len(data) |
Parses an Analyze Re href into collection name and ID
def parse_href(href):
"""Parses an Analyze Re href into collection name and ID"""
url = urlparse(href)
path = url.path.split('/')
collection_name = path[1]
id_ = path[2]
return collection_name, id_ |
Takes a value or list of values and returns a single result, joined by ","
if necessary.
def vectorize(values):
"""
Takes a value or list of values and returns a single result, joined by ","
if necessary.
"""
if isinstance(values, list):
return ','.join(str(v) for v in values)
retur... |
This function is for url encoding.
Takes a value or a tuple or list of tuples and returns a single result,
tuples are joined by "," if necessary, elements in tuple are joined by '_'
def vectorize_range(values):
"""
This function is for url encoding.
Takes a value or a tuple or list of tuples and re... |
Creates labels which represent the tree level of each node when
generating option labels.
def label_from_instance(self, obj):
"""
Creates labels which represent the tree level of each node when
generating option labels.
"""
return u'%s %s %i' % (self.level_indicator * (g... |
Accepts a file-like object or string and uploads it. Files are
automatically uploaded in chunks. The default chunk size is 16MiB and
can be overwritten by specifying the number of bytes in the
``chunk_size`` variable.
Accepts an optional poll_interval for temporarily overriding the
... |
Deletes orphaned files, i.e. media files existing in storage that are not in the database.
def delete_orphaned_files(modeladmin, request, queryset=None):
"""
Deletes orphaned files, i.e. media files existing in storage that are not in the database.
"""
execute = request.POST.get('execute')
... |
Rebuilds whole tree in database using `parent` link.
def rebuild_tree(modeladmin, request, queryset=None):
"""
Rebuilds whole tree in database using `parent` link.
"""
tree = FileNode.tree.rebuild()
messages.success(request, message=_('The node tree was rebuilt.'))
return HttpResponseRedirect('... |
Clears media cache files such as thumbnails.
def clear_cache(modeladmin, request, queryset=None):
"""
Clears media cache files such as thumbnails.
"""
execute = request.POST.get('execute')
files_in_storage = []
storage = get_media_storage()
cache_files_choices = []
for storage... |
Returns a suitable description of this field for South.
def south_field_triple(self):
"Returns a suitable description of this field for South."
from south.modelsinspector import introspector
field_class = "django.db.models.fields.CharField"
args, kwargs = introspector(self)
retu... |
Auto-discover INSTALLED_APPS media_extensions.py modules and fail silently when
not present. This forces an import on them to register any media extension bits
they may want.
Rip of django.contrib.admin.autodiscover()
def autodiscover_media_extensions():
"""
Auto-discover INSTALLED_APPS media_exte... |
Similar to os.path.slittext(), but with special handling for files with multiple extensions,
such as "archive.tar.gz": Returns a list containg three elements, the first being the
name without any extensions (taking into account hidden files/leading periods),
the second being the "full" extension, the third ... |
Joins two strings, optionally escaping the second, and using one of two
string formats for glueing them together, depending on whether a condition
is True or False.
This function is a shorthand for complicated code blocks when you want to
format some strings and link them together. A typical use case m... |
Does the same like Django's `widthratio` template tag (scales max_width to factor value/max_value)
def widthratio(value, max_value, max_width):
"""
Does the same like Django's `widthratio` template tag (scales max_width to factor value/max_value)
"""
ratio = float(value) / float(max_value)
return i... |
Find metadata tree root, detect format version
def _initialize(self, path):
""" Find metadata tree root, detect format version """
# Find the tree root
root = os.path.abspath(path)
try:
while ".fmf" not in next(os.walk(root))[1]:
if root == "/":
... |
Merge parent data
def merge(self, parent=None):
""" Merge parent data """
# Check parent, append source files
if parent is None:
parent = self.parent
if parent is None:
return
self.sources = parent.sources + self.sources
# Merge child data with pa... |
Apply inheritance
def inherit(self):
""" Apply inheritance """
# Preserve original data and merge parent
# (original data needed for custom inheritance extensions)
self.original_data = self.data
self.merge()
log.debug("Data for '{0}' inherited.".format(self))
log... |
Update metadata, handle virtual hierarchy
def update(self, data):
""" Update metadata, handle virtual hierarchy """
# Nothing to do if no data
if data is None:
return
for key, value in sorted(data.items()):
# Handle child attributes
if key.startswith(... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.