text_prompt
stringlengths
100
17.7k
code_prompt
stringlengths
7
9.86k
<SYSTEM_TASK:> Resize the current column to its contents. <END_TASK> <USER_TASK:> Description: def _resizeCurrentColumnToContents(self, new_index, old_index): """Resize the current column to its contents."""
if new_index.column() not in self._autosized_cols: # Ensure the requested column is fully into view after resizing self._resizeVisibleColumnsToContents() self.dataTable.scrollTo(new_index)
<SYSTEM_TASK:> Resize the columns to its contents. <END_TASK> <USER_TASK:> Description: def resizeColumnsToContents(self): """Resize the columns to its contents."""
self._autosized_cols = set() self._resizeColumnsToContents(self.table_level, self.table_index, self._max_autosize_ms) self._update_layout()
<SYSTEM_TASK:> Ask user for display format for floats and use it. <END_TASK> <USER_TASK:> Description: def change_format(self): """ Ask user for display format for floats and use it. This function also checks whether the format is valid and emits `sig_option_changed`. """
format, valid = QInputDialog.getText(self, _('Format'), _("Float formatting"), QLineEdit.Normal, self.dataModel.get_format()) if valid: format = str(format) try: format % 1.1 except: msg = _("Format ({}) is incorrect").format(format) QMessageBox.critical(self, _("Error"), msg) return if not format.startswith('%'): msg = _("Format ({}) should start with '%'").format(format) QMessageBox.critical(self, _("Error"), msg) return self.dataModel.set_format(format) self.sig_option_changed.emit('dataframe_format', format)
<SYSTEM_TASK:> Update the column width of the header. <END_TASK> <USER_TASK:> Description: def _update_header_size(self): """Update the column width of the header."""
column_count = self.table_header.model().columnCount() for index in range(0, column_count): if index < column_count: column_width = self.dataTable.columnWidth(index) self.table_header.setColumnWidth(index, column_width) else: break
<SYSTEM_TASK:> Add the cog menu button to the toolbar. <END_TASK> <USER_TASK:> Description: def setup_options_button(self): """Add the cog menu button to the toolbar."""
if not self.options_button: self.options_button = create_toolbutton( self, text=_('Options'), icon=ima.icon('tooloptions')) actions = self.actions + [MENU_SEPARATOR] + self.plugin_actions self.options_menu = QMenu(self) add_actions(self.options_menu, actions) self.options_button.setMenu(self.options_menu) if self.tools_layout.itemAt(self.tools_layout.count() - 1) is None: self.tools_layout.insertWidget( self.tools_layout.count() - 1, self.options_button) else: self.tools_layout.addWidget(self.options_button)
<SYSTEM_TASK:> Option has changed <END_TASK> <USER_TASK:> Description: def option_changed(self, option, value): """Option has changed"""
setattr(self, to_text_string(option), value) self.shellwidget.set_namespace_view_settings() self.refresh_table()
<SYSTEM_TASK:> Reimplement Qt method to be able to save the widget's size from the <END_TASK> <USER_TASK:> Description: def resizeEvent(self, event): """ Reimplement Qt method to be able to save the widget's size from the main application """
QDialog.resizeEvent(self, event) self.size_change.emit(self.size())
<SYSTEM_TASK:> Return True if all widget contents are valid <END_TASK> <USER_TASK:> Description: def is_valid(self): """Return True if all widget contents are valid"""
for lineedit in self.lineedits: if lineedit in self.validate_data and lineedit.isEnabled(): validator, invalid_msg = self.validate_data[lineedit] text = to_text_string(lineedit.text()) if not validator(text): QMessageBox.critical(self, self.get_name(), "%s:<br><b>%s</b>" % (invalid_msg, text), QMessageBox.Ok) return False return True
<SYSTEM_TASK:> Save settings to configuration file <END_TASK> <USER_TASK:> Description: def save_to_conf(self): """Save settings to configuration file"""
for checkbox, (option, _default) in list(self.checkboxes.items()): self.set_option(option, checkbox.isChecked()) for radiobutton, (option, _default) in list(self.radiobuttons.items()): self.set_option(option, radiobutton.isChecked()) for lineedit, (option, _default) in list(self.lineedits.items()): self.set_option(option, to_text_string(lineedit.text())) for textedit, (option, _default) in list(self.textedits.items()): self.set_option(option, to_text_string(textedit.toPlainText())) for spinbox, (option, _default) in list(self.spinboxes.items()): self.set_option(option, spinbox.value()) for combobox, (option, _default) in list(self.comboboxes.items()): data = combobox.itemData(combobox.currentIndex()) self.set_option(option, from_qvariant(data, to_text_string)) for (fontbox, sizebox), option in list(self.fontboxes.items()): font = fontbox.currentFont() font.setPointSize(sizebox.value()) self.set_font(font, option) for clayout, (option, _default) in list(self.coloredits.items()): self.set_option(option, to_text_string(clayout.lineedit.text())) for (clayout, cb_bold, cb_italic), (option, _default) in list(self.scedits.items()): color = to_text_string(clayout.lineedit.text()) bold = cb_bold.isChecked() italic = cb_italic.isChecked() self.set_option(option, (color, bold, italic))
<SYSTEM_TASK:> Prompt the user with a request to restart. <END_TASK> <USER_TASK:> Description: def prompt_restart_required(self): """Prompt the user with a request to restart."""
restart_opts = self.restart_options changed_opts = self.changed_options options = [restart_opts[o] for o in changed_opts if o in restart_opts] if len(options) == 1: msg_start = _("Spyder needs to restart to change the following " "setting:") else: msg_start = _("Spyder needs to restart to change the following " "settings:") msg_end = _("Do you wish to restart now?") msg_options = u"" for option in options: msg_options += u"<li>{0}</li>".format(option) msg_title = _("Information") msg = u"{0}<ul>{1}</ul><br>{2}".format(msg_start, msg_options, msg_end) answer = QMessageBox.information(self, msg_title, msg, QMessageBox.Yes | QMessageBox.No) if answer == QMessageBox.Yes: self.restart()
<SYSTEM_TASK:> Restoring scrollbar position after main window is visible <END_TASK> <USER_TASK:> Description: def restore_scrollbar_position(self): """Restoring scrollbar position after main window is visible"""
scrollbar_pos = self.get_option('scrollbar_position', None) if scrollbar_pos is not None: self.explorer.treewidget.set_scrollbar_position(scrollbar_pos)
<SYSTEM_TASK:> Checks if there is an update available. <END_TASK> <USER_TASK:> Description: def check_update_available(self): """Checks if there is an update available. It takes as parameters the current version of Spyder and a list of valid cleaned releases in chronological order. Example: ['2.3.2', '2.3.3' ...] or with github ['2.3.4', '2.3.3' ...] """
# Don't perform any check for development versions if 'dev' in self.version: return (False, latest_release) # Filter releases if is_stable_version(self.version): releases = [r for r in self.releases if is_stable_version(r)] else: releases = [r for r in self.releases if not is_stable_version(r) or r in self.version] latest_release = releases[-1] return (check_version(self.version, latest_release, '<'), latest_release)
<SYSTEM_TASK:> Create shortcuts for this widget <END_TASK> <USER_TASK:> Description: def create_shortcuts(self, parent): """Create shortcuts for this widget"""
# Configurable findnext = config_shortcut(self.find_next, context='_', name='Find next', parent=parent) findprev = config_shortcut(self.find_previous, context='_', name='Find previous', parent=parent) togglefind = config_shortcut(self.show, context='_', name='Find text', parent=parent) togglereplace = config_shortcut(self.show_replace, context='_', name='Replace text', parent=parent) hide = config_shortcut(self.hide, context='_', name='hide find and replace', parent=self) return [findnext, findprev, togglefind, togglereplace, hide]
<SYSTEM_TASK:> Toggle the 'highlight all results' feature <END_TASK> <USER_TASK:> Description: def toggle_highlighting(self, state): """Toggle the 'highlight all results' feature"""
if self.editor is not None: if state: self.highlight_matches() else: self.clear_matches()
<SYSTEM_TASK:> Show replace widgets <END_TASK> <USER_TASK:> Description: def show_replace(self): """Show replace widgets"""
self.show(hide_replace=False) for widget in self.replace_widgets: widget.show()
<SYSTEM_TASK:> Find next occurrence <END_TASK> <USER_TASK:> Description: def find_next(self): """Find next occurrence"""
state = self.find(changed=False, forward=True, rehighlight=False, multiline_replace_check=False) self.editor.setFocus() self.search_text.add_current_text() return state
<SYSTEM_TASK:> Find previous occurrence <END_TASK> <USER_TASK:> Description: def find_previous(self): """Find previous occurrence"""
state = self.find(changed=False, forward=False, rehighlight=False, multiline_replace_check=False) self.editor.setFocus() return state
<SYSTEM_TASK:> Highlight found results <END_TASK> <USER_TASK:> Description: def highlight_matches(self): """Highlight found results"""
if self.is_code_editor and self.highlight_button.isChecked(): text = self.search_text.currentText() words = self.words_button.isChecked() regexp = self.re_button.isChecked() self.editor.highlight_found_results(text, words=words, regexp=regexp)
<SYSTEM_TASK:> Replace and find <END_TASK> <USER_TASK:> Description: def replace_find(self, focus_replace_text=False, replace_all=False): """Replace and find"""
if (self.editor is not None): replace_text = to_text_string(self.replace_text.currentText()) search_text = to_text_string(self.search_text.currentText()) re_pattern = None # Check regexp before proceeding if self.re_button.isChecked(): try: re_pattern = re.compile(search_text) # Check if replace_text can be substituted in re_pattern # Fixes issue #7177 re_pattern.sub(replace_text, '') except re.error: # Do nothing with an invalid regexp return case = self.case_button.isChecked() first = True cursor = None while True: if first: # First found seltxt = to_text_string(self.editor.get_selected_text()) cmptxt1 = search_text if case else search_text.lower() cmptxt2 = seltxt if case else seltxt.lower() if re_pattern is None: has_selected = self.editor.has_selected_text() if has_selected and cmptxt1 == cmptxt2: # Text was already found, do nothing pass else: if not self.find(changed=False, forward=True, rehighlight=False): break else: if len(re_pattern.findall(cmptxt2)) > 0: pass else: if not self.find(changed=False, forward=True, rehighlight=False): break first = False wrapped = False position = self.editor.get_position('cursor') position0 = position cursor = self.editor.textCursor() cursor.beginEditBlock() else: position1 = self.editor.get_position('cursor') if is_position_inf(position1, position0 + len(replace_text) - len(search_text) + 1): # Identify wrapping even when the replace string # includes part of the search string wrapped = True if wrapped: if position1 == position or \ is_position_sup(position1, position): # Avoid infinite loop: replace string includes # part of the search string break if position1 == position0: # Avoid infinite loop: single found occurrence break position0 = position1 if re_pattern is None: cursor.removeSelectedText() cursor.insertText(replace_text) else: seltxt = to_text_string(cursor.selectedText()) cursor.removeSelectedText() cursor.insertText(re_pattern.sub(replace_text, seltxt)) if self.find_next(): found_cursor = self.editor.textCursor() cursor.setPosition(found_cursor.selectionStart(), QTextCursor.MoveAnchor) cursor.setPosition(found_cursor.selectionEnd(), QTextCursor.KeepAnchor) else: break if not replace_all: break if cursor is not None: cursor.endEditBlock() if focus_replace_text: self.replace_text.setFocus()
<SYSTEM_TASK:> Replace and find in the current selection <END_TASK> <USER_TASK:> Description: def replace_find_selection(self, focus_replace_text=False): """Replace and find in the current selection"""
if self.editor is not None: replace_text = to_text_string(self.replace_text.currentText()) search_text = to_text_string(self.search_text.currentText()) case = self.case_button.isChecked() words = self.words_button.isChecked() re_flags = re.MULTILINE if case else re.IGNORECASE|re.MULTILINE re_pattern = None if self.re_button.isChecked(): pattern = search_text else: pattern = re.escape(search_text) replace_text = re.escape(replace_text) if words: # match whole words only pattern = r'\b{pattern}\b'.format(pattern=pattern) # Check regexp before proceeding try: re_pattern = re.compile(pattern, flags=re_flags) # Check if replace_text can be substituted in re_pattern # Fixes issue #7177 re_pattern.sub(replace_text, '') except re.error as e: # Do nothing with an invalid regexp return selected_text = to_text_string(self.editor.get_selected_text()) replacement = re_pattern.sub(replace_text, selected_text) if replacement != selected_text: cursor = self.editor.textCursor() cursor.beginEditBlock() cursor.removeSelectedText() if not self.re_button.isChecked(): replacement = re.sub(r'\\(?![nrtf])(.)', r'\1', replacement) cursor.insertText(replacement) cursor.endEditBlock() if focus_replace_text: self.replace_text.setFocus() else: self.editor.setFocus()
<SYSTEM_TASK:> Change number of match and total matches. <END_TASK> <USER_TASK:> Description: def change_number_matches(self, current_match=0, total_matches=0): """Change number of match and total matches."""
if current_match and total_matches: matches_string = u"{} {} {}".format(current_match, _(u"of"), total_matches) self.number_matches_text.setText(matches_string) elif total_matches: matches_string = u"{} {}".format(total_matches, _(u"matches")) self.number_matches_text.setText(matches_string) else: self.number_matches_text.setText(_(u"no matches"))
<SYSTEM_TASK:> Switch to plain text mode <END_TASK> <USER_TASK:> Description: def switch_to_plain_text(self): """Switch to plain text mode"""
self.rich_help = False self.plain_text.show() self.rich_text.hide() self.plain_text_action.setChecked(True)
<SYSTEM_TASK:> Show the Spyder tutorial in the Help plugin, opening it if needed <END_TASK> <USER_TASK:> Description: def show_tutorial(self): """Show the Spyder tutorial in the Help plugin, opening it if needed"""
self.switch_to_plugin() tutorial_path = get_module_source_path('spyder.plugins.help.utils') tutorial = osp.join(tutorial_path, 'tutorial.rst') text = open(tutorial).read() self.show_rich_text(text, collapse=True)
<SYSTEM_TASK:> Set object analyzed by Help <END_TASK> <USER_TASK:> Description: def set_object_text(self, text, force_refresh=False, ignore_unknown=False): """Set object analyzed by Help"""
if (self.locked and not force_refresh): return self.switch_to_console_source() add_to_combo = True if text is None: text = to_text_string(self.combo.currentText()) add_to_combo = False found = self.show_help(text, ignore_unknown=ignore_unknown) if ignore_unknown and not found: return if add_to_combo: self.combo.add_text(text) if found: self.save_history() if self.dockwidget is not None: self.dockwidget.blockSignals(True) self.__eventually_raise_help(text, force=force_refresh) if self.dockwidget is not None: self.dockwidget.blockSignals(False)
<SYSTEM_TASK:> Use the help plugin to show docstring dictionary computed <END_TASK> <USER_TASK:> Description: def set_editor_doc(self, doc, force_refresh=False): """ Use the help plugin to show docstring dictionary computed with introspection plugin from the Editor plugin """
if (self.locked and not force_refresh): return self.switch_to_editor_source() self._last_editor_doc = doc self.object_edit.setText(doc['obj_text']) if self.rich_help: self.render_sphinx_doc(doc) else: self.set_plain_text(doc, is_code=False) if self.dockwidget is not None: self.dockwidget.blockSignals(True) self.__eventually_raise_help(doc['docstring'], force=force_refresh) if self.dockwidget is not None: self.dockwidget.blockSignals(False)
<SYSTEM_TASK:> Toggle between sphinxified docstrings or plain ones <END_TASK> <USER_TASK:> Description: def toggle_rich_text(self, checked): """Toggle between sphinxified docstrings or plain ones"""
if checked: self.docstring = not checked self.switch_to_rich_text() self.set_option('rich_mode', checked)
<SYSTEM_TASK:> Return shell which is currently bound to Help, <END_TASK> <USER_TASK:> Description: def get_shell(self): """ Return shell which is currently bound to Help, or another running shell if it has been terminated """
if (not hasattr(self.shell, 'get_doc') or (hasattr(self.shell, 'is_running') and not self.shell.is_running())): self.shell = None if self.main.ipyconsole is not None: shell = self.main.ipyconsole.get_current_shellwidget() if shell is not None and shell.kernel_client is not None: self.shell = shell if self.shell is None: self.shell = self.internal_shell return self.shell
<SYSTEM_TASK:> Checks if the textCursor is in the decoration. <END_TASK> <USER_TASK:> Description: def contains_cursor(self, cursor): """ Checks if the textCursor is in the decoration. :param cursor: The text cursor to test :type cursor: QtGui.QTextCursor :returns: True if the cursor is over the selection """
start = self.cursor.selectionStart() end = self.cursor.selectionEnd() if cursor.atBlockEnd(): end -= 1 return start <= cursor.position() <= end
<SYSTEM_TASK:> Underlines the text. <END_TASK> <USER_TASK:> Description: def set_as_underlined(self, color=Qt.blue): """ Underlines the text. :param color: underline color. """
self.format.setUnderlineStyle( QTextCharFormat.SingleUnderline) self.format.setUnderlineColor(color)
<SYSTEM_TASK:> Underlines text as a spellcheck error. <END_TASK> <USER_TASK:> Description: def set_as_spell_check(self, color=Qt.blue): """ Underlines text as a spellcheck error. :param color: Underline color :type color: QtGui.QColor """
self.format.setUnderlineStyle( QTextCharFormat.SpellCheckUnderline) self.format.setUnderlineColor(color)
<SYSTEM_TASK:> Highlights text as a syntax error. <END_TASK> <USER_TASK:> Description: def set_as_error(self, color=Qt.red): """ Highlights text as a syntax error. :param color: Underline color :type color: QtGui.QColor """
self.format.setUnderlineStyle( QTextCharFormat.WaveUnderline) self.format.setUnderlineColor(color)
<SYSTEM_TASK:> Highlights text as a syntax warning. <END_TASK> <USER_TASK:> Description: def set_as_warning(self, color=QColor("orange")): """ Highlights text as a syntax warning. :param color: Underline color :type color: QtGui.QColor """
self.format.setUnderlineStyle( QTextCharFormat.WaveUnderline) self.format.setUnderlineColor(color)
<SYSTEM_TASK:> Close threads associated to parent_id <END_TASK> <USER_TASK:> Description: def close_threads(self, parent): """Close threads associated to parent_id"""
logger.debug("Call ThreadManager's 'close_threads'") if parent is None: # Closing all threads self.pending_threads = [] threadlist = [] for threads in list(self.started_threads.values()): threadlist += threads else: parent_id = id(parent) self.pending_threads = [(_th, _id) for (_th, _id) in self.pending_threads if _id != parent_id] threadlist = self.started_threads.get(parent_id, []) for thread in threadlist: logger.debug("Waiting for thread %r to finish" % thread) while thread.isRunning(): # We can't terminate thread safely, so we simply wait... QApplication.processEvents()
<SYSTEM_TASK:> Editor's text has changed <END_TASK> <USER_TASK:> Description: def text_changed(self): """Editor's text has changed"""
self.default = False self.editor.document().changed_since_autosave = True self.text_changed_at.emit(self.filename, self.editor.get_position('cursor'))
<SYSTEM_TASK:> Remove editors that are not longer open. <END_TASK> <USER_TASK:> Description: def refresh(self): """Remove editors that are not longer open."""
self._update_id_list() for _id in self.history[:]: if _id not in self.id_list: self.history.remove(_id)
<SYSTEM_TASK:> Remove the widget at the corresponding tab_index. <END_TASK> <USER_TASK:> Description: def remove(self, tab_index): """Remove the widget at the corresponding tab_index."""
_id = id(self.editor.tabs.widget(tab_index)) if _id in self.history: self.history.remove(_id)
<SYSTEM_TASK:> Remove previous entrances of a tab, and add it as the latest. <END_TASK> <USER_TASK:> Description: def remove_and_append(self, index): """Remove previous entrances of a tab, and add it as the latest."""
while index in self: self.remove(index) self.append(index)
<SYSTEM_TASK:> Fill ListWidget with the tabs texts. <END_TASK> <USER_TASK:> Description: def load_data(self): """Fill ListWidget with the tabs texts. Add elements in inverse order of stack_history. """
for index in reversed(self.stack_history): text = self.tabs.tabText(index) text = text.replace('&', '') item = QListWidgetItem(ima.icon('TextFileIcon'), text) self.addItem(item)
<SYSTEM_TASK:> Change to the selected document and hide this widget. <END_TASK> <USER_TASK:> Description: def item_selected(self, item=None): """Change to the selected document and hide this widget."""
if item is None: item = self.currentItem() # stack history is in inverse order try: index = self.stack_history[-(self.currentRow()+1)] except IndexError: pass else: self.editor.set_stack_index(index) self.editor.current_changed(index) self.hide()
<SYSTEM_TASK:> Move selected row a number of steps. <END_TASK> <USER_TASK:> Description: def select_row(self, steps): """Move selected row a number of steps. Iterates in a cyclic behaviour. """
row = (self.currentRow() + steps) % self.count() self.setCurrentRow(row)
<SYSTEM_TASK:> Positions the tab switcher in the top-center of the editor. <END_TASK> <USER_TASK:> Description: def set_dialog_position(self): """Positions the tab switcher in the top-center of the editor."""
left = self.editor.geometry().width()/2 - self.width()/2 top = self.editor.tabs.tabBar().geometry().height() self.move(self.editor.mapToGlobal(QPoint(left, top)))
<SYSTEM_TASK:> Reimplement Qt method. <END_TASK> <USER_TASK:> Description: def keyReleaseEvent(self, event): """Reimplement Qt method. Handle "most recent used" tab behavior, When ctrl is released and tab_switcher is visible, tab will be changed. """
if self.isVisible(): qsc = get_shortcut(context='Editor', name='Go to next file') for key in qsc.split('+'): key = key.lower() if ((key == 'ctrl' and event.key() == Qt.Key_Control) or (key == 'alt' and event.key() == Qt.Key_Alt)): self.item_selected() event.accept()
<SYSTEM_TASK:> Reimplement Qt method to allow cyclic behavior. <END_TASK> <USER_TASK:> Description: def keyPressEvent(self, event): """Reimplement Qt method to allow cyclic behavior."""
if event.key() == Qt.Key_Down: self.select_row(1) elif event.key() == Qt.Key_Up: self.select_row(-1)
<SYSTEM_TASK:> Reimplement Qt method to close the widget when loosing focus. <END_TASK> <USER_TASK:> Description: def focusOutEvent(self, event): """Reimplement Qt method to close the widget when loosing focus."""
event.ignore() # Inspired from CompletionWidget.focusOutEvent() in file # widgets/sourcecode/base.py line 212 if sys.platform == "darwin": if event.reason() != Qt.ActiveWindowFocusReason: self.close() else: self.close()
<SYSTEM_TASK:> Set conditional breakpoint <END_TASK> <USER_TASK:> Description: def set_or_edit_conditional_breakpoint(self): """Set conditional breakpoint"""
if self.data: editor = self.get_current_editor() editor.debugger.toogle_breakpoint(edit_condition=True)
<SYSTEM_TASK:> Inspect current object in the Help plugin <END_TASK> <USER_TASK:> Description: def inspect_current_object(self): """Inspect current object in the Help plugin"""
editor = self.get_current_editor() editor.sig_display_signature.connect(self.display_signature_help) line, col = editor.get_cursor_line_column() editor.request_hover(line, col)
<SYSTEM_TASK:> This method is called separately from 'set_oulineexplorer' to avoid <END_TASK> <USER_TASK:> Description: def initialize_outlineexplorer(self): """This method is called separately from 'set_oulineexplorer' to avoid doing unnecessary updates when there are multiple editor windows"""
for index in range(self.get_stack_count()): if index != self.get_stack_index(): self._refresh_outlineexplorer(index=index)
<SYSTEM_TASK:> Setup tab context menu before showing it <END_TASK> <USER_TASK:> Description: def __setup_menu(self): """Setup tab context menu before showing it"""
self.menu.clear() if self.data: actions = self.menu_actions else: actions = (self.new_action, self.open_action) self.setFocus() # --> Editor.__get_focus_editortabwidget add_actions(self.menu, list(actions) + self.__get_split_actions()) self.close_action.setEnabled(self.is_closable)
<SYSTEM_TASK:> Set current filename and return the associated editor instance. <END_TASK> <USER_TASK:> Description: def set_current_filename(self, filename, focus=True): """Set current filename and return the associated editor instance."""
index = self.has_filename(filename) if index is not None: if focus: self.set_stack_index(index) editor = self.data[index].editor if focus: editor.setFocus() else: self.stack_history.remove_and_append(index) return editor
<SYSTEM_TASK:> Return the position index of a file in the tab bar of the editorstack <END_TASK> <USER_TASK:> Description: def get_index_from_filename(self, filename): """ Return the position index of a file in the tab bar of the editorstack from its name. """
filenames = [d.filename for d in self.data] return filenames.index(filename)
<SYSTEM_TASK:> Reorder editorstack.data so it is synchronized with the tab bar when <END_TASK> <USER_TASK:> Description: def move_editorstack_data(self, start, end): """Reorder editorstack.data so it is synchronized with the tab bar when tabs are moved."""
if start < 0 or end < 0: return else: steps = abs(end - start) direction = (end-start) // steps # +1 for right, -1 for left data = self.data self.blockSignals(True) for i in range(start, end, direction): data[i], data[i+direction] = data[i+direction], data[i] self.blockSignals(False) self.refresh()
<SYSTEM_TASK:> Get list of current opened files' languages <END_TASK> <USER_TASK:> Description: def poll_open_file_languages(self): """Get list of current opened files' languages"""
languages = [] for index in range(self.get_stack_count()): languages.append( self.tabs.widget(index).language.lower()) return set(languages)
<SYSTEM_TASK:> Notify language server availability to code editors. <END_TASK> <USER_TASK:> Description: def notify_server_ready(self, language, config): """Notify language server availability to code editors."""
for index in range(self.get_stack_count()): editor = self.tabs.widget(index) if editor.language.lower() == language: editor.start_lsp_services(config)
<SYSTEM_TASK:> Close all files opened to the right <END_TASK> <USER_TASK:> Description: def close_all_right(self): """ Close all files opened to the right """
num = self.get_stack_index() n = self.get_stack_count() for i in range(num, n-1): self.close_file(num+1)
<SYSTEM_TASK:> Close all files but the current one <END_TASK> <USER_TASK:> Description: def close_all_but_this(self): """Close all files but the current one"""
self.close_all_right() for i in range(0, self.get_stack_count()-1 ): self.close_file(0)
<SYSTEM_TASK:> Add to last closed file list. <END_TASK> <USER_TASK:> Description: def add_last_closed_file(self, fname): """Add to last closed file list."""
if fname in self.last_closed_files: self.last_closed_files.remove(fname) self.last_closed_files.insert(0, fname) if len(self.last_closed_files) > 10: self.last_closed_files.pop(-1)
<SYSTEM_TASK:> File was just saved in another editorstack, let's synchronize! <END_TASK> <USER_TASK:> Description: def file_saved_in_other_editorstack(self, original_filename, filename): """ File was just saved in another editorstack, let's synchronize! This avoids file being automatically reloaded. The original filename is passed instead of an index in case the tabs on the editor stacks were moved and are now in a different order - see issue 5703. Filename is passed in case file was just saved as another name. """
index = self.has_filename(original_filename) if index is None: return finfo = self.data[index] finfo.newly_created = False finfo.filename = to_text_string(filename) finfo.lastmodified = QFileInfo(finfo.filename).lastModified()
<SYSTEM_TASK:> Analyze current script with todos <END_TASK> <USER_TASK:> Description: def analyze_script(self, index=None): """Analyze current script with todos"""
if self.is_analysis_done: return if index is None: index = self.get_stack_index() if self.data: finfo = self.data[index] if self.todolist_enabled: finfo.run_todo_finder() self.is_analysis_done = True
<SYSTEM_TASK:> Synchronize todo results between editorstacks <END_TASK> <USER_TASK:> Description: def set_todo_results(self, filename, todo_results): """Synchronize todo results between editorstacks"""
index = self.has_filename(filename) if index is None: return self.data[index].set_todo_results(todo_results)
<SYSTEM_TASK:> Stack index has changed <END_TASK> <USER_TASK:> Description: def current_changed(self, index): """Stack index has changed"""
# count = self.get_stack_count() # for btn in (self.filelist_btn, self.previous_btn, self.next_btn): # btn.setEnabled(count > 1) editor = self.get_current_editor() if editor.lsp_ready and not editor.document_opened: editor.document_did_open() if index != -1: editor.setFocus() logger.debug("Set focus to: %s" % editor.filename) else: self.reset_statusbar.emit() self.opened_files_list_changed.emit() self.stack_history.refresh() self.stack_history.remove_and_append(index) # Needed to avoid an error generated after moving/renaming # files outside Spyder while in debug mode. # See issue 8749. try: logger.debug("Current changed: %d - %s" % (index, self.data[index].editor.filename)) except IndexError: pass self.update_plugin_title.emit() if editor is not None: # Needed in order to handle the close of files open in a directory # that has been renamed. See issue 5157 try: self.current_file_changed.emit(self.data[index].filename, editor.get_position('cursor')) except IndexError: pass
<SYSTEM_TASK:> Editor focus has changed <END_TASK> <USER_TASK:> Description: def focus_changed(self): """Editor focus has changed"""
fwidget = QApplication.focusWidget() for finfo in self.data: if fwidget is finfo.editor: self.refresh() self.editor_focus_changed.emit()
<SYSTEM_TASK:> Order the root file items of the outline explorer as in the tabbar <END_TASK> <USER_TASK:> Description: def _sync_outlineexplorer_file_order(self): """ Order the root file items of the outline explorer as in the tabbar of the current EditorStack. """
if self.outlineexplorer is not None: self.outlineexplorer.treewidget.set_editor_ids_order( [finfo.editor.get_document_id() for finfo in self.data])
<SYSTEM_TASK:> Run selected text or current line in console. <END_TASK> <USER_TASK:> Description: def run_selection(self): """ Run selected text or current line in console. If some text is selected, then execute that text in console. If no text is selected, then execute current line, unless current line is empty. Then, advance cursor to next line. If cursor is on last line and that line is not empty, then add a new blank line and move the cursor there. If cursor is on last line and that line is empty, then do not move cursor. """
text = self.get_current_editor().get_selection_as_executable_code() if text: self.exec_in_extconsole.emit(text.rstrip(), self.focus_to_editor) return editor = self.get_current_editor() line = editor.get_current_line() text = line.lstrip() if text: self.exec_in_extconsole.emit(text, self.focus_to_editor) if editor.is_cursor_on_last_line() and text: editor.append(editor.get_line_separator()) editor.move_cursor_to_next('line', 'down')
<SYSTEM_TASK:> Run the previous cell again. <END_TASK> <USER_TASK:> Description: def re_run_last_cell(self): """Run the previous cell again."""
text, line = (self.get_current_editor() .get_last_cell_as_executable_code()) self._run_cell_text(text, line)
<SYSTEM_TASK:> Create and attach a new EditorSplitter to the current EditorSplitter. <END_TASK> <USER_TASK:> Description: def split(self, orientation=Qt.Vertical): """Create and attach a new EditorSplitter to the current EditorSplitter. The new EditorSplitter widget will contain an EditorStack that is a clone of the current EditorStack. A single EditorSplitter instance can be split multiple times, but the orientation will be the same for all the direct splits. If one of the child splits is split, then that split can have a different orientation. """
self.setOrientation(orientation) self.editorstack.set_orientation(orientation) editorsplitter = EditorSplitter(self.parent(), self.plugin, self.menu_actions, register_editorstack_cb=self.register_editorstack_cb, unregister_editorstack_cb=self.unregister_editorstack_cb) self.addWidget(editorsplitter) editorsplitter.destroyed.connect(lambda: self.editorsplitter_closed()) current_editor = editorsplitter.editorstack.get_current_editor() if current_editor is not None: current_editor.setFocus()
<SYSTEM_TASK:> Add toolbars to a menu. <END_TASK> <USER_TASK:> Description: def add_toolbars_to_menu(self, menu_title, actions): """Add toolbars to a menu."""
# Six is the position of the view menu in menus list # that you can find in plugins/editor.py setup_other_windows. view_menu = self.menus[6] if actions == self.toolbars and view_menu: toolbars = [] for toolbar in self.toolbars: action = toolbar.toggleViewAction() toolbars.append(action) add_actions(view_menu, toolbars)
<SYSTEM_TASK:> A file was saved in editorstack, this notifies others <END_TASK> <USER_TASK:> Description: def file_saved_in_editorstack(self, editorstack_id_str, original_filename, filename): """A file was saved in editorstack, this notifies others"""
for editorstack in self.editorstacks: if str(id(editorstack)) != editorstack_id_str: editorstack.file_saved_in_other_editorstack(original_filename, filename)
<SYSTEM_TASK:> A file was renamed in data in editorstack, this notifies others <END_TASK> <USER_TASK:> Description: def file_renamed_in_data_in_editorstack(self, editorstack_id_str, original_filename, filename): """A file was renamed in data in editorstack, this notifies others"""
for editorstack in self.editorstacks: if str(id(editorstack)) != editorstack_id_str: editorstack.rename_in_data(original_filename, filename)
<SYSTEM_TASK:> Draw the fold region when the mouse is over and non collapsed <END_TASK> <USER_TASK:> Description: def _draw_fold_region_background(self, block, painter): """ Draw the fold region when the mouse is over and non collapsed indicator. :param top: Top position :param block: Current block. :param painter: QPainter """
r = FoldScope(block) th = TextHelper(self.editor) start, end = r.get_range(ignore_blank_lines=True) if start > 0: top = th.line_pos_from_number(start) else: top = 0 bottom = th.line_pos_from_number(end + 1) h = bottom - top if h == 0: h = self.sizeHint().height() w = self.sizeHint().width() self._draw_rect(QRectF(0, top, w, h), painter)
<SYSTEM_TASK:> Draw the background rectangle using the current style primitive color. <END_TASK> <USER_TASK:> Description: def _draw_rect(self, rect, painter): """ Draw the background rectangle using the current style primitive color. :param rect: The fold zone rect to draw :param painter: The widget's painter. """
c = self.editor.sideareas_color grad = QLinearGradient(rect.topLeft(), rect.topRight()) if sys.platform == 'darwin': grad.setColorAt(0, c.lighter(100)) grad.setColorAt(1, c.lighter(110)) outline = c.darker(110) else: grad.setColorAt(0, c.lighter(110)) grad.setColorAt(1, c.lighter(130)) outline = c.darker(100) painter.fillRect(rect, grad) painter.setPen(QPen(outline)) painter.drawLine(rect.topLeft() + QPointF(1, 0), rect.topRight() - QPointF(1, 0)) painter.drawLine(rect.bottomLeft() + QPointF(1, 0), rect.bottomRight() - QPointF(1, 0)) painter.drawLine(rect.topRight() + QPointF(0, 1), rect.bottomRight() - QPointF(0, 1)) painter.drawLine(rect.topLeft() + QPointF(0, 1), rect.bottomLeft() - QPointF(0, 1))
<SYSTEM_TASK:> Find parent scope, if the block is not a fold trigger. <END_TASK> <USER_TASK:> Description: def find_parent_scope(block): """Find parent scope, if the block is not a fold trigger."""
original = block if not TextBlockHelper.is_fold_trigger(block): # search level of next non blank line while block.text().strip() == '' and block.isValid(): block = block.next() ref_lvl = TextBlockHelper.get_fold_lvl(block) - 1 block = original while (block.blockNumber() and (not TextBlockHelper.is_fold_trigger(block) or TextBlockHelper.get_fold_lvl(block) > ref_lvl)): block = block.previous() return block
<SYSTEM_TASK:> Create a decoration and add it to the editor. <END_TASK> <USER_TASK:> Description: def _decorate_block(self, start, end): """ Create a decoration and add it to the editor. Args: start (int) start line of the decoration end (int) end line of the decoration """
color = self._get_scope_highlight_color() draw_order = DRAW_ORDERS.get('codefolding') d = TextDecoration(self.editor.document(), start_line=start, end_line=end+1, draw_order=draw_order) d.set_background(color) d.set_full_width(True, clear=False) self.editor.decorations.add(d) self._scope_decos.append(d)
<SYSTEM_TASK:> Highlights the current fold scope. <END_TASK> <USER_TASK:> Description: def _highlight_block(self, block): """ Highlights the current fold scope. :param block: Block that starts the current fold scope. """
scope = FoldScope(block) if (self._current_scope is None or self._current_scope.get_range() != scope.get_range()): self._current_scope = scope self._clear_scope_decos() # highlight current scope with darker or lighter color start, end = scope.get_range() if not TextBlockHelper.is_collapsed(block): self._decorate_block(start, end)
<SYSTEM_TASK:> Show the block previous blank lines <END_TASK> <USER_TASK:> Description: def _show_previous_blank_lines(block): """ Show the block previous blank lines """
# set previous blank lines visibles pblock = block.previous() while (pblock.text().strip() == '' and pblock.blockNumber() >= 0): pblock.setVisible(True) pblock = pblock.previous()
<SYSTEM_TASK:> Refresh decorations colors. This function is called by the syntax <END_TASK> <USER_TASK:> Description: def refresh_decorations(self, force=False): """ Refresh decorations colors. This function is called by the syntax highlighter when the style changed so that we may update our decorations colors according to the new style. """
cursor = self.editor.textCursor() if (self._prev_cursor is None or force or self._prev_cursor.blockNumber() != cursor.blockNumber()): for deco in self._block_decos: self.editor.decorations.remove(deco) for deco in self._block_decos: deco.set_outline(drift_color( self._get_scope_highlight_color(), 110)) deco.set_background(self._get_scope_highlight_color()) self.editor.decorations.add(deco) self._prev_cursor = cursor
<SYSTEM_TASK:> Refrehes editor content and scollbars. <END_TASK> <USER_TASK:> Description: def _refresh_editor_and_scrollbars(self): """ Refrehes editor content and scollbars. We generate a fake resize event to refresh scroll bar. We have the same problem as described here: http://www.qtcentre.org/threads/44803 and we apply the same solution (don't worry, there is no visual effect, the editor does not grow up at all, even with a value = 500) """
TextHelper(self.editor).mark_whole_doc_dirty() self.editor.repaint() s = self.editor.size() s.setWidth(s.width() + 1) self.editor.resizeEvent(QResizeEvent(self.editor.size(), s))
<SYSTEM_TASK:> Collapses all triggers and makes all blocks with fold level > 0 <END_TASK> <USER_TASK:> Description: def collapse_all(self): """ Collapses all triggers and makes all blocks with fold level > 0 invisible. """
self._clear_block_deco() block = self.editor.document().firstBlock() last = self.editor.document().lastBlock() while block.isValid(): lvl = TextBlockHelper.get_fold_lvl(block) trigger = TextBlockHelper.is_fold_trigger(block) if trigger: if lvl == 0: self._show_previous_blank_lines(block) TextBlockHelper.set_collapsed(block, True) block.setVisible(lvl == 0) if block == last and block.text().strip() == '': block.setVisible(True) self._show_previous_blank_lines(block) block = block.next() self._refresh_editor_and_scrollbars() tc = self.editor.textCursor() tc.movePosition(tc.Start) self.editor.setTextCursor(tc) self.collapse_all_triggered.emit()
<SYSTEM_TASK:> Clear the folded block decorations. <END_TASK> <USER_TASK:> Description: def _clear_block_deco(self): """Clear the folded block decorations."""
for deco in self._block_decos: self.editor.decorations.remove(deco) self._block_decos[:] = []
<SYSTEM_TASK:> Toggle the current fold trigger. <END_TASK> <USER_TASK:> Description: def _on_action_toggle(self): """Toggle the current fold trigger."""
block = FoldScope.find_parent_scope(self.editor.textCursor().block()) self.toggle_fold_trigger(block)
<SYSTEM_TASK:> Highlight the scope of the current caret position. <END_TASK> <USER_TASK:> Description: def _highlight_caret_scope(self): """ Highlight the scope of the current caret position. This get called only if :attr:` spyder.widgets.panels.FoldingPanel.highlight_care_scope` is True. """
cursor = self.editor.textCursor() block_nbr = cursor.blockNumber() if self._block_nbr != block_nbr: block = FoldScope.find_parent_scope( self.editor.textCursor().block()) try: s = FoldScope(block) except ValueError: self._clear_scope_decos() else: self._mouse_over_line = block.blockNumber() if TextBlockHelper.is_fold_trigger(block): self._highlight_block(block) self._block_nbr = block_nbr
<SYSTEM_TASK:> Append an entry to history filename. <END_TASK> <USER_TASK:> Description: def append_to_history(self, filename, command, go_to_eof): """ Append an entry to history filename. Args: filename (str): file to be updated in a new tab. command (str): line to be added. go_to_eof (bool): scroll to the end of file. """
if not is_text_string(filename): # filename is a QString filename = to_text_string(filename.toUtf8(), 'utf-8') command = to_text_string(command) index = self.filenames.index(filename) self.editors[index].append(command) if go_to_eof: self.editors[index].set_cursor_position('eof') self.tabwidget.setCurrentIndex(index)
<SYSTEM_TASK:> Call function req and then emit its results to the LSP server. <END_TASK> <USER_TASK:> Description: def request(req=None, method=None, requires_response=True): """Call function req and then emit its results to the LSP server."""
if req is None: return functools.partial(request, method=method, requires_response=requires_response) @functools.wraps(req) def wrapper(self, *args, **kwargs): if self.lsp_ready: params = req(self, *args, **kwargs) if params is not None: self.emit_request(method, params, requires_response) return wrapper
<SYSTEM_TASK:> Return current client with focus, if any <END_TASK> <USER_TASK:> Description: def get_focus_client(self): """Return current client with focus, if any"""
widget = QApplication.focusWidget() for client in self.get_clients(): if widget is client or widget is client.get_control(): return client
<SYSTEM_TASK:> Run script in current or dedicated client <END_TASK> <USER_TASK:> Description: def run_script(self, filename, wdir, args, debug, post_mortem, current_client, clear_variables): """Run script in current or dedicated client"""
norm = lambda text: remove_backslashes(to_text_string(text)) # Run Cython files in a dedicated console is_cython = osp.splitext(filename)[1] == '.pyx' if is_cython: current_client = False # Select client to execute code on it is_new_client = False if current_client: client = self.get_current_client() else: client = self.get_client_for_file(filename) if client is None: self.create_client_for_file(filename, is_cython=is_cython) client = self.get_current_client() is_new_client = True if client is not None: # Internal kernels, use runfile if client.get_kernel() is not None: line = "%s('%s'" % ('debugfile' if debug else 'runfile', norm(filename)) if args: line += ", args='%s'" % norm(args) if wdir: line += ", wdir='%s'" % norm(wdir) if post_mortem: line += ", post_mortem=True" line += ")" else: # External kernels, use %run line = "%run " if debug: line += "-d " line += "\"%s\"" % to_text_string(filename) if args: line += " %s" % norm(args) try: if client.shellwidget._executing: # Don't allow multiple executions when there's # still an execution taking place # Fixes issue 7293 pass elif client.shellwidget._reading: client.shellwidget._append_html( _("<br><b>Please exit from debugging before trying to " "run a file in this console.</b>\n<hr><br>"), before_prompt=True) return elif current_client: self.execute_code(line, current_client, clear_variables) else: if is_new_client: client.shellwidget.silent_execute('%clear') else: client.shellwidget.execute('%clear') client.shellwidget.sig_prompt_ready.connect( lambda: self.execute_code(line, current_client, clear_variables)) except AttributeError: pass self.switch_to_plugin() else: #XXX: not sure it can really happen QMessageBox.warning(self, _('Warning'), _("No IPython console is currently available to run <b>%s</b>." "<br><br>Please open a new one and try again." ) % osp.basename(filename), QMessageBox.Ok)
<SYSTEM_TASK:> Set current client working directory. <END_TASK> <USER_TASK:> Description: def set_current_client_working_directory(self, directory): """Set current client working directory."""
shellwidget = self.get_current_shellwidget() if shellwidget is not None: shellwidget.set_cwd(directory)
<SYSTEM_TASK:> Set current working directory. <END_TASK> <USER_TASK:> Description: def set_working_directory(self, dirname): """Set current working directory. In the workingdirectory and explorer plugins. """
if dirname: self.main.workingdirectory.chdir(dirname, refresh_explorer=True, refresh_console=False)
<SYSTEM_TASK:> Execute code instructions. <END_TASK> <USER_TASK:> Description: def execute_code(self, lines, current_client=True, clear_variables=False): """Execute code instructions."""
sw = self.get_current_shellwidget() if sw is not None: if sw._reading: pass else: if not current_client: # Clear console and reset namespace for # dedicated clients # See issue 5748 try: sw.sig_prompt_ready.disconnect() except TypeError: pass sw.reset_namespace(warning=False) elif current_client and clear_variables: sw.reset_namespace(warning=False) # Needed to handle an error when kernel_client is none # See issue 6308 try: sw.execute(to_text_string(lines)) except AttributeError: pass self.activateWindow() self.get_current_client().get_control().setFocus()
<SYSTEM_TASK:> Create a client connected to an existing kernel <END_TASK> <USER_TASK:> Description: def create_client_for_kernel(self): """Create a client connected to an existing kernel"""
connect_output = KernelConnectionDialog.get_connection_parameters(self) (connection_file, hostname, sshkey, password, ok) = connect_output if not ok: return else: self._create_client_for_kernel(connection_file, hostname, sshkey, password)
<SYSTEM_TASK:> Connect a client to its kernel <END_TASK> <USER_TASK:> Description: def connect_client_to_kernel(self, client, is_cython=False, is_pylab=False, is_sympy=False): """Connect a client to its kernel"""
connection_file = client.connection_file stderr_handle = None if self.test_no_stderr else client.stderr_handle km, kc = self.create_kernel_manager_and_kernel_client( connection_file, stderr_handle, is_cython=is_cython, is_pylab=is_pylab, is_sympy=is_sympy) # An error occurred if this is True if is_string(km) and kc is None: client.shellwidget.kernel_manager = None client.show_kernel_error(km) return # This avoids a recurrent, spurious NameError when running our # tests in our CIs if not self.testing: kc.started_channels.connect( lambda c=client: self.process_started(c)) kc.stopped_channels.connect( lambda c=client: self.process_finished(c)) kc.start_channels(shell=True, iopub=True) shellwidget = client.shellwidget shellwidget.kernel_manager = km shellwidget.kernel_client = kc
<SYSTEM_TASK:> Generate a Trailets Config instance for shell widgets using our <END_TASK> <USER_TASK:> Description: def config_options(self): """ Generate a Trailets Config instance for shell widgets using our config system This lets us create each widget with its own config """
# ---- Jupyter config ---- try: full_cfg = load_pyconfig_files(['jupyter_qtconsole_config.py'], jupyter_config_dir()) # From the full config we only select the JupyterWidget section # because the others have no effect here. cfg = Config({'JupyterWidget': full_cfg.JupyterWidget}) except: cfg = Config() # ---- Spyder config ---- spy_cfg = Config() # Make the pager widget a rich one (i.e a QTextEdit) spy_cfg.JupyterWidget.kind = 'rich' # Gui completion widget completion_type_o = self.get_option('completion_type') completions = {0: "droplist", 1: "ncurses", 2: "plain"} spy_cfg.JupyterWidget.gui_completion = completions[completion_type_o] # Pager pager_o = self.get_option('use_pager') if pager_o: spy_cfg.JupyterWidget.paging = 'inside' else: spy_cfg.JupyterWidget.paging = 'none' # Calltips calltips_o = self.get_option('show_calltips') spy_cfg.JupyterWidget.enable_calltips = calltips_o # Buffer size buffer_size_o = self.get_option('buffer_size') spy_cfg.JupyterWidget.buffer_size = buffer_size_o # Prompts in_prompt_o = self.get_option('in_prompt') out_prompt_o = self.get_option('out_prompt') if in_prompt_o: spy_cfg.JupyterWidget.in_prompt = in_prompt_o if out_prompt_o: spy_cfg.JupyterWidget.out_prompt = out_prompt_o # Style color_scheme = CONF.get('appearance', 'selected') style_sheet = create_qss_style(color_scheme)[0] spy_cfg.JupyterWidget.style_sheet = style_sheet spy_cfg.JupyterWidget.syntax_style = color_scheme # Merge QtConsole and Spyder configs. Spyder prefs will have # prevalence over QtConsole ones cfg._merge(spy_cfg) return cfg
<SYSTEM_TASK:> Additional options for shell widgets that are not defined <END_TASK> <USER_TASK:> Description: def additional_options(self, is_pylab=False, is_sympy=False): """ Additional options for shell widgets that are not defined in JupyterWidget config options """
options = dict( pylab=self.get_option('pylab'), autoload_pylab=self.get_option('pylab/autoload'), sympy=self.get_option('symbolic_math'), show_banner=self.get_option('show_banner') ) if is_pylab is True: options['autoload_pylab'] = True options['sympy'] = False if is_sympy is True: options['autoload_pylab'] = False options['sympy'] = True return options
<SYSTEM_TASK:> Get all other clients that are connected to the same kernel as `client` <END_TASK> <USER_TASK:> Description: def get_related_clients(self, client): """ Get all other clients that are connected to the same kernel as `client` """
related_clients = [] for cl in self.get_clients(): if cl.connection_file == client.connection_file and \ cl is not client: related_clients.append(cl) return related_clients
<SYSTEM_TASK:> Restart the console <END_TASK> <USER_TASK:> Description: def restart(self): """ Restart the console This is needed when we switch projects to update PYTHONPATH and the selected interpreter """
self.master_clients = 0 self.create_new_client_if_empty = False for i in range(len(self.clients)): client = self.clients[-1] try: client.shutdown() except Exception as e: QMessageBox.warning(self, _('Warning'), _("It was not possible to restart the IPython console " "when switching to this project. The error was<br><br>" "<tt>{0}</tt>").format(e), QMessageBox.Ok) self.close_client(client=client, force=True) self.create_new_client(give_focus=False) self.create_new_client_if_empty = True
<SYSTEM_TASK:> Create a client with its cwd pointing to path. <END_TASK> <USER_TASK:> Description: def create_client_from_path(self, path): """Create a client with its cwd pointing to path."""
self.create_new_client() sw = self.get_current_shellwidget() sw.set_cwd(path)
<SYSTEM_TASK:> Create a client to execute code related to a file. <END_TASK> <USER_TASK:> Description: def create_client_for_file(self, filename, is_cython=False): """Create a client to execute code related to a file."""
# Create client self.create_new_client(filename=filename, is_cython=is_cython) # Don't increase the count of master clients self.master_clients -= 1 # Rename client tab with filename client = self.get_current_client() client.allow_rename = False tab_text = self.disambiguate_fname(filename) self.rename_client_tab(client, tab_text)
<SYSTEM_TASK:> Get client associated with a given file. <END_TASK> <USER_TASK:> Description: def get_client_for_file(self, filename): """Get client associated with a given file."""
client = None for idx, cl in enumerate(self.get_clients()): if self.filenames[idx] == filename: self.tabwidget.setCurrentIndex(idx) client = cl break return client
<SYSTEM_TASK:> Set elapsed time for slave clients. <END_TASK> <USER_TASK:> Description: def set_elapsed_time(self, client): """Set elapsed time for slave clients."""
related_clients = self.get_related_clients(client) for cl in related_clients: if cl.timer is not None: client.create_time_label() client.t0 = cl.t0 client.timer.timeout.connect(client.show_time) client.timer.start(1000) break
<SYSTEM_TASK:> Tunnel connections to a kernel via ssh. <END_TASK> <USER_TASK:> Description: def tunnel_to_kernel(self, connection_info, hostname, sshkey=None, password=None, timeout=10): """ Tunnel connections to a kernel via ssh. Remote ports are specified in the connection info ci. """
lports = zmqtunnel.select_random_ports(4) rports = (connection_info['shell_port'], connection_info['iopub_port'], connection_info['stdin_port'], connection_info['hb_port']) remote_ip = connection_info['ip'] for lp, rp in zip(lports, rports): self.ssh_tunnel(lp, rp, hostname, remote_ip, sshkey, password, timeout) return tuple(lports)
<SYSTEM_TASK:> Create a kernel spec for our own kernels <END_TASK> <USER_TASK:> Description: def create_kernel_spec(self, is_cython=False, is_pylab=False, is_sympy=False): """Create a kernel spec for our own kernels"""
# Before creating our kernel spec, we always need to # set this value in spyder.ini CONF.set('main', 'spyder_pythonpath', self.main.get_spyder_pythonpath()) return SpyderKernelSpec(is_cython=is_cython, is_pylab=is_pylab, is_sympy=is_sympy)
<SYSTEM_TASK:> Create kernel manager and client. <END_TASK> <USER_TASK:> Description: def create_kernel_manager_and_kernel_client(self, connection_file, stderr_handle, is_cython=False, is_pylab=False, is_sympy=False): """Create kernel manager and client."""
# Kernel spec kernel_spec = self.create_kernel_spec(is_cython=is_cython, is_pylab=is_pylab, is_sympy=is_sympy) # Kernel manager try: kernel_manager = QtKernelManager(connection_file=connection_file, config=None, autorestart=True) except Exception: error_msg = _("The error is:<br><br>" "<tt>{}</tt>").format(traceback.format_exc()) return (error_msg, None) kernel_manager._kernel_spec = kernel_spec kwargs = {} if os.name == 'nt': # avoid closing fds on win+Python 3.7 # which prevents interrupts # jupyter_client > 5.2.3 will do this by default kwargs['close_fds'] = False # Catch any error generated when trying to start the kernel # See issue 7302 try: kernel_manager.start_kernel(stderr=stderr_handle, **kwargs) except Exception: error_msg = _("The error is:<br><br>" "<tt>{}</tt>").format(traceback.format_exc()) return (error_msg, None) # Kernel client kernel_client = kernel_manager.client() # Increase time to detect if a kernel is alive # See Issue 3444 kernel_client.hb_channel.time_to_dead = 18.0 return kernel_manager, kernel_client