code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
label = Gtk.Label()
set_label_markup(label, '&#x' + icon + ';', constants.ICON_FONT, font_size)
label.show()
return label | 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 | 4.737273 | 7.045896 | 0.672345 |
title = ''
title_list = tab_label_text.split('_')
for word in title_list:
title += word.upper() + ' '
title.strip()
return title | 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 | 3.09869 | 3.115989 | 0.994448 |
child = notebook.get_nth_page(page_num)
tab_label_eventbox = notebook.get_tab_label(child)
return get_widget_title(tab_label_eventbox.get_tooltip_text()) | 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 | 5.406518 | 5.309458 | 1.018281 |
text = get_notebook_tab_title(notebook, page_num)
set_label_markup(title_label, text, constants.INTERFACE_FONT, constants.FONT_SIZE_BIG, constants.LETTER_SPACING_1PT)
return text | 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 notebook | 7.509992 | 8.755969 | 0.8577 |
box = Gtk.Box.new(Gtk.Orientation.HORIZONTAL, 10)
box.set_border_width(0)
icon_label = Gtk.Label()
text_label = Gtk.AccelLabel.new(label_text)
text_label.set_xalign(0)
box.pack_start(icon_label, False, False, 0)
box.pack_start(text_label, True, True, 0)
return box, icon_label, text... | 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: | 2.068156 | 2.192736 | 0.943185 |
size = global_runtime_config.get_config_value(window_key + '_WINDOW_SIZE')
position = global_runtime_config.get_config_value(window_key + '_WINDOW_POS')
maximized = global_runtime_config.get_config_value(window_key + '_WINDOW_MAXIMIZED')
# un-maximize here on purpose otherwise resize and repositio... | 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 not exist, or the corresponding values are missing in the fil... | 3.037398 | 2.971393 | 1.022213 |
# See
# http://pyGtk.org/pygtk2reference/class-gtkwidget.html#method-gtkwidget--is-focus and
# http://pyGtk.org/pygtk2reference/class-gtkwidget.html#method-gtkwidget--has-focus
# for detailed information about the difference between is_focus() and has_focus()
if not view: # view needs to be in... | 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 gtkmvc3.View view: The view in which the widget is re... | 4.662598 | 4.589172 | 1.016 |
return len(event) >= 2 and not isinstance(event[1], Gdk.ModifierType) and event[0] == Gtk.accelerator_parse(key_string)[0] | 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 tuple generated by the ShortcutManager
:param str key... | 5.098007 | 4.897092 | 1.041027 |
super(TopToolBarController, self).register_view(view)
view['maximize_button'].connect('clicked', self.on_maximize_button_clicked)
self.update_maximize_button() | def register_view(self, view) | Called when the View was registered | 5.036294 | 4.784678 | 1.052588 |
super(TopToolBarUndockedWindowController, self).register_view(view)
view['redock_button'].connect('clicked', self.on_redock_button_clicked) | def register_view(self, view) | Called when the View was registered | 9.102304 | 8.386217 | 1.085389 |
super(SingleWidgetWindowController, self).register_view(view)
self.shortcut_manager = ShortcutManager(self.view['main_window'])
self.register_actions(self.shortcut_manager)
view['main_window'].connect('destroy', Gtk.main_quit) | 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 | 5.378646 | 5.497203 | 0.978433 |
def func_wrapper(*args, **kwargs):
if not getattr(func, "currently_executing", False):
func.currently_executing = True
try:
return func(*args, **kwargs)
finally:
func.currently_executing = False
else:
logger.verbose... | 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: | 2.446574 | 2.796668 | 0.874818 |
self.state_execution_status = StateExecutionStatus.ACTIVE
logger.debug("Entering library state '{0}' with name '{1}'".format(self.library_name, self.name))
# self.state_copy.parent = self.parent
self.state_copy._run_id = self._run_id
self.state_copy.input_data = self.inp... | 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: | 3.028985 | 2.817141 | 1.075198 |
if force:
return State.remove_outcome(self, outcome_id, force, destroy)
else:
raise NotImplementedError("Remove outcome is not implemented for library state {}".format(self)) | 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 case | 5.910231 | 5.440654 | 1.086309 |
if force:
return State.remove_output_data_port(self, data_port_id, force, destroy)
else:
raise NotImplementedError("Remove output data port is not implemented for library state {}".format(self)) | 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: True if the removal should be forced
:raises exceptions.NotImplementedError: in... | 4.609519 | 3.290886 | 1.400692 |
current_library_hierarchy_depth = 1
library_root_state = self.get_next_upper_library_root_state()
while library_root_state is not None:
current_library_hierarchy_depth += 1
library_root_state = library_root_state.parent.get_next_upper_library_root_state()
... | 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 | 2.708348 | 2.436502 | 1.111572 |
if config_file is None:
if path is None:
path, config_file = split(resource_filename(__name__, CONFIG_FILE))
else:
config_file = CONFIG_FILE
super(Config, self).load(config_file, path) | 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 | 3.531987 | 4.012261 | 0.880298 |
super(StateEditorController, self).register_view(view)
view.prepare_the_labels() # the preparation of the labels is done here to take into account plugin hook changes
view['add_input_port_button'].connect('clicked', self.inputs_ctrl.on_add)
view['add_output_port_button'].connec... | 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 | 3.348031 | 3.379374 | 0.990725 |
msg = info['arg']
# print(self.__class__.__name__, "state_type_changed check", info)
if msg.action in ['change_state_type', 'change_root_state_type'] and msg.after:
# print(self.__class__.__name__, "state_type_changed")
import rafcon.gui.singleton as gui_singleto... | 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 one with the new model. | 6.038775 | 5.350435 | 1.128651 |
import rafcon.gui.singleton as gui_singletons
states_editor_ctrl = gui_singletons.main_window_controller.get_controller('states_editor_ctrl')
state_identifier = states_editor_ctrl.get_state_identifier(self.model)
states_editor_ctrl.close_page(state_identifier, delete=True) | def state_destruction(self, model, prop_name, info) | Close state editor when state is being destructed | 6.941753 | 5.956321 | 1.165443 |
if self.state_machine is None:
logger.verbose("Multiple calls of prepare destruction for {0}".format(self))
self.destruction_signal.emit()
if self.history is not None:
self.history.prepare_destruction()
if self.auto_backup is not None:
self.au... | def prepare_destruction(self) | Prepares the model for destruction
Unregister itself as observer from the state machine and the root state | 4.244893 | 3.459887 | 1.226888 |
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 root state
# Emit state_meta_signal to inform observing controllers about changes made to the meta data within the
... | 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 | 17.264606 | 16.710831 | 1.033139 |
# print("ACTION_signal_triggered state machine: ", model, prop_name, info)
self.state_machine.marked_dirty = True
msg = info.arg
if model is not self and msg.action.startswith('sm_notification_'): # Signal was caused by the root state
# Emit state_action_signal to i... | 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 | 7.840683 | 7.596233 | 1.03218 |
path_elements = path.split('/')
path_elements.pop(0)
current_state_model = self.root_state
for state_id in path_elements:
if isinstance(current_state_model, ContainerStateModel):
if state_id in current_state_model.states:
current_s... | 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: StateModel
:raises: ValueError, if path is invalid/... | 2.020073 | 2.077799 | 0.972217 |
meta_data_path = path if path is not None else self.state_machine.file_system_path
if meta_data_path:
path_meta_data = os.path.join(meta_data_path, storage.FILE_NAME_META_DATA)
try:
tmp_meta = storage.load_data_file(path_meta_data)
except Va... | 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 state and children is loaded.
:param str path: Optional pat... | 3.990304 | 3.837542 | 1.039807 |
if copy_path:
meta_file_json = os.path.join(copy_path, storage.FILE_NAME_META_DATA)
else:
meta_file_json = os.path.join(self.state_machine.file_system_path, storage.FILE_NAME_META_DATA)
storage_utils.write_dict_to_json(self.meta, meta_file_json)
self.ro... | 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 of the file system path | 3.101176 | 2.917665 | 1.062896 |
kwargs.update(representation=representation, universal=universal,
include_punct=include_punct,
include_erased=include_erased)
return Corpus(self.convert_tree(ptb_tree, **kwargs)
for ptb_tree in ptb_trees) | 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 sentences (CoNLL.Corpus), where each sentence
(CoNLL.Sentence) is itself a list of CoNLL.Token objects.
Currently supported representations are 'basic'... | 2.343706 | 3.31104 | 0.707846 |
import os
import errno
install_dir = os.path.expanduser(INSTALL_DIR)
try:
os.makedirs(install_dir)
except OSError as ose:
if ose.errno != errno.EEXIST:
raise ose
jar_filename = os.path.join(install_dir, jar_base_filename)
... | 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 should be installed. | 2.225731 | 2.093494 | 1.063166 |
if os.path.exists(self.jar_filename):
return
jar_url = self.get_jar_url(version)
if verbose:
print("Downloading %r -> %r" % (jar_url, self.jar_filename))
opener = ErrorAwareURLOpener()
opener.retrieve(jar_url, filename=self.jar_filename) | 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 since PyStanfordDependencies
is distributed separately). | 2.976841 | 2.659747 | 1.11922 |
if representation not in REPRESENTATIONS:
repr_desc = ', '.join(map(repr, REPRESENTATIONS))
raise ValueError("Unknown representation: %r (should be one "
"of %s)" % (representation, repr_desc)) | def _raise_on_bad_representation(representation) | Ensure that representation is a known Stanford Dependency
representation (raises a ValueError if the representation is
invalid). | 3.349579 | 3.134801 | 1.068514 |
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.path.exists(jar_filename):
raise ValueError("jar_filename does not exist: %r" % jar_filename) | def _raise_on_bad_jar_filename(jar_filename) | Ensure that jar_filename is a valid path to a jar file. | 2.100768 | 1.960079 | 1.071777 |
if version is None:
version = DEFAULT_CORENLP_VERSION
try:
string_type = basestring
except NameError:
string_type = str
if not isinstance(version, string_type):
raise TypeError("Version must be a string or None (got %r)." %
... | 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. | 2.985238 | 2.505481 | 1.191483 |
StanfordDependencies._raise_on_bad_jar_filename(jar_filename)
extra_args.update(jar_filename=jar_filename,
download_if_missing=download_if_missing,
version=version)
if backend == 'jpype':
try:
from .JPypeBac... | 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 (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.... | 2.314744 | 2.245591 | 1.030795 |
self._raise_on_bad_input(ptb_tree)
self._raise_on_bad_representation(representation)
tree = self.treeReader(ptb_tree)
if tree is None:
raise ValueError("Invalid Penn Treebank tree: %r" % ptb_tree)
deps = self._get_deps(tree, include_punct, representation,
... | 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 the
Stanford CoreNLP lemmatizer and fill in the lemma field. | 2.717002 | 2.712055 | 1.001824 |
key = (form, tag)
if key not in self.lemma_cache:
lemma = self.stemmer(*key).word()
self.lemma_cache[key] = lemma
return self.lemma_cache[key] | 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. | 3.558271 | 3.145335 | 1.131285 |
if universal:
converter = self.universal_converter
if self.universal_converter == self.converter:
import warnings
warnings.warn("This jar doesn't support universal "
"dependencies, falling back to Stanford "
... | def _get_deps(self, tree, include_punct, representation, universal) | Get a list of dependencies from a Stanford Tree for a specific
Stanford Dependencies representation. | 4.884078 | 4.555131 | 1.072215 |
new_list = []
for index in range(len(collection)):
new_list.append(collection[index])
return new_list | def _listify(collection) | This is a workaround where Collections are no longer iterable
when using JPype. | 3.062541 | 2.556442 | 1.19797 |
def get(field):
value = getattr(self, field)
if value is None:
value = '_'
elif field == 'feats':
value = '|'.join(value)
return str(value)
return '\t'.join([get(field) for field in FIELD_NAMES]) | def as_conll(self) | Represent this Token as a line as a string in CoNLL-X format. | 3.79736 | 3.306845 | 1.148333 |
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('|'))
fields = [value if value != '_' else None for value in fields]
fields.append(None... | def from_conll(this_class, text) | Construct a Token from a line in CoNLL-X format. | 3.560025 | 3.377145 | 1.054152 |
mapping = {0: 0} # old index -> real index
needs_renumbering = False
for real_index, token in enumerate(self, 1):
mapping[token.index] = real_index
if token.index != real_index:
needs_renumbering = True
if needs_renumbering:
#... | 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. | 3.786036 | 3.319134 | 1.14067 |
import asciitree
from collections import defaultdict
children = defaultdict(list)
# since erased nodes may be missing, multiple tokens may have same
# index (CCprocessed), etc.
token_to_index = {}
roots = []
for token in self:
children... | 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. | 3.904516 | 3.811379 | 1.024437 |
digraph_kwargs = digraph_kwargs or {}
id_prefix = id_prefix or ''
node_formatter = node_formatter or (lambda token: {})
edge_formatter = edge_formatter or (lambda token: {})
import graphviz
graph = graphviz.Digraph(**digraph_kwargs)
# add root node
... | 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 can be passed
as a dictionary to digraph_kwargs. If you're viewing multiple
Sentences in the same graph, you'll need t... | 2.079849 | 1.893537 | 1.098394 |
stream = iter(stream)
sentence = this_class()
for line in stream:
line = line.strip()
if line:
sentence.append(Token.from_conll(line))
elif sentence:
return sentence
return sentence | 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. | 2.936434 | 2.484718 | 1.181798 |
stream = iter(stream)
sentence = this_class()
covered_indices = set()
tags_and_words = ptb_tags_and_words_re.findall(tree)
# perform some basic cleanups
tags_and_words = [(tag, word.replace(r'\/', '/'))
for (tag, word) in tags_and_words ... | 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 Stanford Dependency tool:
deprel(gov-index, dep-depindex)
The corresponding Penn Treebank formatted tree must be provided
... | 2.871253 | 2.900183 | 0.990025 |
stream = iter(stream)
corpus = this_class()
while 1:
# read until we get an empty sentence
sentence = Sentence.from_conll(stream)
if sentence:
corpus.append(sentence)
else:
break
return corpus | 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. | 3.867441 | 3.389801 | 1.140905 |
stream = iter(stream)
corpus = this_class()
for tree in trees:
sentence = Sentence.from_stanford_dependencies(stream,
tree,
include_erased,
... | 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 Stanford Dependency tool:
deprel(gov-index, dep-depindex)
Sentences are separated by blank lines. A corresponding list of
... | 2.873633 | 3.29577 | 0.871916 |
self._raise_on_bad_representation(representation)
input_file = tempfile.NamedTemporaryFile(delete=False)
try:
for ptb_tree in ptb_trees:
self._raise_on_bad_input(ptb_tree)
tree_with_line_break = ptb_tree + "\n"
input_file.write... | 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
as a list of sentences, where each sentence is itself a list of
Token objects.
Currently supported representations are 'basic', 'collapsed',
'CCprocessed', an... | 2.795694 | 2.777072 | 1.006706 |
if endpoint_name is None:
return None
factory = relation_factory(endpoint_name)
if factory:
return factory.from_name(endpoint_name) | def endpoint_from_name(endpoint_name) | The object used for interacting with the named relations, or None. | 4.345373 | 3.134745 | 1.386196 |
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.startswith('endpoint.'):
# new-style Endpoint
relation_name = flag.split('.')[1]
elif '.' i... | def endpoint_from_flag(flag) | The object used for interacting with relations tied to a flag, or None. | 3.566146 | 3.471278 | 1.027329 |
role, interface = hookenv.relation_to_role_and_interface(relation_name)
if not (role and interface):
hookenv.log('Unable to determine role and interface for relation '
'{}'.format(relation_name), hookenv.ERROR)
return None
return _find_relation_factory(_relation_modu... | 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`` | 3.619728 | 3.878629 | 0.933249 |
_append_path(hookenv.charm_dir())
_append_path(os.path.join(hookenv.charm_dir(), 'hooks'))
base_module = 'relations.{}.{}'.format(interface, role)
for module in ('reactive.{}'.format(base_module), base_module):
if module in sys.modules:
break
try:
importlib.i... | 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). | 2.97548 | 2.921687 | 1.018412 |
if not module:
return None
# All the RelationFactory subclasses
candidates = [o for o in (getattr(module, attr) for attr in dir(module))
if (o is not RelationFactory and
o is not RelationBase and
isclass(o) and
... | 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. | 3.762451 | 3.510966 | 1.071629 |
if 'local-data' in key:
continue
if 'namespace' in data:
continue
relation_name = data.pop('relation_name')
if data['scope'] == scopes.GLOBAL:
data['namespace'] = relation_name
unitdata.kv().set(key, data)
else:
# split ... | def _migrate_conversations(): # noqa
for key, data in unitdata.kv().getrange('reactive.conversations.').items() | 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 | 3.545489 | 3.228775 | 1.098091 |
if relation_name:
relation = relation_from_name(relation_name)
if relation is None:
raise ValueError('Relation not found: %s' % relation_name)
elif flag or state:
relation = relation_from_flag(flag or state)
if relation is None:
raise ValueError('Rela... | def relation_call(method, relation_name=None, flag=None, state=None, *args) | Invoke a method on the class implementing a relation via the CLI | 2.919402 | 2.904553 | 1.005112 |
value = _get_flag_value(flag)
if value is None:
return None
relation_name = value['relation']
conversations = Conversation.load(value['conversations'])
return cls.from_name(relation_name, conversations) | 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. | 5.755527 | 5.652489 | 1.018229 |
if relation_name is None:
return None
relation_class = cls._cache.get(relation_name)
if relation_class:
return relation_class(relation_name, conversations)
role, interface = hookenv.relation_to_role_and_interface(relation_name)
if role and interfa... | 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 | 2.465309 | 2.344235 | 1.051648 |
module = _relation_module(role, interface)
if not module:
return None
return cls._find_subclass(module) | def _find_impl(cls, role, interface) | Find relation implementation based on its role and interface. | 7.927527 | 5.375884 | 1.474646 |
for attr in dir(module):
candidate = getattr(module, attr)
if (isclass(candidate) and issubclass(candidate, cls) and
candidate is not RelationBase):
return candidate
return None | 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. | 3.760832 | 2.814907 | 1.336041 |
if scope is None:
if self.scope is scopes.UNIT:
scope = hookenv.remote_unit()
elif self.scope is scopes.SERVICE:
scope = hookenv.remote_service_name()
else:
scope = self.scope
if scope is None:
raise... | 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 that there is only a single global conversation scope for t... | 3.621497 | 2.969781 | 1.219449 |
self.conversation(scope).toggle_state(state, active) | 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.toggle_state`. | 13.532097 | 5.304676 | 2.550975 |
self.conversation(scope).set_remote(key, value, data, **kwdata) | 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)
See :meth:`conversation` and :meth:`Conversation.set_remote`. | 6.136528 | 3.759795 | 1.632144 |
return self.conversation(scope).get_remote(key, default) | 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:`Conversation.get_remote`. | 11.706836 | 5.720131 | 2.046603 |
self.conversation(scope).set_local(key, value, data, **kwdata) | 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 :meth:`conversation` and :meth:`Conversation.set_local`. | 6.070638 | 4.061594 | 1.494644 |
return self.conversation(scope).get_local(key, default) | 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`. | 11.084932 | 5.219571 | 2.123725 |
if self.scope == scopes.GLOBAL:
# the namespace is the relation name and this conv speaks for all
# connected instances of that relation
return hookenv.relation_ids(self.namespace)
else:
# the namespace is the relation ID
return [self.... | def relation_ids(self) | The set of IDs of the specific relation instances that this conversation
is communicating with. | 11.226216 | 9.503194 | 1.18131 |
relation_name = hookenv.relation_type()
relation_id = hookenv.relation_id()
unit = hookenv.remote_unit()
service = hookenv.remote_service_name()
if scope is scopes.UNIT:
scope = unit
namespace = relation_id
elif scope is scopes.SERVICE:
... | 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:`~charmhelpers.core.unitdata.Storage.flush` be call... | 3.432578 | 3.166017 | 1.084194 |
unit = hookenv.remote_unit()
self.units.remove(unit)
if self.units:
unitdata.kv().set(self.key, self.serialize(self))
else:
unitdata.kv().unset(self.key) | def depart(self) | Remove the current remote unit, for the active hook context, from
this conversation. This should be called from a `-departed` hook. | 5.853467 | 4.710832 | 1.242555 |
return {
'namespace': conversation.namespace,
'units': sorted(conversation.units),
'scope': conversation.scope,
} | def serialize(cls, conversation) | Serialize a conversation instance for storage. | 7.271805 | 6.211757 | 1.170652 |
conversations = []
for key in keys:
conversation = unitdata.kv().get(key)
if conversation:
conversations.append(cls.deserialize(conversation))
return conversations | def load(cls, keys) | Load a set of conversations by their keys. | 4.639656 | 3.887758 | 1.193402 |
state = state.format(relation_name=self.relation_name)
value = _get_flag_value(state, {
'relation': self.relation_name,
'conversations': [],
})
if self.key not in value['conversations']:
value['conversations'].append(self.key)
set_flag... | 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::
conversation.set_state('{relation_name}.state')
... | 5.099207 | 3.859271 | 1.321288 |
state = state.format(relation_name=self.relation_name)
value = _get_flag_value(state)
if not value:
return
if self.key in value['conversations']:
value['conversations'].remove(self.key)
if value['conversations']:
set_flag(state, value)... | 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 states from
other relations. For example::... | 4.262163 | 3.427171 | 1.243639 |
state = state.format(relation_name=self.relation_name)
value = _get_flag_value(state)
if not value:
return False
return self.key in value['conversations'] | def is_state(self, state) | Test if this conversation is in the given state. | 8.567874 | 6.900054 | 1.241711 |
if active is TOGGLE:
active = not self.is_state(state)
if active:
self.set_state(state)
else:
self.remove_state(state) | 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 the state is currently set, ``True`` if it is not; essentially
... | 2.583246 | 5.163998 | 0.500242 |
if data is None:
data = {}
if key is not None:
data[key] = value
data.update(kwdata)
if not data:
return
for relation_id in self.relation_ids:
hookenv.relation_set(relation_id, data) | 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 conversation only includes a single unit, the data will
still be set for that... | 3.120999 | 3.298361 | 0.946227 |
cur_rid = hookenv.relation_id()
departing = hookenv.hook_name().endswith('-relation-departed')
for relation_id in self.relation_ids:
units = hookenv.related_units(relation_id)
if departing and cur_rid == relation_id:
# Work around the fact that Ju... | 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 the data or by all units eventually
converging to iden... | 4.226774 | 4.213329 | 1.003191 |
if data is None:
data = {}
if key is not None:
data[key] = value
data.update(kwdata)
if not data:
return
unitdata.kv().update(data, prefix='%s.%s.' % (self.key, 'local-data')) | 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 if it has changed, you can use the following::
prev = conversation.get... | 4.152603 | 4.566528 | 0.909357 |
key = '%s.%s.%s' % (self.key, 'local-data', key)
return unitdata.kv().get(key, default) | def get_local(self, key, default=None) | Retrieve some data previously set via :meth:`set_local` for this conversation. | 6.180571 | 5.982132 | 1.033172 |
old_flags = get_flags()
unitdata.kv().update({flag: value}, prefix='reactive.states.')
if flag not in old_flags:
tracer().set_flag(flag)
FlagWatch.change(flag)
trigger = _get_trigger(flag, None)
for flag_name in trigger['set_flag']:
set_flag(flag_name)
... | 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 run of the reactive framework. All unpe... | 6.728759 | 6.786707 | 0.991461 |
old_flags = get_flags()
unitdata.kv().unset('reactive.states.%s' % flag)
unitdata.kv().set('reactive.dispatch.removed_state', True)
if flag in old_flags:
tracer().clear_flag(flag)
FlagWatch.change(flag)
trigger = _get_trigger(None, flag)
for flag_name in trigger['set... | 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 framework. All unpersisted
changes... | 6.320064 | 6.580816 | 0.960377 |
if not any((when, when_not)):
raise ValueError('Must provide one of when or when_not')
if all((when, when_not)):
raise ValueError('Only one of when or when_not can be provided')
if not any((set_flag, clear_flag)):
raise ValueError('Must provide at least one of set_flag or clear_... | 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_not: Flag to trigger on when it is cleared.
:param str set_flag: If given, this flag will... | 1.837488 | 1.874506 | 0.980252 |
flags = unitdata.kv().getrange('reactive.states.', strip=True) or {}
return sorted(flags.keys()) | def get_flags() | Return a list of all flags which are set. | 24.088924 | 18.59412 | 1.295513 |
FlagWatch.reset()
def _test(to_test):
return list(filter(lambda h: h.test(), to_test))
def _invoke(to_invoke):
while to_invoke:
unitdata.kv().set('reactive.dispatch.removed_state', False)
for handler in list(to_invoke):
to_invoke.remove(handler)... | 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 into quiescence (that is, until no new handlers... | 3.339227 | 3.35185 | 0.996234 |
# Add $CHARM_DIR and $CHARM_DIR/hooks to sys.path so
# 'import reactive.leadership', 'import relations.pgsql' works
# as expected, as well as relative imports like 'import ..leadership'
# or 'from . import leadership'. Without this, it becomes difficult
# for layers to access APIs provided by o... | 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 be imported and decorated
... | 5.69672 | 5.011592 | 1.136709 |
action_id = _action_id(action, suffix)
if action_id not in cls._HANDLERS:
if LOG_OPTS['register']:
hookenv.log('Registering reactive handler for %s' % _short_action_id(action, suffix),
level=hookenv.DEBUG)
cls._HANDLERS[action_... | 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 | 3.962452 | 4.238814 | 0.934802 |
_predicate = predicate
if isinstance(predicate, partial):
_predicate = 'partial(%s, %s, %s)' % (predicate.func, predicate.args, predicate.keywords)
if LOG_OPTS['register']:
hookenv.log(' Adding predicate for %s: %s' % (self.id(), _predicate), level=hookenv.DEBUG... | def add_predicate(self, predicate) | Add a new predicate callback to this handler. | 4.330152 | 4.22278 | 1.025427 |
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 | def _get_args(self) | Lazily evaluate the args. | 6.328173 | 4.891643 | 1.29367 |
args = self._get_args()
self._action(*args)
for callback in self._post_callbacks:
callback() | def invoke(self) | Invoke this handler. | 7.835725 | 6.681901 | 1.172679 |
self._CONSUMED_FLAGS.update(flags)
self._flags.update(flags) | 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` run
and none of its relevant flags have been s... | 7.974359 | 11.570922 | 0.689172 |
# 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_output], env=os.environ) | def invoke(self) | Call the external handler to be invoked. | 25.341591 | 23.680647 | 1.070139 |
def _register(action):
def arg_gen():
# use a generator to defer calling of hookenv.relation_type, for tests
rel = endpoint_from_name(hookenv.relation_type())
if rel:
yield rel
handler = Handler.get(action)
handler.add_predicate(parti... | 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
supported by :func:`~charms.reacti... | 9.449812 | 11.51105 | 0.820934 |
def _register(action):
handler = Handler.get(action)
handler.add_predicate(partial(any_file_changed, filenames, **kwargs))
return action
return _register | 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 for determining if a file has
changed. Defaults... | 7.303371 | 9.025939 | 0.809154 |
def _decorator(func):
action_id = _action_id(func)
short_action_id = _short_action_id(func)
@wraps(func)
def _wrapped(*args, **kwargs):
active_flags = get_flags()
missing_flags = [flag for flag in desired_flags if flag not in active_flags]
if... | 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 flags do not match.
This is primarily for ... | 2.193943 | 2.318197 | 0.946401 |
if action is None:
# allow to be used as @only_once or @only_once()
return only_once
action_id = _action_id(action)
handler = Handler.get(action)
handler.add_predicate(lambda: not was_invoked(action_id))
handler.add_post_callback(partial(mark_invoked, action_id))
return act... | 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 decorated function to be run once, and only onc... | 5.55838 | 5.970598 | 0.930959 |
def _register(action):
handler = Handler.get(action)
handler.add_predicate(partial(_restricted_hook, 'collect-metrics'))
return action
return _register | def collect_metrics() | Register the decorated function to run for the collect_metrics hook. | 16.791155 | 11.979013 | 1.401714 |
return tuple(flag.format(endpoint_name=endpoint_name) for flag in flags) | def _expand_endpoint_name(endpoint_name, flags) | Populate any ``{endpoint_name}`` tags in the flag names for the given
handler, based on the handlers module / file name. | 5.34386 | 4.93647 | 1.082527 |
params = signature(handler).parameters
has_self = len(params) == 1 and list(params.keys())[0] == 'self'
has_endpoint_class = any(isclass(g) and issubclass(g, Endpoint)
for g in handler.__globals__.values())
return has_self and has_endpoint_class | def _is_endpoint_method(handler) | from the context. Unfortunately, we can't directly detect whether
a handler is an Endpoint method, because at the time of decoration,
the class doesn't actually exist yet so it's impossible to get a
reference to it. So, we use the heuristic of seeing if the handler
takes only a single ``self`` param a... | 2.948328 | 2.251568 | 1.309455 |
current_hook = hookenv.hook_name()
# expand {role:interface} patterns
i_pat = re.compile(r'{([^:}]+):([^}]+)}')
hook_patterns = _expand_replacements(i_pat, hookenv.role_and_interface_to_relations, hook_patterns)
# expand {A,B,C,...} patterns
c_pat = re.compile(r'{((?:[^:,}]+,?)+)}')
h... | def any_hook(*hook_patterns) | Assert that the currently executing hook matches one of the given patterns.
Each pattern will match one or more hooks, and can use the following
special syntax:
* ``db-relation-{joined,changed}`` can be used to match multiple hooks
(in this case, ``db-relation-joined`` and ``db-relation-changed`... | 4.443907 | 4.500521 | 0.987421 |
changed = False
for filename in filenames:
if callable(filename):
filename = str(filename())
else:
filename = str(filename)
old_hash = unitdata.kv().get('reactive.files_changed.%s' % filename)
new_hash = host.file_hash(filename, hash_type=hash_type)
... | def any_file_changed(filenames, hash_type='md5') | Check if any of the given files have changed since the last time this
was called.
:param list filenames: Names of files to check. Accepts callables returning
the filename.
:param str hash_type: Algorithm to use to check the files. | 3.218358 | 3.434839 | 0.936975 |
global hooks
if sys.version_info[0] > 2 and sys.version_info[1] > 4:
fsglob = sorted(glob.iglob(pathname, recursive=True))
else:
fsglob = sorted(glob.iglob(pathname))
for path in fsglob:
real_path = os.path.realpath(path)
# Append hooks file directory to the sys.pa... | def load_hook_files(pathname) | Loads files either defined as a glob or a single file path
sorted by filenames. | 2.204897 | 2.196781 | 1.003694 |
hook_name = hookenv.hook_name()
restricted_mode = hook_name in ['meter-status-changed', 'collect-metrics']
hookenv.log('Reactive main running for hook %s' % hookenv.hook_name(), level=hookenv.INFO)
if restricted_mode:
hookenv.log('Restricted mode.', level=hookenv.INFO)
# work-around f... | def main(relation_name=None) | This is the main entry point for the reactive framework. It calls
:func:`~bus.discover` to find and load all reactive handlers (e.g.,
:func:`@when <decorators.when>` decorated blocks), and then
:func:`~bus.dispatch` to trigger handlers until the queue settles out.
Finally, :meth:`unitdata.kv().flush <c... | 4.222849 | 3.81085 | 1.108112 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.