output stringlengths 1 928k | instruction stringlengths 7 928k | system stringlengths 0 104k |
|---|---|---|
Create the tab header label for notebook tabs. | Explain what the following Python 3 code does
def create_tab_header_label(tab_name, icons):
tooltip_event_box = Gtk.EventBox()
tooltip_event_box.set_tooltip_text(tab_name)
tab_label = Gtk.Label()
if global_gui_config.get_config_value('USE_ICONS_AS_TAB_LABELS', True):
tab_label.set_markup('<span ... | You are a Python code architect, reviewing and designing scalable and efficient code |
Create a button label with a chosen icon. | Can you generate a brief explanation for the following Python 3 code
def create_button_label(icon, font_size=constants.FONT_SIZE_NORMAL):
label = Gtk.Label()
set_label_markup(label, '&#x' + icon + ';', constants.ICON_FONT, font_size)
label.show()
return label | As a Python code translator, you convert algorithms and pseudocode into Python. |
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 = '... | Can you write a function in Python 3 where it
transforms Notebook tab label to title by replacing underscores with white spaces and capitalizing the first letter of each word. | You are a Python code generator, capable of creating scripts from specifications. |
Set the title of a GTK notebook to one of its tab s titles. | Can you generate a brief explanation for the following Python 3 code
def set_notebook_title(notebook, page_num, title_label):
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 | As a Python code translator, you convert algorithms and pseudocode into Python. |
Creates a MenuItem box with icon and label. | How would you explain what the following Python 3 function does
def create_menu_box_with_icon_and_label(label_text):
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_s... | As a Python code analyst, you investigate and solve complex coding mysteries |
Adjust GTK Window s size and position according to the corresponding values in the runtime_config file. | Given the following Python 3 function, write the documentation
def set_window_size_and_position(window, window_key):
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_... | You are a Python code analyst, evaluating scripts for potential improvements. |
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... | Write a Python 3 script to
check whether the widget is supposed to react to the event. | You are a Python code analyst, evaluating scripts for potential improvements. |
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... | Write a Python 3 function for
checking if the event is of right type | As a Python code translator, you convert algorithms and pseudocode into Python. |
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() | Can you create a Python 3 function that
calls when the View was registered | You are a Python code analyst, evaluating scripts for potential improvements. |
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) | Can you write a function in Python 3 where it
calls when the View was registered | As a Python code translator, you convert algorithms and pseudocode into Python. |
Called when the View was registered | Make a summary of the following Python 3 code
def register_view(self, view):
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'... | As a Python code analyst, you investigate and solve complex coding mysteries |
Overwrites the remove_outcome method of the State class. Removes the outcome from the library state. | Can you generate a brief explanation for the following Python 3 code
def remove_outcome(self, outcome_id, force=False, destroy=True):
if force:
return State.remove_outcome(self, outcome_id, force, destroy)
else:
raise NotImplementedError("Remove outcome is not implemented for lib... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Overwrites the remove_output_data_port method of the State class to allow the user to remove an output data port from the library state. | Can you generate a brief explanation for the following Python 3 code
def remove_output_data_port(self, data_port_id, force=False, destroy=True):
if force:
return State.remove_output_data_port(self, data_port_id, force, destroy)
else:
raise NotImplementedError("Remove output data ... | As a Python code translator, you convert algorithms and pseudocode into Python. |
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... | How would you code a function in Python 3 to
calculate the library hierarchy depth of the current library state. | You are a Python code analyst, evaluating scripts for potential improvements. |
Loads the configuration from a specific file | Here you have a function in Python 3, explain what it does
def load(self, config_file=None, path=None):
if config_file is None:
if path is None:
path, config_file = split(resource_filename(__name__, CONFIG_FILE))
else:
config_file = CONFIG_FILE
sup... | You are a Python code architect, reviewing and designing scalable and efficient code |
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... | Implement a function in Python 3 to
call when the view was registered | You are a Python code analyst, evaluating scripts for potential improvements. |
Reopen state editor when state type is changed | Here you have a function in Python 3, explain what it does
def state_type_changed(self, model, prop_name, info):
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:
# prin... | As a Python code analyst, you investigate and solve complex coding mysteries |
Close state editor when state is being destructed | Can you generate the documentation for the following Python 3 function
def state_destruction(self, model, prop_name, info):
import rafcon.gui.singleton as gui_singletons
states_editor_ctrl = gui_singletons.main_window_controller.get_controller('states_editor_ctrl')
state_identifier = states_edit... | As a Python code analyst, you investigate and solve complex coding mysteries |
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... | Write a Python 3 function that can
prepare the model for destruction | As a Python code translator, you convert algorithms and pseudocode into Python. |
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
... | How would you implement a function in Python 3 that
calls when a state machine action was triggered. | As a Python code composer, you craft elegant and concise scripts. |
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... | Can you implement a function in Python 3 that
returns the StateModel for the given path. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Loads the meta data of the state machine model from the file system. | Can you generate the documentation for the following Python 3 function
def load_meta_data(self, path=None, recursively=True):
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... | As a Python code composer, you craft elegant and concise scripts. |
Save the meta data of the state machine model to the file system | Can you generate a brief explanation for the following Python 3 code
def store_meta_data(self, copy_path=None):
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.FIL... | You are a Python code generator, capable of creating scripts from specifications. |
Convert a list of Penn Treebank formatted strings into Stanford Dependencies. | Explain what the following Python 3 code does
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 dependencie... | As a python code expert, you are capable of creating scripts from specifications. |
Setup the user - specific install path for the Stanford
Dependencies jar if the jar_url is not specified and ensure that the directory exists and return the full path for the jar file. | Make a summary of the following Python 3 code
def setup_and_get_default_path(self, jar_base_filename):
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:
... | As a Python code composer, you craft elegant and concise scripts. |
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... | Write a Python 3 function for
downloading the jar for version into the jar_filename specified by the constructor. Will not overwrite jar_filename if it already exists. | As a python code expert, you are capable of creating scripts from specifications. |
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))... | Can you implement a function in Python 3 that
ensures that the given representation is a known Stanford Dependency representation. | As a Python code composer, you craft elegant and concise scripts. |
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... | How would you implement a function in Python 3 that
ensures that jar_filename is a valid path to a jar file. | As a Python code analyst, you investigate and solve complex coding mysteries |
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... | Create a Python 3 function for
getting the URL to a Stanford CoreNLP jar file with a specific version. | You are a Python code analyst, evaluating scripts for potential improvements. |
Converts a Penn Treebank tree into a Stanford Information object. | Can you tell what is the following Python 3 function doing
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
th... | As a Python code analyst, you investigate and solve complex coding mysteries |
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] =... | How would you code a function in Python 3 to
return the stem of word with specific form and part - of - speech tag according to the Stanford lemmatizer. Lemmas are cached if necessary. | You are a Python code analyst, evaluating scripts for potential improvements. |
Get a list of dependencies from a Stanford Tree for a specific Universal Dependencies representation. | Can you generate a brief explanation for the following Python 3 code
def _get_deps(self, tree, include_punct, representation, universal):
if universal:
converter = self.universal_converter
if self.universal_converter == self.converter:
import warnings
war... | You are a Python code generator, capable of creating scripts from specifications. |
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... | Implement a Python 3 function for
representing this Token as a string in CoNLL - X format. | As a Python code translator, you convert algorithms and pseudocode into Python. |
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... | How would you code a function in Python 3 to
construct a Token from a line in CoNLL - X format. | As a Python code translator, you convert algorithms and pseudocode into Python. |
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... | How would you implement a function in Python 3 that
represents this Sentence as an ASCII tree string. Requires a str_func which should take a single Token and return a string. | As a Python code composer, you craft elegant and concise scripts. |
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... | Implement a Python 3 function for
returning this sentence as a graphviz. Digraph. | You are a Python code analyst, evaluating scripts for potential improvements. |
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... | Implement a Python 3 function for
constructing a Sentence. stream is an iterable over strings where each string is a line in CoNLL - X format. | You are a Python code analyst, evaluating scripts for potential improvements. |
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... | How would you implement a function in Python 3 that
constructs a Sentence from a Stanford Dependency file. | As a Python code analyst, you investigate and solve complex coding mysteries |
Construct a Corpus. stream is an iterable over strings where
each string is a line in CoNLL - X format. | Here you have a function in Python 3, explain what it does
def from_conll(this_class, stream):
stream = iter(stream)
corpus = this_class()
while 1:
# read until we get an empty sentence
sentence = Sentence.from_conll(stream)
if sentence:
corpus... | As a Python code composer, you craft elegant and concise scripts. |
Construct a Corpus from a list of trees and a list of UnifiedTrees. | Can you generate a brief explanation for the following Python 3 code
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 ... | You are a Python code generator, capable of creating scripts from specifications. |
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
... | Implement a function in Python 3 to
convert a list of Penn Treebank formatted trees into Stanford Dependencies. | You are a Python code analyst, evaluating scripts for potential improvements. |
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) | Can you write a function in Python 3 where it
returns an endpoint object from a name. | As a Python code composer, you craft elegant and concise scripts. |
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... | Can you create a Python 3 function that
returns the Endpoint object used for interacting with relations tied to a flag. | As a Python code translator, you convert algorithms and pseudocode into Python. |
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)
... | Can you create a Python 3 function that
gets the RelationFactory for the given relation name. | As a Python code composer, you craft elegant and concise scripts. |
Return module for relation based on its role and interface. | Can you generate the documentation for the following Python 3 function
def _relation_module(role, interface):
_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... | You are a Python code architect, reviewing and designing scalable and efficient code |
Attempt to find a RelationFactory subclass in the module. | Can you tell what is the following Python 3 function doing
def _find_relation_factory(module):
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
... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Migrate all conversations in the SERVICE
to the new format. | Given the following Python 3 function, write the documentation
def _migrate_conversations(): # noqa
for key, data in unitdata.kv().getrange('reactive.conversations.').items():
if 'local-data' in key:
continue
if 'namespace' in data:
continue
relation_name = data.pop(... | As a Python code translator, you convert algorithms and pseudocode into Python. |
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... | How would you code a function in Python 3 to
invoke a method on the class implementing a relation via the CLI | As a Python code analyst, you investigate and solve complex coding mysteries |
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:
... | Can you write a function in Python 3 where it
returns an Endpoint from a flag. | You are a Python code analyst, evaluating scripts for potential improvements. |
Find a relation implementation in the current charm based on the relation name. | Given the following Python 3 function, write the documentation
def from_name(cls, relation_name, conversations=None):
if relation_name is None:
return None
relation_class = cls._cache.get(relation_name)
if relation_class:
return relation_class(relation_name, conversations... | As a Python code translator, you convert algorithms and pseudocode into Python. |
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) | Create a Python 3 function to
find the implementation based on its role and interface. | As a Python code composer, you craft elegant and concise scripts. |
Attempt to find a subclass of cls in the given module. | Given the following Python 3 function, write the documentation
def _find_subclass(cls, module):
for attr in dir(module):
candidate = getattr(module, attr)
if (isclass(candidate) and issubclass(candidate, cls) and
candidate is not RelationBase):
return ... | As a Python code analyst, you investigate and solve complex coding mysteries |
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... | Write a Python 3 script to
get a single conversation by scope | You are a Python code architect, reviewing and designing scalable and efficient code |
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... | Can you implement a function in Python 3 that
toggles the state of the related conversation with the given scope. | You are a Python code architect, reviewing and designing scalable and efficient code |
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)
... | How would you implement a function in Python 3 that
sets data for the remote end of the current conversation with the given scope. | As a python code expert, you are capable of creating scripts from specifications. |
Get data from the remote end of the conversation with the given key. | Explain what the following Python 3 code does
def get_remote(self, key, default=None, scope=None):
return self.conversation(scope).get_remote(key, default) | As a Python code analyst, you investigate and solve complex coding mysteries |
Locally store some data namespaced by the current or given conversation scope. | Can you generate the documentation for the following Python 3 function
def set_local(self, key=None, value=None, data=None, scope=None, **kwdata):
self.conversation(scope).set_local(key, value, data, **kwdata) | You are a Python code analyst, evaluating scripts for potential improvements. |
Retrieve some data previously set via set_local. | Explain what the following Python 3 code does
def get_local(self, key, default=None, scope=None):
return self.conversation(scope).get_local(key, default) | As a Python code translator, you convert algorithms and pseudocode into Python. |
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 ... | Write a Python 3 function that can
return the set of relation IDs that this conversation is communicating with. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Get or create a conversation for the given scope and active hook context. | Here you have a function in Python 3, explain what it does
def join(cls, scope):
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
... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Removes the current remote unit from the current conversation context. | Can you generate the documentation for the following Python 3 function
def depart(self):
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) | As a Python code analyst, you investigate and solve complex coding mysteries |
def serialize(cls, conversation):
"""
Serialize a conversation instance for storage.
"""
return {
'namespace': conversation.namespace,
'units': sorted(conversation.units),
'scope': conversation.scope,
} | Implement a function in Python 3 to
serialize a conversation instance for storage. | You are a Python code analyst, evaluating scripts for potential improvements. |
Load a set of conversations by their keys. | Given the following Python 3 function, write the documentation
def load(cls, keys):
conversations = []
for key in keys:
conversation = unitdata.kv().get(key)
if conversation:
conversations.append(cls.deserialize(conversation))
return conversations | You are a Python code generator, capable of creating scripts from specifications. |
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... | Implement a function in Python 3 to
activate and put this conversation into the given state. | As a python code expert, you are capable of creating scripts from specifications. |
Removes this conversation from the given state and potentially
deactivate the state if no more conversations are in it. | Can you tell what is the following Python 3 function doing
def remove_state(self, state):
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'].remov... | You are a Python code generator, capable of creating scripts from specifications. |
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'] | Write a Python 3 script for
testing if this conversation is in the given state. | You are a Python code analyst, evaluating scripts for potential improvements. |
Toggle the given state for this conversation. | Given the following Python 3 function, write the documentation
def toggle_state(self, state, active=TOGGLE):
if active is TOGGLE:
active = not self.is_state(state)
if active:
self.set_state(state)
else:
self.remove_state(state) | You are a Python code generator, capable of creating scripts from specifications. |
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 ... | Write a Python 3 script for
setting data for the remote end of this conversation. | You are a Python code architect, reviewing and designing scalable and efficient code |
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... | Write a Python 3 script for
getting a value from the remote end of this conversation. | You are a Python code generator, capable of creating scripts from specifications. |
Set the local data associated with this conversation. | Given the following Python 3 function, write the documentation
def set_local(self, key=None, value=None, data=None, **kwdata):
if data is None:
data = {}
if key is not None:
data[key] = value
data.update(kwdata)
if not data:
return
unitdata.kv(... | As a python code expert, you are capable of creating scripts from specifications. |
Retrieve some data from the local - data store for this conversation. | Explain what the following Python 3 code does
def get_local(self, key, default=None):
key = '%s.%s.%s' % (self.key, 'local-data', key)
return unitdata.kv().get(key, default) | You are a Python code analyst, evaluating scripts for potential improvements. |
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 ... | Create a Python 3 function to
set the given flag as active. | As a Python code analyst, you investigate and solve complex coding mysteries |
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... | Can you implement a function in Python 3 that
clears the flag in the specified node. | As a Python code composer, you craft elegant and concise scripts. |
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... | Implement a function in Python 3 to
register a trigger to set or clear a flag when a given flag is set. | As a Python code analyst, you investigate and solve complex coding mysteries |
Return a list of all flags which are set. | Can you generate the documentation for the following Python 3 function
def get_flags():
flags = unitdata.kv().getrange('reactive.states.', strip=True) or {}
return sorted(flags.keys()) | You are a Python code architect, reviewing and designing scalable and efficient code |
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... | Make a summary of the following Python 3 code
def dispatch(restricted=False):
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)
... | You are a Python code generator, capable of creating scripts from specifications. |
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... | How would you code a function in Python 3 to
discover handlers based on convention. | You are a Python code analyst, evaluating scripts for potential improvements. |
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... | Create a Python 3 function to
get or register a handler for the given action. | You are a Python code analyst, evaluating scripts for potential improvements. |
Add a new predicate callback to this handler. | Here you have a function in Python 3, explain what it does
def add_predicate(self, predicate):
_predicate = predicate
if isinstance(predicate, partial):
_predicate = 'partial(%s, %s, %s)' % (predicate.func, predicate.args, predicate.keywords)
if LOG_OPTS['register']:
hook... | As a python code expert, you are capable of creating scripts from specifications. |
Lazily evaluate the args.
| Make a summary of the following Python 3 code
def _get_args(self):
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 | As a Python code composer, you craft elegant and concise scripts. |
Register flags as being relevant to this handler. | Can you generate the documentation for the following Python 3 function
def register_flags(self, flags):
self._CONSUMED_FLAGS.update(flags)
self._flags.update(flags) | You are a Python code generator, capable of creating scripts from specifications. |
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... | How would you implement a function in Python 3 that
invokes the external handler. | As a Python code analyst, you investigate and solve complex coding mysteries |
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
... | Can you write a function in Python 3 where it
registers the decorated function to run when the current hook matches any of the hook_patterns. | You are a Python code architect, reviewing and designing scalable and efficient code |
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... | Create a Python 3 function to
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. Defa... | You are a Python code architect, reviewing and designing scalable and efficient code |
Decorator that ensures that the decorated function is not called if the desired_flags are active. | Can you generate the documentation for the following Python 3 function
def not_unless(*desired_flags):
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()
... | You are a Python code architect, reviewing and designing scalable and efficient code |
Decorator to register the decorated function to run for the collect_metrics hook. | Make a summary of the following Python 3 code
def collect_metrics():
def _register(action):
handler = Handler.get(action)
handler.add_predicate(partial(_restricted_hook, 'collect-metrics'))
return action
return _register | As a Python code translator, you convert algorithms and pseudocode into Python. |
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.
"""
return tuple(flag.format(endpoint_name=endpoint_name) for flag in flags) | Can you write a function in Python 3 where it
expands any endpoint name tags in the given flags. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Returns True if the given handler is an Endpoint method. | Here you have a function in Python 3, explain what it does
def _is_endpoint_method(handler):
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._... | As a python code expert, you are capable of creating scripts from specifications. |
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-re... | Can you write a function in Python 3 where it
asserts that the currently executing hook matches one of the given patterns. | You are a Python code architect, reviewing and designing scalable and efficient code |
Check if any of the given files have changed since the last time this
was called. | Here you have a function in Python 3, explain what it does
def any_file_changed(filenames, hash_type='md5'):
changed = False
for filename in filenames:
if callable(filename):
filename = str(filename())
else:
filename = str(filename)
old_hash = unitdata.kv().get('r... | As a Python code analyst, you investigate and solve complex coding mysteries |
Loads the files defined as a glob or a single file path and adds them to the internal list of hooks. | Here you have a function in Python 3, explain what it does
def load_hook_files(pathname):
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:
r... | As a python code expert, you are capable of creating scripts from specifications. |
def from_flag(cls, flag):
"""
Return an Endpoint subclass instance based on the given flag.
The instance that is returned depends on the endpoint name embedded
in the flag. Flags should be of the form ``endpoint.{name}.extra...``,
though for legacy purposes, the ``endpoint.`` p... | Write a Python 3 function for
returning an Endpoint subclass instance based on the given flag. | You are a Python code architect, reviewing and designing scalable and efficient code |
Create Endpoint instances and manage automatic flags. | Given the following Python 3 function, write the documentation
def _startup(cls):
for endpoint_name in sorted(hookenv.relation_types()):
# populate context based on attached relations
relf = relation_factory(endpoint_name)
if not relf or not issubclass(relf, cls):
... | You are a Python code generator, capable of creating scripts from specifications. |
def expand_name(self, flag):
"""
Complete a flag for this endpoint by expanding the endpoint name.
If the flag does not already contain ``{endpoint_name}``, it will be
prefixed with ``endpoint.{endpoint_name}.``. Then, any occurance of
``{endpoint_name}`` will be replaced with `... | Can you create a Python 3 function that
expands the flag for this endpoint by expanding the endpoint name. | As a python code expert, you are capable of creating scripts from specifications. |
def _manage_flags(self):
"""
Manage automatic relation flags.
"""
already_joined = is_flag_set(self.expand_name('joined'))
hook_name = hookenv.hook_name()
rel_hook = hook_name.startswith(self.endpoint_name + '-relation-')
departed_hook = rel_hook and hook_name.end... | How would you implement a function in Python 3 that
manages automatic relation flags. | As a python code expert, you are capable of creating scripts from specifications. |
A list view of all the units of all relations attached to this Endpoint. | Can you tell what is the following Python 3 function doing
def all_joined_units(self):
if self._all_joined_units is None:
units = chain.from_iterable(rel.units for rel in self.relations)
self._all_joined_units = CombinedUnitsView(units)
return self._all_joined_units | As a Python code translator, you convert algorithms and pseudocode into Python. |
def all_departed_units(self):
"""
Collection of all units that were previously part of any relation on
this endpoint but which have since departed.
This collection is persistent and mutable. The departed units will
be kept until they are explicitly removed, to allow for reasona... | Write a Python 3 script for
returning a collection of all departed units. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Returns the name of the remote application for this relation or None if the relation is not in the remote application. | How would you explain what the following Python 3 function does
def application_name(self):
if self._application_name is None and self.units:
self._application_name = self.units[0].unit_name.split('/')[0]
return self._application_name | As a Python code composer, you craft elegant and concise scripts. |
Returns the relation data that the local unit publishes so it is visible to all related units. | Given the following Python 3 function, write the documentation
def to_publish(self):
if self._data is None:
self._data = JSONUnitDataView(
hookenv.relation_get(unit=hookenv.local_unit(),
rid=self.relation_id),
writeable=True)
... | As a Python code composer, you craft elegant and concise scripts. |
Flushes the local unit data to the relation. | Explain what the following Python 3 code does
def _flush_data(self):
if self._data and self._data.modified:
hookenv.relation_set(self.relation_id, dict(self.to_publish.data)) | You are a Python code analyst, evaluating scripts for potential improvements. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.