INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Create a new python worker instance.
def create_python_worker(self, func, *args, **kwargs): """Create a new python worker instance.""" worker = PythonWorker(func, args, kwargs) self._create_worker(worker) return worker
Create a new process worker instance.
def create_process_worker(self, cmd_list, environ=None): """Create a new process worker instance.""" worker = ProcessWorker(cmd_list, environ=environ) self._create_worker(worker) return worker
Terminate all worker processes.
def terminate_all(self): """Terminate all worker processes.""" for worker in self._workers: worker.terminate() # for thread in self._threads: # try: # thread.terminate() # thread.wait() # except Exception: # pas...
Common worker setup.
def _create_worker(self, worker): """Common worker setup.""" worker.sig_started.connect(self._start) self._workers.append(worker)
Gather data about a given file.
def gather_file_data(name): """ Gather data about a given file. Returns a dict with fields name, mtime and size, containing the relevant data for the fiel. """ res = {'name': name} try: res['mtime'] = osp.getmtime(name) res['size'] = osp.getsize(name) except OSError: ...
Convert file data to a string for display.
def file_data_to_str(data): """ Convert file data to a string for display. This function takes the file data produced by gather_file_data(). """ if not data: return _('<i>File name not recorded</i>') res = data['name'] try: mtime_as_str = time.strftime('%Y-%m-%d %H:%M:%S', ...
Make temporary files to simulate a recovery use case.
def make_temporary_files(tempdir): """ Make temporary files to simulate a recovery use case. Create a directory under tempdir containing some original files and another directory with autosave files. Return a tuple with the name of the directory with the original files, the name of the directory wi...
Gather data about files which may be recovered.
def gather_data(self): """ Gather data about files which may be recovered. The data is stored in self.data as a list of tuples with the data pertaining to the original file and the autosave file. Each element of the tuple is a dict as returned by gather_file_data(). """ ...
Add label with explanation at top of dialog window.
def add_label(self): """Add label with explanation at top of dialog window.""" txt = _('Autosave files found. What would you like to do?\n\n' 'This dialog will be shown again on next startup if any ' 'autosave files are not restored, moved or deleted.') label = QL...
Add a label to specified cell in table.
def add_label_to_table(self, row, col, txt): """Add a label to specified cell in table.""" label = QLabel(txt) label.setMargin(5) label.setAlignment(Qt.AlignLeft | Qt.AlignVCenter) self.table.setCellWidget(row, col, label)
Add table with info about files to be recovered.
def add_table(self): """Add table with info about files to be recovered.""" table = QTableWidget(len(self.data), 3, self) self.table = table labels = [_('Original file'), _('Autosave file'), _('Actions')] table.setHorizontalHeaderLabels(labels) table.verticalHeader().hid...
Add a cancel button at the bottom of the dialog window.
def add_cancel_button(self): """Add a cancel button at the bottom of the dialog window.""" button_box = QDialogButtonBox(QDialogButtonBox.Cancel, self) button_box.rejected.connect(self.reject) self.layout.addWidget(button_box)
Register plugin in Spyder s main window
def register_plugin(self): """Register plugin in Spyder's main window""" self.redirect_stdio.connect(self.main.redirect_internalshell_stdio) self.main.console.shell.refresh.connect(self.refresh_plugin) iconsize = 24 self.toolbar.setIconSize(QSize(iconsize, iconsize)) ...
Refresh widget
def refresh_plugin(self): """Refresh widget""" curdir = getcwd_or_home() self.pathedit.add_text(curdir) self.save_wdhistory() self.set_previous_enabled.emit( self.histindex is not None and self.histindex > 0) self.set_next_enabled.emit(...
Load history from a text file in user home directory
def load_wdhistory(self, workdir=None): """Load history from a text file in user home directory""" if osp.isfile(self.LOG_PATH): wdhistory, _ = encoding.readlines(self.LOG_PATH) wdhistory = [name for name in wdhistory if os.path.isdir(name)] else: if wor...
Save history to a text file in user home directory
def save_wdhistory(self): """Save history to a text file in user home directory""" text = [ to_text_string( self.pathedit.itemText(index) ) \ for index in range(self.pathedit.count()) ] try: encoding.writelines(text, self.LOG_PATH) except EnvironmentErr...
Select directory
def select_directory(self): """Select directory""" self.redirect_stdio.emit(False) directory = getexistingdirectory(self.main, _("Select directory"), getcwd_or_home()) if directory: self.chdir(directory) self.redirect_st...
Change working directory to parent directory
def parent_directory(self): """Change working directory to parent directory""" self.chdir(os.path.join(getcwd_or_home(), os.path.pardir))
Set directory as working directory
def chdir(self, directory, browsing_history=False, refresh_explorer=True, refresh_console=True): """Set directory as working directory""" if directory: directory = osp.abspath(to_text_string(directory)) # Working directory history management if browsing_...
Add/ remove breakpoint.
def toogle_breakpoint(self, line_number=None, condition=None, edit_condition=False): """Add/remove breakpoint.""" if not self.editor.is_python_like(): return if line_number is None: block = self.editor.textCursor().block() else: ...
Get breakpoints
def get_breakpoints(self): """Get breakpoints""" breakpoints = [] block = self.editor.document().firstBlock() for line_number in range(1, self.editor.document().blockCount()+1): data = block.userData() if data and data.breakpoint: breakpoints.appen...
Clear breakpoints
def clear_breakpoints(self): """Clear breakpoints""" self.breakpoints = [] for data in self.editor.blockuserdata_list[:]: data.breakpoint = False # data.breakpoint_condition = None # not necessary, but logical if data.is_empty(): # This is not...
Set breakpoints
def set_breakpoints(self, breakpoints): """Set breakpoints""" self.clear_breakpoints() for line_number, condition in breakpoints: self.toogle_breakpoint(line_number, condition) self.breakpoints = self.get_breakpoints()
Breakpoint list has changed
def breakpoints_changed(self): """Breakpoint list has changed""" breakpoints = self.get_breakpoints() if self.breakpoints != breakpoints: self.breakpoints = breakpoints self.save_breakpoints()
Return whether a string has open quotes.
def unmatched_quotes_in_line(text): """Return whether a string has open quotes. This simply counts whether the number of quote characters of either type in the string is odd. Take from the IPython project (in IPython/core/completer.py in v0.13) Spyder team: Add some changes to deal with escaped qu...
Connect/ disconnect sig_key_pressed signal.
def on_state_changed(self, state): """Connect/disconnect sig_key_pressed signal.""" if state: self.editor.sig_key_pressed.connect(self._on_key_pressed) else: self.editor.sig_key_pressed.disconnect(self._on_key_pressed)
Control how to automatically insert quotes in various situations.
def _autoinsert_quotes(self, key): """Control how to automatically insert quotes in various situations.""" char = {Qt.Key_QuoteDbl: '"', Qt.Key_Apostrophe: '\''}[key] line_text = self.editor.get_text('sol', 'eol') line_to_cursor = self.editor.get_text('sol', 'cursor') cursor = s...
Populate the given combobox with the class or function names.
def populate(combobox, data): """ Populate the given ``combobox`` with the class or function names. Parameters ---------- combobox : :class:`qtpy.QtWidets.QComboBox` The combobox to populate data : list of :class:`FoldScopeHelper` The data to populate with. There should be one l...
Return a list of all the class/ function definition ranges.
def _get_fold_levels(editor): """ Return a list of all the class/function definition ranges. Parameters ---------- editor : :class:`spyder.plugins.editor.widgets.codeeditor.CodeEditor` Returns ------- folds : list of :class:`FoldScopeHelper` A list of all the class or function ...
Adjust the parent stack in - place as the trigger level changes.
def _adjust_parent_stack(fsh, prev, parents): """ Adjust the parent stack in-place as the trigger level changes. Parameters ---------- fsh : :class:`FoldScopeHelper` The :class:`FoldScopeHelper` object to act on. prev : :class:`FoldScopeHelper` The previous :class:`FoldScopeHelp...
Split out classes and methods into two separate lists.
def _split_classes_and_methods(folds): """ Split out classes and methods into two separate lists. Parameters ---------- folds : list of :class:`FoldScopeHelper` The result of :func:`_get_fold_levels`. Returns ------- classes, functions: list of :class:`FoldScopeHelper` ...
Get the parents at a given linenum.
def _get_parents(folds, linenum): """ Get the parents at a given linenum. If parents is empty, then the linenum belongs to the module. Parameters ---------- folds : list of :class:`FoldScopeHelper` linenum : int The line number to get parents for. Typically this would be the ...
Update the combobox with the selected item based on the parents.
def update_selected_cb(parents, combobox): """ Update the combobox with the selected item based on the parents. Parameters ---------- parents : list of :class:`FoldScopeHelper` combobox : :class:`qtpy.QtWidets.QComboBox` The combobox to populate Returns ------- None """...
Update the internal data values.
def _update_data(self): """Update the internal data values.""" _old = self.folds self.folds = _get_fold_levels(self.editor) # only update our dropdown lists if the folds have changed. if self.folds != _old: self.classes, self.funcs = _split_classes_and_methods(self.f...
Move the cursor to the selected definition.
def combobox_activated(self): """Move the cursor to the selected definition.""" sender = self.sender() data = sender.itemData(sender.currentIndex()) if isinstance(data, FoldScopeHelper): self.editor.go_to_line(data.line + 1)
Updates the dropdowns to reflect the current class and function.
def update_selected(self, linenum): """Updates the dropdowns to reflect the current class and function.""" self.parents = _get_parents(self.funcs, linenum) update_selected_cb(self.parents, self.method_cb) self.parents = _get_parents(self.classes, linenum) update_selected_cb(self...
Set text editor palette colors: background color and caret ( text cursor ) color
def set_palette(self, background, foreground): """ Set text editor palette colors: background color and caret (text cursor) color """ palette = QPalette() palette.setColor(QPalette.Base, background) palette.setColor(QPalette.Text, foreground) self....
Set extra selections for a key. Also assign draw orders to leave current_cell and current_line in the backgrund ( and avoid them to cover other decorations ) NOTE: This will remove previous decorations added to the same key. Args: key ( str ) name of the extra selections group. extra_selections ( list of sourcecode. ap...
def set_extra_selections(self, key, extra_selections): """Set extra selections for a key. Also assign draw orders to leave current_cell and current_line in the backgrund (and avoid them to cover other decorations) NOTE: This will remove previous decorations added to the same key...
Add extra selections to DecorationsManager. TODO: This method could be remove it and decorations could be added/ removed in set_extra_selections/ clear_extra_selections.
def update_extra_selections(self): """Add extra selections to DecorationsManager. TODO: This method could be remove it and decorations could be added/removed in set_extra_selections/clear_extra_selections. """ extra_selections = [] for key, extra in list(self.ex...
Remove decorations added through set_extra_selections. Args: key ( str ) name of the extra selections group.
def clear_extra_selections(self, key): """Remove decorations added through set_extra_selections. Args: key (str) name of the extra selections group. """ for decoration in self.extra_selections_dict.get(key, []): self.decorations.remove(decoration) ...
Highlight current line
def highlight_current_line(self): """Highlight current line""" selection = TextDecoration(self.textCursor()) selection.format.setProperty(QTextFormat.FullWidthSelection, to_qvariant(True)) selection.format.setBackground(self.currentline_color) ...
Highlight current cell
def highlight_current_cell(self): """Highlight current cell""" if self.cell_separators is None or \ not self.highlight_current_cell_enabled: return cursor, whole_file_selected, whole_screen_selected =\ self.select_current_cell_in_visible_portion() ...
Brace matching
def cursor_position_changed(self): """Brace matching""" if self.bracepos is not None: self.__highlight(self.bracepos, cancel=True) self.bracepos = None cursor = self.textCursor() if cursor.position() == 0: return cursor.movePosition(QTe...
Set wrap mode Valid * mode * values: None word character
def set_wrap_mode(self, mode=None): """ Set wrap mode Valid *mode* values: None, 'word', 'character' """ if mode == 'word': wrap_mode = QTextOption.WrapAtWordBoundaryOrAnywhere elif mode == 'character': wrap_mode = QTextOption.WrapAnywhere ...
Reimplement Qt method Fix PyQt4 bug on Windows and Python 3
def toPlainText(self): """ Reimplement Qt method Fix PyQt4 bug on Windows and Python 3 """ # Fix what appears to be a PyQt4 bug when getting file # contents under Windows and PY3. This bug leads to # corruptions when saving files with certain combinations ...
Return selected text as a processed text to be executable in a Python/ IPython interpreter
def get_selection_as_executable_code(self): """Return selected text as a processed text, to be executable in a Python/IPython interpreter""" ls = self.get_line_separator() _indent = lambda line: len(line)-len(line.lstrip()) line_from, line_to = self.get_selection_bounds(...
Return True if cursor ( or text block ) is on a block separator
def is_cell_separator(self, cursor=None, block=None): """Return True if cursor (or text block) is on a block separator""" assert cursor is not None or block is not None if cursor is not None: cursor0 = QTextCursor(cursor) cursor0.select(QTextCursor.BlockUnderCursor) ...
Select cell under cursor cell = group of lines separated by CELL_SEPARATORS returns the textCursor and a boolean indicating if the entire file is selected
def select_current_cell(self): """Select cell under cursor cell = group of lines separated by CELL_SEPARATORS returns the textCursor and a boolean indicating if the entire file is selected""" cursor = self.textCursor() cursor.movePosition(QTextCursor.StartOfBlock) ...
Select cell under cursor in the visible portion of the file cell = group of lines separated by CELL_SEPARATORS returns - the textCursor - a boolean indicating if the entire file is selected - a boolean indicating if the entire visible portion of the file is selected
def select_current_cell_in_visible_portion(self): """Select cell under cursor in the visible portion of the file cell = group of lines separated by CELL_SEPARATORS returns -the textCursor -a boolean indicating if the entire file is selected -a boolean indicating ...
Go to the next cell of lines
def go_to_next_cell(self): """Go to the next cell of lines""" cursor = self.textCursor() cursor.movePosition(QTextCursor.NextBlock) cur_pos = prev_pos = cursor.position() while not self.is_cell_separator(cursor): # Moving to the next code cell curso...
Go to the previous cell of lines
def go_to_previous_cell(self): """Go to the previous cell of lines""" cursor = self.textCursor() cur_pos = prev_pos = cursor.position() if self.is_cell_separator(cursor): # Move to the previous cell cursor.movePosition(QTextCursor.PreviousBlock) ...
Restore cursor selection from position bounds
def __restore_selection(self, start_pos, end_pos): """Restore cursor selection from position bounds""" cursor = self.textCursor() cursor.setPosition(start_pos) cursor.setPosition(end_pos, QTextCursor.KeepAnchor) self.setTextCursor(cursor)
Duplicate current line or selected text
def __duplicate_line_or_selection(self, after_current_line=True): """Duplicate current line or selected text""" cursor = self.textCursor() cursor.beginEditBlock() start_pos, end_pos = self.__save_selection() if to_text_string(cursor.selectedText()): cursor.setPo...
Move current line or selected text
def __move_line_or_selection(self, after_current_line=True): """Move current line or selected text""" cursor = self.textCursor() cursor.beginEditBlock() start_pos, end_pos = self.__save_selection() last_line = False # ------ Select text # Get selection ...
Go to the end of the current line and create a new line
def go_to_new_line(self): """Go to the end of the current line and create a new line""" self.stdkey_end(False, False) self.insert_text(self.get_line_separator())
Extend current selection to complete lines
def extend_selection_to_complete_lines(self): """Extend current selection to complete lines""" cursor = self.textCursor() start_pos, end_pos = cursor.selectionStart(), cursor.selectionEnd() cursor.setPosition(start_pos) cursor.setPosition(end_pos, QTextCursor.KeepAnchor) ...
Delete current line
def delete_line(self): """Delete current line""" cursor = self.textCursor() if self.has_selected_text(): self.extend_selection_to_complete_lines() start_pos, end_pos = cursor.selectionStart(), cursor.selectionEnd() cursor.setPosition(start_pos) ...
Unselect read - only parts in shell like prompt
def truncate_selection(self, position_from): """Unselect read-only parts in shell, like prompt""" position_from = self.get_position(position_from) cursor = self.textCursor() start, end = cursor.selectionStart(), cursor.selectionEnd() if start < end: start = max(...
In shell avoid editing text except between prompt and EOF
def restrict_cursor_position(self, position_from, position_to): """In shell, avoid editing text except between prompt and EOF""" position_from = self.get_position(position_from) position_to = self.get_position(position_to) cursor = self.textCursor() cursor_position = cursor....
Hide calltip when necessary
def hide_tooltip_if_necessary(self, key): """Hide calltip when necessary""" try: calltip_char = self.get_character(self.calltip_position) before = self.is_cursor_before(self.calltip_position, char_offset=1) other = key ...
Smart HOME feature: cursor is first moved at indentation position then at the start of the line
def stdkey_home(self, shift, ctrl, prompt_pos=None): """Smart HOME feature: cursor is first moved at indentation position, then at the start of the line""" move_mode = self.__get_move_mode(shift) if ctrl: self.moveCursor(QTextCursor.Start, move_mode) else: ...
Reimplement Qt method
def mousePressEvent(self, event): """Reimplement Qt method""" if sys.platform.startswith('linux') and event.button() == Qt.MidButton: self.calltip_widget.hide() self.setFocus() event = QMouseEvent(QEvent.MouseButtonPress, event.pos(), ...
Reimplemented to handle focus
def focusInEvent(self, event): """Reimplemented to handle focus""" self.focus_changed.emit() self.focus_in.emit() self.highlight_current_cell() QPlainTextEdit.focusInEvent(self, event)
Reimplemented to handle focus
def focusOutEvent(self, event): """Reimplemented to handle focus""" self.focus_changed.emit() QPlainTextEdit.focusOutEvent(self, event)
Reimplemented to emit zoom in/ out signals when Ctrl is pressed
def wheelEvent(self, event): """Reimplemented to emit zoom in/out signals when Ctrl is pressed""" # This feature is disabled on MacOS, see Issue 1510 if sys.platform != 'darwin': if event.modifiers() & Qt.ControlModifier: if hasattr(event, 'angleDelta'): ...
Convert options into commands return commands message
def get_options(argv=None): """ Convert options into commands return commands, message """ parser = argparse.ArgumentParser(usage="spyder [options] files") parser.add_argument('--new-instance', action='store_true', default=False, help="Run a new instance of Spyder, even if ...
Set a list of files opened by the project.
def set_recent_files(self, recent_files): """Set a list of files opened by the project.""" for recent_file in recent_files[:]: if not os.path.isfile(recent_file): recent_files.remove(recent_file) try: self.CONF[WORKSPACE].set('main', 'recent_files', ...
Return a list of files opened by the project.
def get_recent_files(self): """Return a list of files opened by the project.""" try: recent_files = self.CONF[WORKSPACE].get('main', 'recent_files', default=[]) except EnvironmentError: return [] for rec...
Set project root path.
def set_root_path(self, root_path): """Set project root path.""" if self.name is None: self.name = osp.basename(root_path) self.root_path = to_text_string(root_path) config_path = self.__get_project_config_path() if osp.exists(config_path): self.loa...
Rename project and rename its root path accordingly.
def rename(self, new_name): """Rename project and rename its root path accordingly.""" old_name = self.name self.name = new_name pypath = self.relative_pythonpath # ?? self.root_path = self.root_path[:-len(old_name)]+new_name self.relative_pythonpath = pypath # ??...
Start pydoc server
def initialize(self): """Start pydoc server""" QApplication.setOverrideCursor(QCursor(Qt.WaitCursor)) QApplication.processEvents() self.start_server()
Start pydoc server
def start_server(self): """Start pydoc server""" if self.server is None: self.port = select_port(default_port=self.DEFAULT_PORT) self.set_home_url('http://localhost:%d/' % self.port) elif self.server.isRunning(): self.server.server_started.disconnect(sel...
Convert text address into QUrl object
def text_to_url(self, text): """Convert text address into QUrl object""" if text.startswith('/'): text = text[1:] return QUrl(self.home_url.toString()+text+'.html')
Instruct current editorstack to autosave files where necessary.
def do_autosave(self): """Instruct current editorstack to autosave files where necessary.""" logger.debug('Autosave triggered') stack = self.editor.get_current_editorstack() stack.autosave.autosave_all() self.start_autosave_timer()
Offer to recover files from autosave.
def try_recover_from_autosave(self): """Offer to recover files from autosave.""" autosave_dir = get_conf_path('autosave') autosave_mapping = CONF.get('editor', 'autosave_mapping', {}) dialog = RecoveryDialog(autosave_dir, autosave_mapping, parent=self.edit...
Create unique autosave file name for specified file name.
def create_unique_autosave_filename(self, filename, autosave_dir): """ Create unique autosave file name for specified file name. Args: filename (str): original file name autosave_dir (str): directory in which autosave files are stored """ basename = osp.b...
Remove autosave file for specified file.
def remove_autosave_file(self, fileinfo): """ Remove autosave file for specified file. This function also updates `self.autosave_mapping` and clears the `changed_since_autosave` flag. """ filename = fileinfo.filename if filename not in self.name_mapping: ...
Get name of autosave file for specified file name.
def get_autosave_filename(self, filename): """ Get name of autosave file for specified file name. This function uses the dict in `self.name_mapping`. If `filename` is in the mapping, then return the corresponding autosave file name. Otherwise, construct a unique file name and up...
Autosave a file.
def autosave(self, index): """ Autosave a file. Do nothing if the `changed_since_autosave` flag is not set or the file is newly created (and thus not named by the user). Otherwise, save a copy of the file with the name given by `self.get_autosave_filename()` and clear th...
Autosave all opened files.
def autosave_all(self): """Autosave all opened files.""" for index in range(self.stack.get_stack_count()): self.autosave(index)
Fixtures that returns a temporary CONF element.
def tmpconfig(request): """ Fixtures that returns a temporary CONF element. """ SUBFOLDER = tempfile.mkdtemp() CONF = UserConfig('spyder-test', defaults=DEFAULTS, version=CONF_VERSION, subfolder=SUBFOLDER, raw_mo...
Log last error in filename * fname * -- * context *: string ( optional )
def log_last_error(fname, context=None): """Log last error in filename *fname* -- *context*: string (optional)""" fd = open(fname, 'a') log_time(fd) if context: print("Context", file=fd) print("-------", file=fd) print("", file=fd) if PY2: print(u' '....
Hack some_class to log all method calls into fname file. If prefix format is not set each log entry is prefixed with: -- [ asked/ called/ defined ] -- asked - name of some_class called - name of class for which a method is called defined - name of class where method is defined Must be used carefully because it monkeypa...
def log_methods_calls(fname, some_class, prefix=None): """ Hack `some_class` to log all method calls into `fname` file. If `prefix` format is not set, each log entry is prefixed with: --[ asked / called / defined ] -- asked - name of `some_class` called - name of class for whi...
This property holds the vertical offset of the scroll flag area relative to the top of the text editor.
def offset(self): """This property holds the vertical offset of the scroll flag area relative to the top of the text editor.""" vsb = self.editor.verticalScrollBar() style = vsb.style() opt = QStyleOptionSlider() vsb.initStyleOption(opt) # Get the area in which t...
Override Qt method. Painting the scroll flag area
def paintEvent(self, event): """ Override Qt method. Painting the scroll flag area """ make_flag = self.make_flag_qrect # Fill the whole painting area painter = QPainter(self) painter.fillRect(event.rect(), self.editor.sideareas_color) # Paint wa...
Override Qt method
def mousePressEvent(self, event): """Override Qt method""" if self.slider and event.button() == Qt.LeftButton: vsb = self.editor.verticalScrollBar() value = self.position_to_value(event.pos().y()) vsb.setValue(value-vsb.pageStep()/2)
Override Qt method.
def keyReleaseEvent(self, event): """Override Qt method.""" if event.key() == Qt.Key_Alt: self._alt_key_is_down = False self.update()
Override Qt method
def keyPressEvent(self, event): """Override Qt method""" if event.key() == Qt.Key_Alt: self._alt_key_is_down = True self.update()
Return the pixel span height of the scrollbar area in which the slider handle may move
def get_scrollbar_position_height(self): """Return the pixel span height of the scrollbar area in which the slider handle may move""" vsb = self.editor.verticalScrollBar() style = vsb.style() opt = QStyleOptionSlider() vsb.initStyleOption(opt) # Get the area in w...
Return the value span height of the scrollbar
def get_scrollbar_value_height(self): """Return the value span height of the scrollbar""" vsb = self.editor.verticalScrollBar() return vsb.maximum()-vsb.minimum()+vsb.pageStep()
Convert value to position in pixels
def value_to_position(self, y): """Convert value to position in pixels""" vsb = self.editor.verticalScrollBar() return (y-vsb.minimum())*self.get_scale_factor()+self.offset
Convert position in pixels to value
def position_to_value(self, y): """Convert position in pixels to value""" vsb = self.editor.verticalScrollBar() return vsb.minimum()+max([0, (y-self.offset)/self.get_scale_factor()])
Make flag QRect
def make_flag_qrect(self, value): """Make flag QRect""" if self.slider: position = self.value_to_position(value+0.5) # The 0.5 offset is used to align the flags with the center of # their corresponding text edit block before scaling. return QRect(self.FLA...
Make slider range QRect
def make_slider_range(self, cursor_pos): """Make slider range QRect""" # The slider range indicator position follows the mouse vertical # position while its height corresponds to the part of the file that # is currently visible on screen. vsb = self.editor.verticalScrollBar() ...
Set scroll flag area painter pen and brush colors
def set_painter(self, painter, light_color): """Set scroll flag area painter pen and brush colors""" painter.setPen(QColor(light_color).darker(120)) painter.setBrush(QBrush(QColor(light_color)))
Action to be performed on first plugin registration
def on_first_registration(self): """Action to be performed on first plugin registration""" self.main.tabify_plugins(self.main.help, self) self.dockwidget.hide()
Register plugin in Spyder s main window
def register_plugin(self): """Register plugin in Spyder's main window""" self.profiler.datatree.sig_edit_goto.connect(self.main.editor.load) self.profiler.redirect_stdio.connect( self.main.redirect_internalshell_stdio) self.main.add_dockwidget(self) profiler_act = cr...
Run profiler
def run_profiler(self): """Run profiler""" if self.main.editor.save(): self.switch_to_plugin() self.analyze(self.main.editor.get_current_filename())
Reimplement analyze method
def analyze(self, filename): """Reimplement analyze method""" if self.dockwidget and not self.ismaximized: self.dockwidget.setVisible(True) self.dockwidget.setFocus() self.dockwidget.raise_() pythonpath = self.main.get_spyder_pythonpath() runconf = get...
Return physical memory usage ( float ) Works on Windows platforms only
def windows_memory_usage(): """Return physical memory usage (float) Works on Windows platforms only""" from ctypes import windll, Structure, c_uint64, sizeof, byref from ctypes.wintypes import DWORD class MemoryStatus(Structure): _fields_ = [('dwLength', DWORD), ('...