INSTRUCTION
stringlengths
1
46.3k
RESPONSE
stringlengths
75
80.2k
Allow user to drop supported files
def dropEvent(self, event): """Allow user to drop supported files""" urls = mimedata2url(event.mimeData()) if urls: event.setDropAction(Qt.CopyAction) event.accept() self.sig_files_dropped.emit(urls) else: event.ignore()
Toggle min/max display for numpy arrays
def toggle_minmax(self, state): """Toggle min/max display for numpy arrays""" self.sig_option_changed.emit('minmax', state) self.model.minmax = state
Set format to use in DataframeEditor. Args: new_format (string): e.g. "%.3f"
def set_dataframe_format(self, new_format): """ Set format to use in DataframeEditor. Args: new_format (string): e.g. "%.3f" """ self.sig_option_changed.emit('dataframe_format', new_format) self.model.dataframe_format = new_format
Edit item
def edit_item(self): """Edit item""" index = self.currentIndex() if not index.isValid(): return # TODO: Remove hard coded "Value" column number (3 here) self.edit(index.child(index.row(), 3))
Remove item
def remove_item(self): """Remove item""" indexes = self.selectedIndexes() if not indexes: return for index in indexes: if not index.isValid(): return one = _("Do you want to remove the selected item?") more = _("Do you want...
Copy item
def copy_item(self, erase_original=False): """Copy item""" indexes = self.selectedIndexes() if not indexes: return idx_rows = unsorted_unique([idx.row() for idx in indexes]) if len(idx_rows) > 1 or not indexes[0].isValid(): return orig_key ...
Insert item
def insert_item(self): """Insert item""" index = self.currentIndex() if not index.isValid(): row = self.model.rowCount() else: row = index.row() data = self.model.get_data() if isinstance(data, list): key = row dat...
Plot item
def plot_item(self, funcname): """Plot item""" index = self.currentIndex() if self.__prepare_plot(): key = self.model.get_key(index) try: self.plot(key, funcname) except (ValueError, TypeError) as error: QMessageBox.crit...
Imshow item
def imshow_item(self): """Imshow item""" index = self.currentIndex() if self.__prepare_plot(): key = self.model.get_key(index) try: if self.is_image(key): self.show_image(key) else: self.imsh...
Save array
def save_array(self): """Save array""" title = _( "Save array") if self.array_filename is None: self.array_filename = getcwd_or_home() self.redirect_stdio.emit(False) filename, _selfilter = getsavefilename(self, title, ...
Copy text to clipboard
def copy(self): """Copy text to clipboard""" clipboard = QApplication.clipboard() clipl = [] for idx in self.selectedIndexes(): if not idx.isValid(): continue obj = self.delegate.get_value(idx) # Check if we are trying to copy a...
Import data from string
def import_from_string(self, text, title=None): """Import data from string""" data = self.model.get_data() # Check if data is a dict if not hasattr(data, "keys"): return editor = ImportWizard(self, text, title=title, contents_title...
Import text/data/code from clipboard
def paste(self): """Import text/data/code from clipboard""" clipboard = QApplication.clipboard() cliptext = '' if clipboard.mimeData().hasText(): cliptext = to_text_string(clipboard.text()) if cliptext.strip(): self.import_from_string(cliptext, titl...
Remove values from data
def remove_values(self, keys): """Remove values from data""" data = self.model.get_data() for key in sorted(keys, reverse=True): data.pop(key) self.set_data(data)
Copy value
def copy_value(self, orig_key, new_key): """Copy value""" data = self.model.get_data() if isinstance(data, list): data.append(data[orig_key]) if isinstance(data, set): data.add(data[orig_key]) else: data[new_key] = data[orig_key] ...
Create new value in data
def new_value(self, key, value): """Create new value in data""" data = self.model.get_data() data[key] = value self.set_data(data)
Return True if variable is a list or a tuple
def is_list(self, key): """Return True if variable is a list or a tuple""" data = self.model.get_data() return isinstance(data[key], (tuple, list))
Return True if variable is a set
def is_set(self, key): """Return True if variable is a set""" data = self.model.get_data() return isinstance(data[key], set)
Return sequence length
def get_len(self, key): """Return sequence length""" data = self.model.get_data() return len(data[key])
Return True if variable is a numpy array
def is_array(self, key): """Return True if variable is a numpy array""" data = self.model.get_data() return isinstance(data[key], (ndarray, MaskedArray))
Return True if variable is a PIL.Image image
def is_image(self, key): """Return True if variable is a PIL.Image image""" data = self.model.get_data() return isinstance(data[key], Image)
Return True if variable is a dictionary
def is_dict(self, key): """Return True if variable is a dictionary""" data = self.model.get_data() return isinstance(data[key], dict)
Return array's shape
def get_array_shape(self, key): """Return array's shape""" data = self.model.get_data() return data[key].shape
Return array's ndim
def get_array_ndim(self, key): """Return array's ndim""" data = self.model.get_data() return data[key].ndim
Edit item
def oedit(self, key): """Edit item""" data = self.model.get_data() from spyder.plugins.variableexplorer.widgets.objecteditor import ( oedit) oedit(data[key])
Plot item
def plot(self, key, funcname): """Plot item""" data = self.model.get_data() import spyder.pyplot as plt plt.figure() getattr(plt, funcname)(data[key]) plt.show()
Show item's image
def imshow(self, key): """Show item's image""" data = self.model.get_data() import spyder.pyplot as plt plt.figure() plt.imshow(data[key]) plt.show()
Show image (item is a PIL image)
def show_image(self, key): """Show image (item is a PIL image)""" data = self.model.get_data() data[key].show()
Refresh context menu
def refresh_menu(self): """Refresh context menu""" data = self.model.get_data() index = self.currentIndex() condition = (not isinstance(data, (tuple, set))) and index.isValid() \ and not self.readonly self.edit_action.setEnabled( condition ) sel...
Setup editor.
def setup(self, data, title='', readonly=False, width=650, remote=False, icon=None, parent=None): """Setup editor.""" if isinstance(data, (dict, set)): # dictionnary, set self.data_copy = data.copy() datalen = len(data) elif isinstance(dat...
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.setAutoDefault(True) self.btn_save_and_close.setDefault(True)
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)] # Needed to prevent memory...
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 = osp.join(self.stderr_dir, 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='utf-8') except Ex...
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 the kernel self.stderr_handle.clos...
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 save history self.shellwidget.executing....
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: self.interrupt_kernel() else: self...
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>') # Don't break lines in hyphens # From htt...
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 client_id = ...
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 page_control else: retu...
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, text=_("Stop"),...
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', 'inspect curren...
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: pass
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 """ sw = self.shellwidget if not running_under_pytest() and self.ask_before_restart: message = _('Are you ...
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 # message about it. # So we ...
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')) self.dialog_mana...
Show environment variables.
def show_env(self, env): """Show environment variables.""" self.dialog_manager.show(RemoteEnvDialog(env, parent=self))
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) )
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: self.t0 = time.monotonic() ...
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 = loading_img.replace('\\', '/') message = _("Con...
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_ready.disconnect(self._hide_loading_page)
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() # This is needed to avoid show...
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_ipython().kernel._show_mpl_backend_errors()") self.shellwidget....
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 line, local cursor position, or local point. """ # Check that no option or only one option is given: ...
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 = widget.palette() background = palette.col...
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. This will display title and text as separate sections and add `...` if `ellide` is True and the text is too long. """ template = ''' <div sty...
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_COLOR, is_python=False): """ Create HTML template for signature. This template will include indent after the method name, a highlight ...
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, is_python=False): """ Show calltip. Calltips look like tooltips but will not disappear if mouse hovers them. They are useful for displaying signature informat...
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 disappear if mouse hovers them. They are meant for quick inspections. """ if text is not None and ...
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 = sourcecode.get_eol_chars(text) is_document_modified = eol_chars ...
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_line_separator() txt = linesep.join(lines) if utext.endswith('\...
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 elif subject == 'sol': cursor.movePosition(QTextCursor.StartOfBlock) ...
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 < cursor.position(): cursor.set...
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_cursor_anchor(what, direction, QTextCursor.MoveAnchor)
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') """ self.__move_cursor_anchor(what, direction, QTextCursor.KeepAnchor)
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 more efficient try: ret...
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', 'eof' or 'cursor' """ cursor = self.__select_text(position_from, position_to) text = to_text_string(cursor.se...
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 position < cursor.position(): cursor.setPo...
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(): # Removes the selection and moves the cursor to the left side ...
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)-len(text.lstrip())
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.document().findBlock(end) return sort...
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 the unicode line separator character \u2029 by the line separator characters returned by get_line_separator """ return to_text_string(self.textCursor().selec...
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 text substitution""" cursor = self.textCursor() cursor.beginEditBlock() if pattern is not None: seltxt =...
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.pattern()) text = to_text_string(self.toPlainText()) try: regobj = re.comp...
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 i...
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 if not regexp: pattern = re.escap...
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_number = self.get_number_matches(pattern, ...