sentence1 stringlengths 52 3.87M | sentence2 stringlengths 1 47.2k | label stringclasses 1
value |
|---|---|---|
def log_to_raw_structure(execution_history_items):
"""
:param dict execution_history_items: history items, in the simplest case
directly the opened shelve log file
:return: start_item, the StateMachineStartItem of the log file
previous, a dict mapping history_item_id --> history_item... | :param dict execution_history_items: history items, in the simplest case
directly the opened shelve log file
:return: start_item, the StateMachineStartItem of the log file
previous, a dict mapping history_item_id --> history_item_id of previous history item
next_, a dict mapping... | entailment |
def log_to_collapsed_structure(execution_history_items, throw_on_pickle_error=True,
include_erroneous_data_ports=False, full_next=False):
"""
Collapsed structure means that all history items belonging to the same state execution are
merged together into one object (e.g. CallIt... | Collapsed structure means that all history items belonging to the same state execution are
merged together into one object (e.g. CallItem and ReturnItem of an ExecutionState). This
is based on the log structure in which all Items which belong together have the same run_id.
The collapsed items hold input as ... | entailment |
def log_to_DataFrame(execution_history_items, data_in_columns=[], data_out_columns=[], scoped_in_columns=[],
scoped_out_columns=[], semantic_data_columns=[], throw_on_pickle_error=True):
"""
Returns all collapsed items in a table-like structure (pandas.DataFrame) with one row per executed
... | Returns all collapsed items in a table-like structure (pandas.DataFrame) with one row per executed
state and a set of properties resp. columns (e.g. state_name, outcome, run_id) for this state.
The data flow (data_in/out, scoped_data_in/out, semantic_data) is omitted from this table
representation by defau... | entailment |
def log_to_ganttplot(execution_history_items):
"""
Example how to use the DataFrame representation
"""
import matplotlib.pyplot as plt
import matplotlib.dates as dates
import numpy as np
d = log_to_DataFrame(execution_history_items)
# de-duplicate states and make mapping from state to ... | Example how to use the DataFrame representation | entailment |
def call_gui_callback(callback, *args, **kwargs):
"""Wrapper method for GLib.idle_add
This method is intended as replacement for idle_add. It wraps the method with a callback option. The advantage is
that this way, the call is blocking. The method return, when the callback method has been called and execut... | Wrapper method for GLib.idle_add
This method is intended as replacement for idle_add. It wraps the method with a callback option. The advantage is
that this way, the call is blocking. The method return, when the callback method has been called and executed.
:param callback: The callback method, e.g. on_op... | entailment |
def create_tab_header_label(tab_name, icons):
"""Create the tab header labels for notebook tabs. If USE_ICONS_AS_TAB_LABELS is set to True in the gui_config,
icons are used as headers. Otherwise, the titles of the tabs are rotated by 90 degrees.
:param tab_name: The label text of the tab, written in small ... | Create the tab header labels for notebook tabs. If USE_ICONS_AS_TAB_LABELS is set to True in the gui_config,
icons are used as headers. Otherwise, the titles of the tabs are rotated by 90 degrees.
:param tab_name: The label text of the tab, written in small letters and separated by underscores, e.g. states_tre... | entailment |
def create_button_label(icon, font_size=constants.FONT_SIZE_NORMAL):
"""Create a button label with a chosen icon.
:param icon: The icon
:param font_size: The size of the icon
:return: The created label
"""
label = Gtk.Label()
set_label_markup(label, '&#x' + icon + ';', constants.ICON_FONT, ... | Create a button label with a chosen icon.
:param icon: The icon
:param font_size: The size of the icon
:return: The created label | entailment |
def get_widget_title(tab_label_text):
"""Transform Notebook tab label to title by replacing underscores with white spaces and capitalizing the first
letter of each word.
:param tab_label_text: The string of the tab label to be transformed
:return: The transformed title as a string
"""
title = '... | Transform Notebook tab label to title by replacing underscores with white spaces and capitalizing the first
letter of each word.
:param tab_label_text: The string of the tab label to be transformed
:return: The transformed title as a string | entailment |
def get_notebook_tab_title(notebook, page_num):
"""Helper function that gets a notebook's tab title given its page number
:param notebook: The GTK notebook
:param page_num: The page number of the tab, for which the title is required
:return: The title of the tab
"""
child = notebook.get_nth_pag... | Helper function that gets a notebook's tab title given its page number
:param notebook: The GTK notebook
:param page_num: The page number of the tab, for which the title is required
:return: The title of the tab | entailment |
def set_notebook_title(notebook, page_num, title_label):
"""Set the title of a GTK notebook to one of its tab's titles
:param notebook: The GTK notebook
:param page_num: The page number of a specific tab
:param title_label: The GTK label holding the notebook's title
:return: The new title of the no... | Set the title of a GTK notebook to one of its tab's titles
:param notebook: The GTK notebook
:param page_num: The page number of a specific tab
:param title_label: The GTK label holding the notebook's title
:return: The new title of the notebook | entailment |
def create_menu_box_with_icon_and_label(label_text):
""" Creates a MenuItem box, which is a replacement for the former ImageMenuItem. The box contains, a label
for the icon and one for the text.
:param label_text: The text, which is displayed for the text label
:return:
"""
box = Gtk.Box.ne... | Creates a MenuItem box, which is a replacement for the former ImageMenuItem. The box contains, a label
for the icon and one for the text.
:param label_text: The text, which is displayed for the text label
:return: | entailment |
def set_window_size_and_position(window, window_key):
"""Adjust GTK Window's size, position and maximized state according to the corresponding values in the
runtime_config file. The maximize method is triggered last to restore also the last stored size and position of the
window. If the runtime_config does ... | Adjust GTK Window's size, position and maximized state according to the corresponding values in the
runtime_config file. The maximize method is triggered last to restore also the last stored size and position of the
window. If the runtime_config does not exist, or the corresponding values are missing in the fil... | entailment |
def react_to_event(view, widget, event):
"""Checks whether the widget is supposed to react to passed event
The function is intended for callback methods registering to shortcut actions. As several widgets can register to
the same shortcut, only the one having the focus should react to it.
:param gtkmv... | Checks whether the widget is supposed to react to passed event
The function is intended for callback methods registering to shortcut actions. As several widgets can register to
the same shortcut, only the one having the focus should react to it.
:param gtkmvc3.View view: The view in which the widget is re... | entailment |
def is_event_of_key_string(event, key_string):
"""Condition check if key string represent the key value of handed event and whether the event is of right type
The function checks for constructed event tuple that are generated by the rafcon.gui.shortcut_manager.ShortcutManager.
:param tuple event: Event tup... | Condition check if key string represent the key value of handed event and whether the event is of right type
The function checks for constructed event tuple that are generated by the rafcon.gui.shortcut_manager.ShortcutManager.
:param tuple event: Event tuple generated by the ShortcutManager
:param str key... | entailment |
def register_view(self, view):
"""Called when the View was registered"""
super(TopToolBarController, self).register_view(view)
view['maximize_button'].connect('clicked', self.on_maximize_button_clicked)
self.update_maximize_button() | Called when the View was registered | entailment |
def register_view(self, view):
"""Called when the View was registered"""
super(TopToolBarUndockedWindowController, self).register_view(view)
view['redock_button'].connect('clicked', self.on_redock_button_clicked) | Called when the View was registered | entailment |
def register_view(self, view):
"""Called when the View was registered
Can be used e.g. to connect signals. Here, the destroy signal is connected to close the application
"""
super(SingleWidgetWindowController, self).register_view(view)
self.shortcut_manager = ShortcutManager(sel... | Called when the View was registered
Can be used e.g. to connect signals. Here, the destroy signal is connected to close the application | entailment |
def avoid_parallel_execution(func):
"""A decorator to avoid the parallel execution of a function.
If the function is currently called, the second call is just skipped.
:param func: The function to decorate
:return:
"""
def func_wrapper(*args, **kwargs):
if not getattr(func, "currently_... | A decorator to avoid the parallel execution of a function.
If the function is currently called, the second call is just skipped.
:param func: The function to decorate
:return: | entailment |
def run(self):
""" This defines the sequence of actions that are taken when the library state is executed
It basically just calls the run method of the container state
:return:
"""
self.state_execution_status = StateExecutionStatus.ACTIVE
logger.debug("Entering library s... | This defines the sequence of actions that are taken when the library state is executed
It basically just calls the run method of the container state
:return: | entailment |
def remove_outcome(self, outcome_id, force=False, destroy=True):
"""Overwrites the remove_outcome method of the State class. Prevents user from removing a
outcome from the library state.
For further documentation, look at the State class.
:raises exceptions.NotImplementedError: in any ... | Overwrites the remove_outcome method of the State class. Prevents user from removing a
outcome from the library state.
For further documentation, look at the State class.
:raises exceptions.NotImplementedError: in any case | entailment |
def remove_output_data_port(self, data_port_id, force=False, destroy=True):
"""Overwrites the remove_output_data_port method of the State class. Prevents user from removing a
output data port from the library state.
For further documentation, look at the State class.
:param bool force: ... | Overwrites the remove_output_data_port method of the State class. Prevents user from removing a
output data port from the library state.
For further documentation, look at the State class.
:param bool force: True if the removal should be forced
:raises exceptions.NotImplementedError: in... | entailment |
def library_hierarchy_depth(self):
""" Calculates the library hierarchy depth
Counting starts at the current library state. So if the there is no upper library state the depth is one.
:return: library hierarchy depth
:rtype: int
"""
current_library_hierarchy_dep... | Calculates the library hierarchy depth
Counting starts at the current library state. So if the there is no upper library state the depth is one.
:return: library hierarchy depth
:rtype: int | entailment |
def load(self, config_file=None, path=None):
"""Loads the configuration from a specific file
:param config_file: the name of the config file
:param path: the path to the config file
"""
if config_file is None:
if path is None:
path, config_file = spli... | Loads the configuration from a specific file
:param config_file: the name of the config file
:param path: the path to the config file | entailment |
def register_view(self, view):
"""Called when the View was registered
Can be used e.g. to connect signals. Here, the destroy signal is connected to close the application
"""
super(StateEditorController, self).register_view(view)
view.prepare_the_labels() # the preparation of th... | Called when the View was registered
Can be used e.g. to connect signals. Here, the destroy signal is connected to close the application | entailment |
def state_type_changed(self, model, prop_name, info):
"""Reopen state editor when state type is changed
When the type of the observed state changes, a new model is created. The look of this controller's view
depends on the kind of model. Therefore, we have to destroy this editor and open a new ... | Reopen state editor when state type is changed
When the type of the observed state changes, a new model is created. The look of this controller's view
depends on the kind of model. Therefore, we have to destroy this editor and open a new one with the new model. | entailment |
def state_destruction(self, model, prop_name, info):
""" Close state editor when state is being destructed """
import rafcon.gui.singleton as gui_singletons
states_editor_ctrl = gui_singletons.main_window_controller.get_controller('states_editor_ctrl')
state_identifier = states_editor_ct... | Close state editor when state is being destructed | entailment |
def prepare_destruction(self):
"""Prepares the model for destruction
Unregister itself as observer from the state machine and the root state
"""
if self.state_machine is None:
logger.verbose("Multiple calls of prepare destruction for {0}".format(self))
self.destructi... | Prepares the model for destruction
Unregister itself as observer from the state machine and the root state | entailment |
def meta_changed(self, model, prop_name, info):
"""When the meta was changed, we have to set the dirty flag, as the changes are unsaved"""
self.state_machine.marked_dirty = True
msg = info.arg
if model is not self and msg.change.startswith('sm_notification_'): # Signal was caused by the... | When the meta was changed, we have to set the dirty flag, as the changes are unsaved | entailment |
def action_signal_triggered(self, model, prop_name, info):
"""When the action was performed, we have to set the dirty flag, as the changes are unsaved"""
# print("ACTION_signal_triggered state machine: ", model, prop_name, info)
self.state_machine.marked_dirty = True
msg = info.arg
... | When the action was performed, we have to set the dirty flag, as the changes are unsaved | entailment |
def get_state_model_by_path(self, path):
"""Returns the `StateModel` for the given `path`
Searches a `StateModel` in the state machine, who's path is given by `path`.
:param str path: Path of the searched state
:return: The state with that path
:rtype: StateMo... | Returns the `StateModel` for the given `path`
Searches a `StateModel` in the state machine, who's path is given by `path`.
:param str path: Path of the searched state
:return: The state with that path
:rtype: StateModel
:raises: ValueError, if path is invalid/... | entailment |
def load_meta_data(self, path=None, recursively=True):
"""Load meta data of state machine model from the file system
The meta data of the state machine model is loaded from the file system and stored in the meta property of the
model. Existing meta data is removed. Also the meta data of root st... | Load meta data of state machine model from the file system
The meta data of the state machine model is loaded from the file system and stored in the meta property of the
model. Existing meta data is removed. Also the meta data of root state and children is loaded.
:param str path: Optional pat... | entailment |
def store_meta_data(self, copy_path=None):
"""Save meta data of the state machine model to the file system
This method generates a dictionary of the meta data of the state machine and stores it on the filesystem.
:param str copy_path: Optional, if the path is specified, it will be used instead... | Save meta data of the state machine model to the file system
This method generates a dictionary of the meta data of the state machine and stores it on the filesystem.
:param str copy_path: Optional, if the path is specified, it will be used instead of the file system path | entailment |
def convert_trees(self, ptb_trees, representation='basic', universal=True,
include_punct=True, include_erased=False, **kwargs):
"""Convert a list of Penn Treebank formatted strings (ptb_trees)
into Stanford Dependencies. The dependencies are represented
as a list of sentenc... | Convert a list of Penn Treebank formatted strings (ptb_trees)
into Stanford Dependencies. The dependencies are represented
as a list of sentences (CoNLL.Corpus), where each sentence
(CoNLL.Sentence) is itself a list of CoNLL.Token objects.
Currently supported representations are 'basic'... | entailment |
def setup_and_get_default_path(self, jar_base_filename):
"""Determine the user-specific install path for the Stanford
Dependencies jar if the jar_url is not specified and ensure that
it is writable (that is, make sure the directory exists). Returns
the full path for where the jar file sh... | Determine the user-specific install path for the Stanford
Dependencies jar if the jar_url is not specified and ensure that
it is writable (that is, make sure the directory exists). Returns
the full path for where the jar file should be installed. | entailment |
def download_if_missing(self, version=None, verbose=True):
"""Download the jar for version into the jar_filename specified
in the constructor. Will not overwrite jar_filename if it already
exists. version defaults to DEFAULT_CORENLP_VERSION (ideally the
latest but we can't guarantee that... | Download the jar for version into the jar_filename specified
in the constructor. Will not overwrite jar_filename if it already
exists. version defaults to DEFAULT_CORENLP_VERSION (ideally the
latest but we can't guarantee that since PyStanfordDependencies
is distributed separately). | entailment |
def _raise_on_bad_representation(representation):
"""Ensure that representation is a known Stanford Dependency
representation (raises a ValueError if the representation is
invalid)."""
if representation not in REPRESENTATIONS:
repr_desc = ', '.join(map(repr, REPRESENTATIONS))... | Ensure that representation is a known Stanford Dependency
representation (raises a ValueError if the representation is
invalid). | entailment |
def _raise_on_bad_jar_filename(jar_filename):
"""Ensure that jar_filename is a valid path to a jar file."""
if jar_filename is None:
return
if not isinstance(jar_filename, string_type):
raise TypeError("jar_filename is not a string: %r" % jar_filename)
if not os... | Ensure that jar_filename is a valid path to a jar file. | entailment |
def get_jar_url(version=None):
"""Get the URL to a Stanford CoreNLP jar file with a specific
version. These jars come from Maven since the Maven version is
smaller than the full CoreNLP distributions. Defaults to
DEFAULT_CORENLP_VERSION."""
if version is None:
version... | Get the URL to a Stanford CoreNLP jar file with a specific
version. These jars come from Maven since the Maven version is
smaller than the full CoreNLP distributions. Defaults to
DEFAULT_CORENLP_VERSION. | entailment |
def get_instance(jar_filename=None, version=None,
download_if_missing=True, backend='jpype',
**extra_args):
"""This is the typical mechanism of constructing a
StanfordDependencies instance. The backend parameter determines
which backend to load (currentl... | This is the typical mechanism of constructing a
StanfordDependencies instance. The backend parameter determines
which backend to load (currently can be 'subprocess' or 'jpype').
To determine which jar file is used, you must specify
jar_filename, download_if_missing=True, and/or version.... | entailment |
def convert_tree(self, ptb_tree, representation='basic',
include_punct=True, include_erased=False,
add_lemmas=False, universal=True):
"""Arguments are as in StanfordDependencies.convert_trees but with
the addition of add_lemmas. If add_lemmas=True, we will run t... | Arguments are as in StanfordDependencies.convert_trees but with
the addition of add_lemmas. If add_lemmas=True, we will run the
Stanford CoreNLP lemmatizer and fill in the lemma field. | entailment |
def stem(self, form, tag):
"""Returns the stem of word with specific form and part-of-speech
tag according to the Stanford lemmatizer. Lemmas are cached."""
key = (form, tag)
if key not in self.lemma_cache:
lemma = self.stemmer(*key).word()
self.lemma_cache[key] =... | Returns the stem of word with specific form and part-of-speech
tag according to the Stanford lemmatizer. Lemmas are cached. | entailment |
def _get_deps(self, tree, include_punct, representation, universal):
"""Get a list of dependencies from a Stanford Tree for a specific
Stanford Dependencies representation."""
if universal:
converter = self.universal_converter
if self.universal_converter == self.converte... | Get a list of dependencies from a Stanford Tree for a specific
Stanford Dependencies representation. | entailment |
def _listify(collection):
"""This is a workaround where Collections are no longer iterable
when using JPype."""
new_list = []
for index in range(len(collection)):
new_list.append(collection[index])
return new_list | This is a workaround where Collections are no longer iterable
when using JPype. | entailment |
def as_conll(self):
"""Represent this Token as a line as a string in CoNLL-X format."""
def get(field):
value = getattr(self, field)
if value is None:
value = '_'
elif field == 'feats':
value = '|'.join(value)
return str(val... | Represent this Token as a line as a string in CoNLL-X format. | entailment |
def from_conll(this_class, text):
"""Construct a Token from a line in CoNLL-X format."""
fields = text.split('\t')
fields[0] = int(fields[0]) # index
fields[6] = int(fields[6]) # head index
if fields[5] != '_': # feats
fields[5] = tuple(fields[5].split('|'))
f... | Construct a Token from a line in CoNLL-X format. | entailment |
def renumber(self):
"""Destructively renumber the indices based on the actual tokens
(e.g., if there are gaps between token indices, this will remove
them). Old Token objects will still exist, so you'll need to
update your references."""
mapping = {0: 0} # old index -> real index... | Destructively renumber the indices based on the actual tokens
(e.g., if there are gaps between token indices, this will remove
them). Old Token objects will still exist, so you'll need to
update your references. | entailment |
def as_asciitree(self, str_func=None):
"""Represent this Sentence as an ASCII tree string. Requires
the asciitree package. A default token stringifier is provided
but for custom formatting, specify a str_func which should take
a single Token and return a string."""
import asciitr... | Represent this Sentence as an ASCII tree string. Requires
the asciitree package. A default token stringifier is provided
but for custom formatting, specify a str_func which should take
a single Token and return a string. | entailment |
def as_dotgraph(self, digraph_kwargs=None, id_prefix=None,
node_formatter=None, edge_formatter=None):
"""Returns this sentence as a graphviz.Digraph. Requires the
graphviz Python package and graphviz itself. There are several
ways to customize. Graph level keyword arguments c... | Returns this sentence as a graphviz.Digraph. Requires the
graphviz Python package and graphviz itself. There are several
ways to customize. Graph level keyword arguments can be passed
as a dictionary to digraph_kwargs. If you're viewing multiple
Sentences in the same graph, you'll need t... | entailment |
def from_conll(this_class, stream):
"""Construct a Sentence. stream is an iterable over strings where
each string is a line in CoNLL-X format. If there are multiple
sentences in this stream, we only return the first one."""
stream = iter(stream)
sentence = this_class()
fo... | Construct a Sentence. stream is an iterable over strings where
each string is a line in CoNLL-X format. If there are multiple
sentences in this stream, we only return the first one. | entailment |
def from_stanford_dependencies(this_class, stream, tree,
include_erased=False, include_punct=True):
"""Construct a Sentence. stream is an iterable over strings
where each string is a line representing a Stanford Dependency
as in the output of the command line S... | Construct a Sentence. stream is an iterable over strings
where each string is a line representing a Stanford Dependency
as in the output of the command line Stanford Dependency tool:
deprel(gov-index, dep-depindex)
The corresponding Penn Treebank formatted tree must be provided
... | entailment |
def from_conll(this_class, stream):
"""Construct a Corpus. stream is an iterable over strings where
each string is a line in CoNLL-X format."""
stream = iter(stream)
corpus = this_class()
while 1:
# read until we get an empty sentence
sentence = Sentence.f... | Construct a Corpus. stream is an iterable over strings where
each string is a line in CoNLL-X format. | entailment |
def from_stanford_dependencies(this_class, stream, trees,
include_erased=False, include_punct=True):
"""Construct a Corpus. stream is an iterable over strings where
each string is a line representing a Stanford Dependency as in
the output of the command line St... | Construct a Corpus. stream is an iterable over strings where
each string is a line representing a Stanford Dependency as in
the output of the command line Stanford Dependency tool:
deprel(gov-index, dep-depindex)
Sentences are separated by blank lines. A corresponding list of
... | entailment |
def convert_trees(self, ptb_trees, representation='basic',
include_punct=True, include_erased=False, universal=True,
debug=False):
"""Convert a list of Penn Treebank formatted trees (ptb_trees)
into Stanford Dependencies. The dependencies are represented
... | Convert a list of Penn Treebank formatted trees (ptb_trees)
into Stanford Dependencies. The dependencies are represented
as a list of sentences, where each sentence is itself a list of
Token objects.
Currently supported representations are 'basic', 'collapsed',
'CCprocessed', an... | entailment |
def endpoint_from_name(endpoint_name):
"""The object used for interacting with the named relations, or None.
"""
if endpoint_name is None:
return None
factory = relation_factory(endpoint_name)
if factory:
return factory.from_name(endpoint_name) | The object used for interacting with the named relations, or None. | entailment |
def endpoint_from_flag(flag):
"""The object used for interacting with relations tied to a flag, or None.
"""
relation_name = None
value = _get_flag_value(flag)
if isinstance(value, dict) and 'relation' in value:
# old-style RelationBase
relation_name = value['relation']
elif flag... | The object used for interacting with relations tied to a flag, or None. | entailment |
def relation_factory(relation_name):
"""Get the RelationFactory for the given relation name.
Looks for a RelationFactory in the first file matching:
``$CHARM_DIR/hooks/relations/{interface}/{provides,requires,peer}.py``
"""
role, interface = hookenv.relation_to_role_and_interface(relation_name)
... | Get the RelationFactory for the given relation name.
Looks for a RelationFactory in the first file matching:
``$CHARM_DIR/hooks/relations/{interface}/{provides,requires,peer}.py`` | entailment |
def _relation_module(role, interface):
"""
Return module for relation based on its role and interface, or None.
Prefers new location (reactive/relations) over old (hooks/relations).
"""
_append_path(hookenv.charm_dir())
_append_path(os.path.join(hookenv.charm_dir(), 'hooks'))
base_module = ... | Return module for relation based on its role and interface, or None.
Prefers new location (reactive/relations) over old (hooks/relations). | entailment |
def _find_relation_factory(module):
"""
Attempt to find a RelationFactory subclass in the module.
Note: RelationFactory and RelationBase are ignored so they may
be imported to be used as base classes without fear.
"""
if not module:
return None
# All the RelationFactory subclasses
... | Attempt to find a RelationFactory subclass in the module.
Note: RelationFactory and RelationBase are ignored so they may
be imported to be used as base classes without fear. | entailment |
def _migrate_conversations(): # noqa
"""
Due to issue #28 (https://github.com/juju-solutions/charms.reactive/issues/28),
conversations needed to be updated to be namespaced per relation ID for SERVICE
and UNIT scope. To ensure backwards compatibility, this updates all convs in
the old format to th... | Due to issue #28 (https://github.com/juju-solutions/charms.reactive/issues/28),
conversations needed to be updated to be namespaced per relation ID for SERVICE
and UNIT scope. To ensure backwards compatibility, this updates all convs in
the old format to the new.
TODO: Remove in 2.0.0 | entailment |
def relation_call(method, relation_name=None, flag=None, state=None, *args):
"""Invoke a method on the class implementing a relation via the CLI"""
if relation_name:
relation = relation_from_name(relation_name)
if relation is None:
raise ValueError('Relation not found: %s' % relation... | Invoke a method on the class implementing a relation via the CLI | entailment |
def from_flag(cls, flag):
"""
Find relation implementation in the current charm, based on the
name of an active flag.
You should not use this method directly.
Use :func:`endpoint_from_flag` instead.
"""
value = _get_flag_value(flag)
if value is None:
... | Find relation implementation in the current charm, based on the
name of an active flag.
You should not use this method directly.
Use :func:`endpoint_from_flag` instead. | entailment |
def from_name(cls, relation_name, conversations=None):
"""
Find relation implementation in the current charm, based on the
name of the relation.
:return: A Relation instance, or None
"""
if relation_name is None:
return None
relation_class = cls._cach... | Find relation implementation in the current charm, based on the
name of the relation.
:return: A Relation instance, or None | entailment |
def _find_impl(cls, role, interface):
"""
Find relation implementation based on its role and interface.
"""
module = _relation_module(role, interface)
if not module:
return None
return cls._find_subclass(module) | Find relation implementation based on its role and interface. | entailment |
def _find_subclass(cls, module):
"""
Attempt to find subclass of :class:`RelationBase` in the given module.
Note: This means strictly subclasses and not :class:`RelationBase` itself.
This is to prevent picking up :class:`RelationBase` being imported to be
used as the base class.... | Attempt to find subclass of :class:`RelationBase` in the given module.
Note: This means strictly subclasses and not :class:`RelationBase` itself.
This is to prevent picking up :class:`RelationBase` being imported to be
used as the base class. | entailment |
def conversation(self, scope=None):
"""
Get a single conversation, by scope, that this relation is currently handling.
If the scope is not given, the correct scope is inferred by the current
hook execution context. If there is no current hook execution context, it
is assume tha... | Get a single conversation, by scope, that this relation is currently handling.
If the scope is not given, the correct scope is inferred by the current
hook execution context. If there is no current hook execution context, it
is assume that there is only a single global conversation scope for t... | entailment |
def toggle_state(self, state, active=TOGGLE, scope=None):
"""
Toggle the state for the :class:`Conversation` with the given scope.
In Python, this is equivalent to::
relation.conversation(scope).toggle_state(state, active)
See :meth:`conversation` and :meth:`Conversation.t... | Toggle the state for the :class:`Conversation` with the given scope.
In Python, this is equivalent to::
relation.conversation(scope).toggle_state(state, active)
See :meth:`conversation` and :meth:`Conversation.toggle_state`. | entailment |
def set_remote(self, key=None, value=None, data=None, scope=None, **kwdata):
"""
Set data for the remote end(s) of the :class:`Conversation` with the given scope.
In Python, this is equivalent to::
relation.conversation(scope).set_remote(key, value, data, scope, **kwdata)
... | Set data for the remote end(s) of the :class:`Conversation` with the given scope.
In Python, this is equivalent to::
relation.conversation(scope).set_remote(key, value, data, scope, **kwdata)
See :meth:`conversation` and :meth:`Conversation.set_remote`. | entailment |
def get_remote(self, key, default=None, scope=None):
"""
Get data from the remote end(s) of the :class:`Conversation` with the given scope.
In Python, this is equivalent to::
relation.conversation(scope).get_remote(key, default)
See :meth:`conversation` and :meth:`Conversa... | Get data from the remote end(s) of the :class:`Conversation` with the given scope.
In Python, this is equivalent to::
relation.conversation(scope).get_remote(key, default)
See :meth:`conversation` and :meth:`Conversation.get_remote`. | entailment |
def set_local(self, key=None, value=None, data=None, scope=None, **kwdata):
"""
Locally store some data, namespaced by the current or given :class:`Conversation` scope.
In Python, this is equivalent to::
relation.conversation(scope).set_local(data, scope, **kwdata)
See :me... | Locally store some data, namespaced by the current or given :class:`Conversation` scope.
In Python, this is equivalent to::
relation.conversation(scope).set_local(data, scope, **kwdata)
See :meth:`conversation` and :meth:`Conversation.set_local`. | entailment |
def get_local(self, key, default=None, scope=None):
"""
Retrieve some data previously set via :meth:`set_local`.
In Python, this is equivalent to::
relation.conversation(scope).get_local(key, default)
See :meth:`conversation` and :meth:`Conversation.get_local`.
"""... | Retrieve some data previously set via :meth:`set_local`.
In Python, this is equivalent to::
relation.conversation(scope).get_local(key, default)
See :meth:`conversation` and :meth:`Conversation.get_local`. | entailment |
def relation_ids(self):
"""
The set of IDs of the specific relation instances that this conversation
is communicating with.
"""
if self.scope == scopes.GLOBAL:
# the namespace is the relation name and this conv speaks for all
# connected instances of that ... | The set of IDs of the specific relation instances that this conversation
is communicating with. | entailment |
def join(cls, scope):
"""
Get or create a conversation for the given scope and active hook context.
The current remote unit for the active hook context will be added to
the conversation.
Note: This uses :mod:`charmhelpers.core.unitdata` and requires that
:meth:`~charmhe... | Get or create a conversation for the given scope and active hook context.
The current remote unit for the active hook context will be added to
the conversation.
Note: This uses :mod:`charmhelpers.core.unitdata` and requires that
:meth:`~charmhelpers.core.unitdata.Storage.flush` be call... | entailment |
def depart(self):
"""
Remove the current remote unit, for the active hook context, from
this conversation. This should be called from a `-departed` hook.
"""
unit = hookenv.remote_unit()
self.units.remove(unit)
if self.units:
unitdata.kv().set(self.ke... | Remove the current remote unit, for the active hook context, from
this conversation. This should be called from a `-departed` hook. | entailment |
def serialize(cls, conversation):
"""
Serialize a conversation instance for storage.
"""
return {
'namespace': conversation.namespace,
'units': sorted(conversation.units),
'scope': conversation.scope,
} | Serialize a conversation instance for storage. | entailment |
def load(cls, keys):
"""
Load a set of conversations by their keys.
"""
conversations = []
for key in keys:
conversation = unitdata.kv().get(key)
if conversation:
conversations.append(cls.deserialize(conversation))
return conversati... | Load a set of conversations by their keys. | entailment |
def set_state(self, state):
"""
Activate and put this conversation into the given state.
The relation name will be interpolated in the state name, and it is
recommended that it be included to avoid conflicts with states from
other relations. For example::
conversat... | Activate and put this conversation into the given state.
The relation name will be interpolated in the state name, and it is
recommended that it be included to avoid conflicts with states from
other relations. For example::
conversation.set_state('{relation_name}.state')
... | entailment |
def remove_state(self, state):
"""
Remove this conversation from the given state, and potentially
deactivate the state if no more conversations are in it.
The relation name will be interpolated in the state name, and it is
recommended that it be included to avoid conflicts with ... | Remove this conversation from the given state, and potentially
deactivate the state if no more conversations are in it.
The relation name will be interpolated in the state name, and it is
recommended that it be included to avoid conflicts with states from
other relations. For example::... | entailment |
def is_state(self, state):
"""
Test if this conversation is in the given state.
"""
state = state.format(relation_name=self.relation_name)
value = _get_flag_value(state)
if not value:
return False
return self.key in value['conversations'] | Test if this conversation is in the given state. | entailment |
def toggle_state(self, state, active=TOGGLE):
"""
Toggle the given state for this conversation.
The state will be set ``active`` is ``True``, otherwise the state will be removed.
If ``active`` is not given, it will default to the inverse of the current state
(i.e., ``False`` if... | Toggle the given state for this conversation.
The state will be set ``active`` is ``True``, otherwise the state will be removed.
If ``active`` is not given, it will default to the inverse of the current state
(i.e., ``False`` if the state is currently set, ``True`` if it is not; essentially
... | entailment |
def set_remote(self, key=None, value=None, data=None, **kwdata):
"""
Set data for the remote end(s) of this conversation.
Data can be passed in either as a single dict, or as key-word args.
Note that, in Juju, setting relation data is inherently service scoped.
That is, if the ... | Set data for the remote end(s) of this conversation.
Data can be passed in either as a single dict, or as key-word args.
Note that, in Juju, setting relation data is inherently service scoped.
That is, if the conversation only includes a single unit, the data will
still be set for that... | entailment |
def get_remote(self, key, default=None):
"""
Get a value from the remote end(s) of this conversation.
Note that if a conversation's scope encompasses multiple units, then
those units are expected to agree on their data, whether that is through
relying on a single leader to set t... | Get a value from the remote end(s) of this conversation.
Note that if a conversation's scope encompasses multiple units, then
those units are expected to agree on their data, whether that is through
relying on a single leader to set the data or by all units eventually
converging to iden... | entailment |
def set_local(self, key=None, value=None, data=None, **kwdata):
"""
Locally store some data associated with this conversation.
Data can be passed in either as a single dict, or as key-word args.
For example, if you need to store the previous value of a remote field
to determine... | Locally store some data associated with this conversation.
Data can be passed in either as a single dict, or as key-word args.
For example, if you need to store the previous value of a remote field
to determine if it has changed, you can use the following::
prev = conversation.get... | entailment |
def get_local(self, key, default=None):
"""
Retrieve some data previously set via :meth:`set_local` for this conversation.
"""
key = '%s.%s.%s' % (self.key, 'local-data', key)
return unitdata.kv().get(key, default) | Retrieve some data previously set via :meth:`set_local` for this conversation. | entailment |
def set_flag(flag, value=None):
"""set_flag(flag)
Set the given flag as active.
:param str flag: Name of flag to set.
.. note:: **Changes to flags are reset when a handler crashes.** Changes to
flags happen immediately, but they are only persisted at the end of a
complete and successful ... | set_flag(flag)
Set the given flag as active.
:param str flag: Name of flag to set.
.. note:: **Changes to flags are reset when a handler crashes.** Changes to
flags happen immediately, but they are only persisted at the end of a
complete and successful run of the reactive framework. All unpe... | entailment |
def clear_flag(flag):
"""
Clear / deactivate a flag.
:param str flag: Name of flag to set.
.. note:: **Changes to flags are reset when a handler crashes.** Changes to
flags happen immediately, but they are only persisted at the end of a
complete and successful run of the reactive framewo... | Clear / deactivate a flag.
:param str flag: Name of flag to set.
.. note:: **Changes to flags are reset when a handler crashes.** Changes to
flags happen immediately, but they are only persisted at the end of a
complete and successful run of the reactive framework. All unpersisted
changes... | entailment |
def register_trigger(when=None, when_not=None, set_flag=None, clear_flag=None):
"""
Register a trigger to set or clear a flag when a given flag is set.
Note: Flag triggers are handled at the same time that the given flag is set.
:param str when: Flag to trigger on when it is set.
:param str when_n... | Register a trigger to set or clear a flag when a given flag is set.
Note: Flag triggers are handled at the same time that the given flag is set.
:param str when: Flag to trigger on when it is set.
:param str when_not: Flag to trigger on when it is cleared.
:param str set_flag: If given, this flag will... | entailment |
def get_flags():
"""
Return a list of all flags which are set.
"""
flags = unitdata.kv().getrange('reactive.states.', strip=True) or {}
return sorted(flags.keys()) | Return a list of all flags which are set. | entailment |
def dispatch(restricted=False):
"""
Dispatch registered handlers.
When dispatching in restricted mode, only matching hook handlers are executed.
Handlers are dispatched according to the following rules:
* Handlers are repeatedly tested and invoked in iterations, until the system
settles int... | Dispatch registered handlers.
When dispatching in restricted mode, only matching hook handlers are executed.
Handlers are dispatched according to the following rules:
* Handlers are repeatedly tested and invoked in iterations, until the system
settles into quiescence (that is, until no new handlers... | entailment |
def discover():
"""
Discover handlers based on convention.
Handlers will be loaded from the following directories and their subdirectories:
* ``$CHARM_DIR/reactive/``
* ``$CHARM_DIR/hooks/reactive/``
* ``$CHARM_DIR/hooks/relations/``
They can be Python files, in which case they will... | Discover handlers based on convention.
Handlers will be loaded from the following directories and their subdirectories:
* ``$CHARM_DIR/reactive/``
* ``$CHARM_DIR/hooks/reactive/``
* ``$CHARM_DIR/hooks/relations/``
They can be Python files, in which case they will be imported and decorated
... | entailment |
def get(cls, action, suffix=None):
"""
Get or register a handler for the given action.
:param func action: Callback that is called when invoking the Handler
:param func suffix: Optional suffix for the handler's ID
"""
action_id = _action_id(action, suffix)
if act... | Get or register a handler for the given action.
:param func action: Callback that is called when invoking the Handler
:param func suffix: Optional suffix for the handler's ID | entailment |
def add_predicate(self, predicate):
"""
Add a new predicate callback to this handler.
"""
_predicate = predicate
if isinstance(predicate, partial):
_predicate = 'partial(%s, %s, %s)' % (predicate.func, predicate.args, predicate.keywords)
if LOG_OPTS['register'... | Add a new predicate callback to this handler. | entailment |
def _get_args(self):
"""
Lazily evaluate the args.
"""
if not hasattr(self, '_args_evaled'):
# cache the args in case handler is re-invoked due to flags change
self._args_evaled = list(chain.from_iterable(self._args))
return self._args_evaled | Lazily evaluate the args. | entailment |
def invoke(self):
"""
Invoke this handler.
"""
args = self._get_args()
self._action(*args)
for callback in self._post_callbacks:
callback() | Invoke this handler. | entailment |
def register_flags(self, flags):
"""
Register flags as being relevant to this handler.
Relevant flags will be used to determine if the handler should
be re-invoked due to changes in the set of active flags. If this
handler has already been invoked during this :func:`dispatch` r... | Register flags as being relevant to this handler.
Relevant flags will be used to determine if the handler should
be re-invoked due to changes in the set of active flags. If this
handler has already been invoked during this :func:`dispatch` run
and none of its relevant flags have been s... | entailment |
def invoke(self):
"""
Call the external handler to be invoked.
"""
# flush to ensure external process can see flags as they currently
# are, and write flags (flush releases lock)
unitdata.kv().flush()
subprocess.check_call([self._filepath, '--invoke', self._test_o... | Call the external handler to be invoked. | entailment |
def hook(*hook_patterns):
"""
Register the decorated function to run when the current hook matches any of
the ``hook_patterns``.
This decorator is generally deprecated and should only be used when
absolutely necessary.
The hook patterns can use the ``{interface:...}`` and ``{A,B,...}`` syntax
... | Register the decorated function to run when the current hook matches any of
the ``hook_patterns``.
This decorator is generally deprecated and should only be used when
absolutely necessary.
The hook patterns can use the ``{interface:...}`` and ``{A,B,...}`` syntax
supported by :func:`~charms.reacti... | entailment |
def when_file_changed(*filenames, **kwargs):
"""
Register the decorated function to run when one or more files have changed.
:param list filenames: The names of one or more files to check for changes
(a callable returning the name is also accepted).
:param str hash_type: The type of hash to use... | Register the decorated function to run when one or more files have changed.
:param list filenames: The names of one or more files to check for changes
(a callable returning the name is also accepted).
:param str hash_type: The type of hash to use for determining if a file has
changed. Defaults... | entailment |
def not_unless(*desired_flags):
"""
Assert that the decorated function can only be called if the desired_flags
are active.
Note that, unlike :func:`when`, this does **not** trigger the decorated
function if the flags match. It **only** raises an exception if the
function is called when the fla... | Assert that the decorated function can only be called if the desired_flags
are active.
Note that, unlike :func:`when`, this does **not** trigger the decorated
function if the flags match. It **only** raises an exception if the
function is called when the flags do not match.
This is primarily for ... | entailment |
def only_once(action=None):
"""
.. deprecated:: 0.5.0
Use :func:`when_not` in combination with :func:`set_state` instead. This
handler is deprecated because it might actually be
`called multiple times <https://github.com/juju-solutions/charms.reactive/issues/22>`_.
Register the decorat... | .. deprecated:: 0.5.0
Use :func:`when_not` in combination with :func:`set_state` instead. This
handler is deprecated because it might actually be
`called multiple times <https://github.com/juju-solutions/charms.reactive/issues/22>`_.
Register the decorated function to be run once, and only onc... | entailment |
def collect_metrics():
"""
Register the decorated function to run for the collect_metrics hook.
"""
def _register(action):
handler = Handler.get(action)
handler.add_predicate(partial(_restricted_hook, 'collect-metrics'))
return action
return _register | Register the decorated function to run for the collect_metrics hook. | entailment |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.