text stringlengths 81 112k |
|---|
Handle the data change event to enable the save and close button.
def save_and_close_enable(self):
"""Handle the data change event to enable the save and close button."""
if self.btn_save_and_close:
self.btn_save_and_close.setEnabled(True)
self.btn_save_and_close.setAutoDefa... |
Get the value of a variable
def get_value(self, name):
"""Get the value of a variable"""
value = self.shellwidget.get_value(name)
# Reset temporal variable where value is saved to
# save memory
self.shellwidget._kernel_value = None
return value |
Create new value in data
def new_value(self, name, value):
"""Create new value in data"""
try:
# We need to enclose values in a list to be able to send
# them to the kernel in Python 2
svalue = [cloudpickle.dumps(value, protocol=PICKLE_PROTOCOL)]
... |
Remove values from data
def remove_values(self, names):
"""Remove values from data"""
for name in names:
self.shellwidget.remove_value(name)
self.shellwidget.refresh_namespacebrowser() |
Copy value
def copy_value(self, orig_name, new_name):
"""Copy value"""
self.shellwidget.copy_value(orig_name, new_name)
self.shellwidget.refresh_namespacebrowser() |
Plot item
def plot(self, name, funcname):
"""Plot item"""
sw = self.shellwidget
if sw._reading:
sw.dbg_exec_magic('varexp', '--%s %s' % (funcname, name))
else:
sw.execute("%%varexp --%s %s" % (funcname, name)) |
Show item's image
def imshow(self, name):
"""Show item's image"""
sw = self.shellwidget
if sw._reading:
sw.dbg_exec_magic('varexp', '--imshow %s' % name)
else:
sw.execute("%%varexp --imshow %s" % name) |
Show image (item is a PIL image)
def show_image(self, name):
"""Show image (item is a PIL image)"""
command = "%s.show()" % name
sw = self.shellwidget
if sw._reading:
sw.kernel_client.input(command)
else:
sw.execute(command) |
Get kernel id
def kernel_id(self):
"""Get kernel id"""
if self.connection_file is not None:
json_file = osp.basename(self.connection_file)
return json_file.split('.json')[0] |
Filename to save kernel stderr output.
def stderr_file(self):
"""Filename to save kernel stderr output."""
stderr_file = None
if self.connection_file is not None:
stderr_file = self.kernel_id + '.stderr'
if self.stderr_dir is not None:
stderr_file =... |
Get handle to stderr_file.
def stderr_handle(self):
"""Get handle to stderr_file."""
if self.stderr_file is not None:
# Needed to prevent any error that could appear.
# See issue 6267
try:
handle = codecs.open(self.stderr_file, 'w', encoding='ut... |
Remove stderr_file associated with the client.
def remove_stderr_file(self):
"""Remove stderr_file associated with the client."""
try:
# Defer closing the stderr_handle until the client
# is closed because jupyter_client needs it open
# while it tries to restart... |
Configure shellwidget after kernel is started
def configure_shellwidget(self, give_focus=True):
"""Configure shellwidget after kernel is started"""
if give_focus:
self.get_control().setFocus()
# Set exit callback
self.shellwidget.set_exit_callback()
# To sa... |
Method to handle what to do when the stop button is pressed
def stop_button_click_handler(self):
"""Method to handle what to do when the stop button is pressed"""
self.stop_button.setDisabled(True)
# Interrupt computations or stop debugging
if not self.shellwidget._reading:
... |
Show kernel initialization errors in infowidget.
def show_kernel_error(self, error):
"""Show kernel initialization errors in infowidget."""
# Replace end of line chars with <br>
eol = sourcecode.get_eol_chars(error)
if eol:
error = error.replace(eol, '<br>')
... |
Return client name
def get_name(self):
"""Return client name"""
if self.given_name is None:
# Name according to host
if self.hostname is None:
name = _("Console")
else:
name = self.hostname
# Adding id to name
... |
Return the text widget (or similar) to give focus to
def get_control(self):
"""Return the text widget (or similar) to give focus to"""
# page_control is the widget used for paging
page_control = self.shellwidget._page_control
if page_control and page_control.isVisible():
... |
Return options menu
def get_options_menu(self):
"""Return options menu"""
env_action = create_action(
self,
_("Show environment variables"),
icon=ima.icon('environ'),
triggered=self.shellwidget.get_env... |
Return toolbar buttons list.
def get_toolbar_buttons(self):
"""Return toolbar buttons list."""
buttons = []
# Code to add the stop button
if self.stop_button is None:
self.stop_button = create_toolbutton(
self,
... |
Add actions to IPython widget context menu
def add_actions_to_context_menu(self, menu):
"""Add actions to IPython widget context menu"""
inspect_action = create_action(self, _("Inspect current object"),
QKeySequence(get_shortcut('console',
... |
Set IPython widget's font
def set_font(self, font):
"""Set IPython widget's font"""
self.shellwidget._control.setFont(font)
self.shellwidget.font = font |
Set IPython color scheme.
def set_color_scheme(self, color_scheme, reset=True):
"""Set IPython color scheme."""
# Needed to handle not initialized kernel_client
# See issue 6996
try:
self.shellwidget.set_color_scheme(color_scheme, reset)
except AttributeError:
... |
Shutdown kernel
def shutdown(self):
"""Shutdown kernel"""
if self.get_kernel() is not None and not self.slave:
self.shellwidget.kernel_manager.shutdown_kernel()
if self.shellwidget.kernel_client is not None:
background(self.shellwidget.kernel_client.stop_channels) |
Restart the associated kernel.
Took this code from the qtconsole project
Licensed under the BSD license
def restart_kernel(self):
"""
Restart the associated kernel.
Took this code from the qtconsole project
Licensed under the BSD license
"""
s... |
Show kernel restarted/died messages.
def kernel_restarted_message(self, msg):
"""Show kernel restarted/died messages."""
if not self.is_error_shown:
# If there are kernel creation errors, jupyter_client will
# try to restart the kernel and qtconsole prints a
# m... |
Resets the namespace by removing all names defined by the user
def reset_namespace(self):
"""Resets the namespace by removing all names defined by the user"""
self.shellwidget.reset_namespace(warning=self.reset_warning,
message=True) |
Show sys.path contents.
def show_syspath(self, syspath):
"""Show sys.path contents."""
if syspath is not None:
editor = CollectionsEditor(self)
editor.setup(syspath, title="sys.path contents", readonly=True,
width=600, icon=ima.icon('syspath'))
... |
Show environment variables.
def show_env(self, env):
"""Show environment variables."""
self.dialog_manager.show(RemoteEnvDialog(env, parent=self)) |
Text to show in time_label.
def show_time(self, end=False):
"""Text to show in time_label."""
if self.time_label is None:
return
elapsed_time = time.monotonic() - self.t0
# System time changed to past date, so reset start.
if elapsed_time < 0:
se... |
Slot to show/hide elapsed time label.
def set_elapsed_time_visible(self, state):
"""Slot to show/hide elapsed time label."""
self.show_elapsed_time = state
if self.time_label is not None:
self.time_label.setVisible(state) |
Set current info_page.
def set_info_page(self):
"""Set current info_page."""
if self.info_page is not None:
self.infowidget.setHtml(
self.info_page,
QUrl.fromLocalFile(self.css_path)
) |
Create html page to show while the kernel is starting
def _create_loading_page(self):
"""Create html page to show while the kernel is starting"""
loading_template = Template(LOADING)
loading_img = get_image_path('loading_sprites.png')
if os.name == 'nt':
loading_img = l... |
Create html page to show while the kernel is starting
def _create_blank_page(self):
"""Create html page to show while the kernel is starting"""
loading_template = Template(BLANK)
page = loading_template.substitute(css_path=self.css_path)
return page |
Show animation while the kernel is loading.
def _show_loading_page(self):
"""Show animation while the kernel is loading."""
self.shellwidget.hide()
self.infowidget.show()
self.info_page = self.loading_page
self.set_info_page() |
Hide animation shown while the kernel is loading.
def _hide_loading_page(self):
"""Hide animation shown while the kernel is loading."""
self.infowidget.hide()
self.shellwidget.show()
self.info_page = self.blank_page
self.set_info_page()
self.shellwidget.sig_prompt_... |
Read the stderr file of the kernel.
def _read_stderr(self):
"""Read the stderr file of the kernel."""
# We need to read stderr_file as bytes to be able to
# detect its encoding with chardet
f = open(self.stderr_file, 'rb')
try:
stderr_text = f.read()
... |
Show possible errors when setting the selected Matplotlib backend.
def _show_mpl_backend_errors(self):
"""
Show possible errors when setting the selected Matplotlib backend.
"""
if not self.external_kernel:
self.shellwidget.silent_execute(
"get_ipyt... |
Calculate a global point position `QPoint(x, y)`, for a given
line, local cursor position, or local point.
def _calculate_position(self, at_line=None, at_position=None,
at_point=None):
"""
Calculate a global point position `QPoint(x, y)`, for a given
lin... |
Update the background stylesheet to make it lighter.
def _update_stylesheet(self, widget):
"""Update the background stylesheet to make it lighter."""
if is_dark_interface():
css = qdarkstyle.load_stylesheet_from_environment()
widget.setStyleSheet(css)
palette = ... |
Create HTML template for calltips and tooltips.
This will display title and text as separate sections and add `...`
if `ellide` is True and the text is too long.
def _format_text(self, title, text, color, ellide=False):
"""
Create HTML template for calltips and tooltips.
... |
Create HTML template for signature.
This template will include indent after the method name, a highlight
color for the active parameter and highlights for special chars.
def _format_signature(self, signature, doc='', parameter='',
parameter_doc='', color=_DEFAULT_TITLE_CO... |
Show calltip.
Calltips look like tooltips but will not disappear if mouse hovers
them. They are useful for displaying signature information on methods
and functions.
def show_calltip(self, signature, doc='', parameter='', parameter_doc='',
color=_DEFAULT_TITLE_COLOR, ... |
Show tooltip.
Tooltips will disappear if mouse hovers them. They are meant for quick
inspections.
def show_tooltip(self, title, text, color=_DEFAULT_TITLE_COLOR,
at_line=None, at_position=None, at_point=None):
"""
Show tooltip.
Tooltips will disapp... |
Set widget end-of-line (EOL) characters from text (analyzes text)
def set_eol_chars(self, text):
"""Set widget end-of-line (EOL) characters from text (analyzes text)"""
if not is_text_string(text): # testing for QString (PyQt API#1)
text = to_text_string(text)
eol_chars = source... |
Same as 'toPlainText', replace '\n'
by correct end-of-line characters
def get_text_with_eol(self):
"""Same as 'toPlainText', replace '\n'
by correct end-of-line characters"""
utext = to_text_string(self.toPlainText())
lines = utext.splitlines()
linesep = self.get_l... |
Get offset in character for the given subject from the start of
text edit area
def get_position(self, subject):
"""Get offset in character for the given subject from the start of
text edit area"""
cursor = self.textCursor()
if subject == 'cursor':
pass
... |
Set cursor position
def set_cursor_position(self, position):
"""Set cursor position"""
position = self.get_position(position)
cursor = self.textCursor()
cursor.setPosition(position)
self.setTextCursor(cursor)
self.ensureCursorVisible() |
Move cursor to left or right (unit: characters)
def move_cursor(self, chars=0):
"""Move cursor to left or right (unit: characters)"""
direction = QTextCursor.Right if chars > 0 else QTextCursor.Left
for _i in range(abs(chars)):
self.moveCursor(direction, QTextCursor.MoveAnchor) |
Return True if cursor is on the first line
def is_cursor_on_first_line(self):
"""Return True if cursor is on the first line"""
cursor = self.textCursor()
cursor.movePosition(QTextCursor.StartOfBlock)
return cursor.atStart() |
Return True if cursor is on the last line
def is_cursor_on_last_line(self):
"""Return True if cursor is on the last line"""
cursor = self.textCursor()
cursor.movePosition(QTextCursor.EndOfBlock)
return cursor.atEnd() |
Return True if cursor is before *position*
def is_cursor_before(self, position, char_offset=0):
"""Return True if cursor is before *position*"""
position = self.get_position(position) + char_offset
cursor = self.textCursor()
cursor.movePosition(QTextCursor.End)
if position ... |
Move cursor to next *what* ('word' or 'character')
toward *direction* ('left' or 'right')
def move_cursor_to_next(self, what='word', direction='left'):
"""
Move cursor to next *what* ('word' or 'character')
toward *direction* ('left' or 'right')
"""
self.__move_cur... |
Clear current selection
def clear_selection(self):
"""Clear current selection"""
cursor = self.textCursor()
cursor.clearSelection()
self.setTextCursor(cursor) |
Extend selection to next *what* ('word' or 'character')
toward *direction* ('left' or 'right')
def extend_selection_to_next(self, what='word', direction='left'):
"""
Extend selection to next *what* ('word' or 'character')
toward *direction* ('left' or 'right')
"""
... |
Return text line at line number *line_nb*
def get_text_line(self, line_nb):
"""Return text line at line number *line_nb*"""
# Taking into account the case when a file ends in an empty line,
# since splitlines doesn't return that line as the last element
# TODO: Make this function mo... |
Return text between *position_from* and *position_to*
Positions may be positions or 'sol', 'eol', 'sof', 'eof' or 'cursor'
def get_text(self, position_from, position_to):
"""
Return text between *position_from* and *position_to*
Positions may be positions or 'sol', 'eol', 'sof', 'eo... |
Return character at *position* with the given offset.
def get_character(self, position, offset=0):
"""Return character at *position* with the given offset."""
position = self.get_position(position) + offset
cursor = self.textCursor()
cursor.movePosition(QTextCursor.End)
if ... |
Return current word, i.e. word at cursor position,
and the start position
def get_current_word_and_position(self, completion=False):
"""Return current word, i.e. word at cursor position,
and the start position"""
cursor = self.textCursor()
if cursor.hasSelection()... |
Return current word, i.e. word at cursor position
def get_current_word(self, completion=False):
"""Return current word, i.e. word at cursor position"""
ret = self.get_current_word_and_position(completion)
if ret is not None:
return ret[0] |
Return current line's text
def get_current_line(self):
"""Return current line's text"""
cursor = self.textCursor()
cursor.select(QTextCursor.BlockUnderCursor)
return to_text_string(cursor.selectedText()) |
Return line at *coordinates* (QPoint)
def get_line_at(self, coordinates):
"""Return line at *coordinates* (QPoint)"""
cursor = self.cursorForPosition(coordinates)
cursor.select(QTextCursor.BlockUnderCursor)
return to_text_string(cursor.selectedText()).replace(u'\u2029', '') |
Return word at *coordinates* (QPoint)
def get_word_at(self, coordinates):
"""Return word at *coordinates* (QPoint)"""
cursor = self.cursorForPosition(coordinates)
cursor.select(QTextCursor.WordUnderCursor)
return to_text_string(cursor.selectedText()) |
Return line indentation (character number)
def get_block_indentation(self, block_nb):
"""Return line indentation (character number)"""
text = to_text_string(self.document().findBlockByNumber(block_nb).text())
text = text.replace("\t", " "*self.tab_stop_width_spaces)
return len(text)... |
Return selection bounds (block numbers)
def get_selection_bounds(self):
"""Return selection bounds (block numbers)"""
cursor = self.textCursor()
start, end = cursor.selectionStart(), cursor.selectionEnd()
block_start = self.document().findBlock(start)
block_end = self.docum... |
Return text selected by current text cursor, converted in unicode
Replace the unicode line separator character \u2029 by
the line separator characters returned by get_line_separator
def get_selected_text(self):
"""
Return text selected by current text cursor, converted in unicode
... |
Replace selected text by *text*
If *pattern* is not None, replacing selected text using regular
expression text substitution
def replace(self, text, pattern=None):
"""Replace selected text by *text*
If *pattern* is not None, replacing selected text using regular
expression ... |
Reimplement QTextDocument's find method
Add support for *multiline* regular expressions
def find_multiline_pattern(self, regexp, cursor, findflag):
"""Reimplement QTextDocument's find method
Add support for *multiline* regular expressions"""
pattern = to_text_string(regexp.patte... |
Find text
def find_text(self, text, changed=True, forward=True, case=False,
words=False, regexp=False):
"""Find text"""
cursor = self.textCursor()
findflag = QTextDocument.FindFlag()
if not forward:
findflag = findflag | QTextDocument.FindBackward
... |
Get the number of matches for the searched text.
def get_number_matches(self, pattern, source_text='', case=False,
regexp=False):
"""Get the number of matches for the searched text."""
pattern = to_text_string(pattern)
if not pattern:
return 0
... |
Get number of the match for the searched text.
def get_match_number(self, pattern, case=False, regexp=False):
"""Get number of the match for the searched text."""
position = self.textCursor().position()
source_text = self.get_text(position_from='sof', position_to=position)
match_num... |
Go to error
def mouseReleaseEvent(self, event):
"""Go to error"""
self.QT_CLASS.mouseReleaseEvent(self, event)
text = self.get_line_at(event.pos())
if get_error_match(text) and not self.has_selected_text():
if self.go_to_error is not None:
self.go_to_er... |
Show Pointing Hand Cursor on error messages
def mouseMoveEvent(self, event):
"""Show Pointing Hand Cursor on error messages"""
text = self.get_line_at(event.pos())
if get_error_match(text):
if not self.__cursor_changed:
QApplication.setOverrideCursor(QCursor(Qt.... |
If cursor has not been restored yet, do it now
def leaveEvent(self, event):
"""If cursor has not been restored yet, do it now"""
if self.__cursor_changed:
QApplication.restoreOverrideCursor()
self.__cursor_changed = False
self.QT_CLASS.leaveEvent(self, event) |
Show signature calltip and/or docstring in the Help plugin
def show_object_info(self, text, call=False, force=False):
"""Show signature calltip and/or docstring in the Help plugin"""
text = to_text_string(text)
# Show docstring
help_enabled = self.help_enabled or force
if... |
Create history_filename with INITHISTORY if it doesn't exist.
def create_history_filename(self):
"""Create history_filename with INITHISTORY if it doesn't exist."""
if self.history_filename and not osp.isfile(self.history_filename):
try:
encoding.writelines(self.INITHIST... |
Add command to history
def add_to_history(self, command):
"""Add command to history"""
command = to_text_string(command)
if command in ['', '\n'] or command.startswith('Traceback'):
return
if command.endswith('\n'):
command = command[:-1]
self.hist... |
Browse history
def browse_history(self, backward):
"""Browse history"""
if self.is_cursor_before('eol') and self.hist_wholeline:
self.hist_wholeline = False
tocursor = self.get_current_line_to_cursor()
text, self.histidx = self.find_in_history(tocursor, self.histidx,
... |
Find text 'tocursor' in history, from index 'start_idx
def find_in_history(self, tocursor, start_idx, backward):
"""Find text 'tocursor' in history, from index 'start_idx'"""
if start_idx is None:
start_idx = len(self.history)
# Finding text in history
step = -1 if back... |
Return a QKeySequence representation of the provided QKeyEvent.
def keyevent_to_keyseq(self, event):
"""Return a QKeySequence representation of the provided QKeyEvent."""
self.keyPressEvent(event)
event.accept()
return self.keySequence() |
Qt method extension.
def setText(self, sequence):
"""Qt method extension."""
self.setToolTip(sequence)
super(ShortcutLineEdit, self).setText(sequence) |
Set the filter text.
def set_text(self, text):
"""Set the filter text."""
text = text.strip()
new_text = self.text() + text
self.setText(new_text) |
Qt Override.
def keyPressEvent(self, event):
"""Qt Override."""
key = event.key()
if key in [Qt.Key_Up]:
self._parent.previous_row()
elif key in [Qt.Key_Down]:
self._parent.next_row()
elif key in [Qt.Key_Enter, Qt.Key_Return]:
self._pa... |
Setup the ShortcutEditor with the provided arguments.
def setup(self):
"""Setup the ShortcutEditor with the provided arguments."""
# Widgets
icon_info = HelperToolButton()
icon_info.setIcon(get_std_icon('MessageBoxInformation'))
layout_icon_info = QVBoxLayout()
lay... |
Qt method override.
def event(self, event):
"""Qt method override."""
if event.type() in (QEvent.Shortcut, QEvent.ShortcutOverride):
return True
else:
return super(ShortcutEditor, self).event(event) |
Qt method override.
def keyPressEvent(self, event):
"""Qt method override."""
event_key = event.key()
if not event_key or event_key == Qt.Key_unknown:
return
if len(self._qsequences) == 4:
# QKeySequence accepts a maximum of 4 different sequences.
... |
Check shortcuts for conflicts.
def check_conflicts(self):
"""Check shortcuts for conflicts."""
conflicts = []
if len(self._qsequences) == 0:
return conflicts
new_qsequence = self.new_qsequence
for shortcut in self.shortcuts:
shortcut_qsequence = ... |
Check if the first sub-sequence of the new key sequence is valid.
def check_singlekey(self):
"""Check if the first sub-sequence of the new key sequence is valid."""
if len(self._qsequences) == 0:
return True
else:
keystr = self._qsequences[0]
valid_sing... |
Update the warning label, buttons state and sequence text.
def update_warning(self):
"""Update the warning label, buttons state and sequence text."""
new_qsequence = self.new_qsequence
new_sequence = self.new_sequence
self.text_new_sequence.setText(
new_qsequence.toStri... |
This is a convenience method to set the new QKeySequence of the
shortcut editor from a string.
def set_sequence_from_str(self, sequence):
"""
This is a convenience method to set the new QKeySequence of the
shortcut editor from a string.
"""
self._qsequences = [QKey... |
Set the new sequence to the default value defined in the config.
def set_sequence_to_default(self):
"""Set the new sequence to the default value defined in the config."""
sequence = CONF.get_default(
'shortcuts', "{}/{}".format(self.context, self.name))
self._qsequences = sequen... |
Unbind all conflicted shortcuts, and accept the new one
def accept_override(self):
"""Unbind all conflicted shortcuts, and accept the new one"""
conflicts = self.check_conflicts()
if conflicts:
for shortcut in conflicts:
shortcut.key = ''
self.accept() |
Get the currently selected index in the parent table view.
def current_index(self):
"""Get the currently selected index in the parent table view."""
i = self._parent.proxy_model.mapToSource(self._parent.currentIndex())
return i |
Qt Override.
def sortByName(self):
"""Qt Override."""
self.shortcuts = sorted(self.shortcuts,
key=lambda x: x.context+'/'+x.name)
self.reset() |
Qt Override.
def data(self, index, role=Qt.DisplayRole):
"""Qt Override."""
row = index.row()
if not index.isValid() or not (0 <= row < len(self.shortcuts)):
return to_qvariant()
shortcut = self.shortcuts[row]
key = shortcut.key
column = index.column... |
Qt Override.
def headerData(self, section, orientation, role=Qt.DisplayRole):
"""Qt Override."""
if role == Qt.TextAlignmentRole:
if orientation == Qt.Horizontal:
return to_qvariant(int(Qt.AlignHCenter | Qt.AlignVCenter))
return to_qvariant(int(Qt.AlignRight... |
Qt Override.
def setData(self, index, value, role=Qt.EditRole):
"""Qt Override."""
if index.isValid() and 0 <= index.row() < len(self.shortcuts):
shortcut = self.shortcuts[index.row()]
column = index.column()
text = from_qvariant(value, str)
if colu... |
Update search letters with text input in search box.
def update_search_letters(self, text):
"""Update search letters with text input in search box."""
self.letters = text
names = [shortcut.name for shortcut in self.shortcuts]
results = get_search_scores(text, names, template='<b>{0}... |
Set regular expression for filter.
def set_filter(self, text):
"""Set regular expression for filter."""
self.pattern = get_search_regex(text)
if self.pattern:
self._parent.setSortingEnabled(False)
else:
self._parent.setSortingEnabled(True)
self.inv... |
Qt override.
Reimplemented from base class to allow the use of custom filtering.
def filterAcceptsRow(self, row_num, parent):
"""Qt override.
Reimplemented from base class to allow the use of custom filtering.
"""
model = self.sourceModel()
name = model.row(row... |
Qt Override.
def focusOutEvent(self, e):
"""Qt Override."""
self.source_model.update_active_row()
super(ShortcutsTable, self).focusOutEvent(e) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.