text_prompt
stringlengths
157
13.1k
code_prompt
stringlengths
7
19.8k
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def path_manager_callback(self): """Spyder path manager"""
from spyder.widgets.pathmanager import PathManager self.remove_path_from_sys_path() project_path = self.projects.get_pythonpath() dialog = PathManager(self, self.path, project_path, self.not_active_path, sync=True) dialog.redirect_stdio.connect...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def pythonpath_changed(self): """Projects PYTHONPATH contribution has changed"""
self.remove_path_from_sys_path() self.project_path = self.projects.get_pythonpath() self.add_path_to_sys_path() self.sig_pythonpath_changed.emit()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def apply_settings(self): """Apply settings changed in 'Preferences' dialog box"""
qapp = QApplication.instance() # Set 'gtk+' as the default theme in Gtk-based desktops # Fixes Issue 2036 if is_gtk_desktop() and ('GTK+' in QStyleFactory.keys()): try: qapp.setStyle('gtk+') except: pass else: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def apply_panes_settings(self): """Update dockwidgets features settings"""
for plugin in (self.widgetlist + self.thirdparty_plugins): features = plugin.FEATURES if CONF.get('main', 'vertical_dockwidget_titlebars'): features = features | QDockWidget.DockWidgetVerticalTitleBar plugin.dockwidget.setFeatures(features) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def apply_statusbar_settings(self): """Update status bar widgets settings"""
show_status_bar = CONF.get('main', 'show_status_bar') self.statusBar().setVisible(show_status_bar) if show_status_bar: for widget, name in ((self.mem_status, 'memory_usage'), (self.cpu_status, 'cpu_usage')): if widget is not N...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def edit_preferences(self): """Edit Spyder preferences"""
from spyder.preferences.configdialog import ConfigDialog dlg = ConfigDialog(self) dlg.size_change.connect(self.set_prefs_size) if self.prefs_dialog_size is not None: dlg.resize(self.prefs_dialog_size) for PrefPageClass in self.general_prefs: widget...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def reset_spyder(self): """ Quit and reset Spyder and then Restart application. """
answer = QMessageBox.warning(self, _("Warning"), _("Spyder will restart and reset to default settings: <br><br>" "Do you want to continue?"), QMessageBox.Yes | QMessageBox.No) if answer == QMessageBox.Yes: self.restart(reset=True)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def restart(self, reset=False): """ Quit and Restart Spyder application. If reset True it allows to reset spyder on restart. """
# Get start path to use in restart script spyder_start_directory = get_module_path('spyder') restart_script = osp.join(spyder_start_directory, 'app', 'restart.py') # Get any initial argument passed when spyder was started # Note: Variables defined in bootstrap.py and spyd...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def show_tour(self, index): """Show interactive tour."""
self.maximize_dockwidget(restore=True) frames = self.tours_available[index] self.tour.set_tour(index, frames, self) self.tour.start_tour()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def open_fileswitcher(self, symbol=False): """Open file list management dialog box."""
if self.fileswitcher is not None and \ self.fileswitcher.is_visible: self.fileswitcher.hide() self.fileswitcher.is_visible = False return if symbol: self.fileswitcher.plugin = self.editor self.fileswitcher.set_search_text('@'...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def add_to_fileswitcher(self, plugin, tabs, data, icon): """Add a plugin to the File Switcher."""
if self.fileswitcher is None: from spyder.widgets.fileswitcher import FileSwitcher self.fileswitcher = FileSwitcher(self, plugin, tabs, data, icon) else: self.fileswitcher.add_plugin(plugin, tabs, data, icon) self.fileswitcher.sig_goto_file.connect( ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _check_updates_ready(self): """Called by WorkerUpdates when ready"""
from spyder.widgets.helperwidgets import MessageCheckBox # feedback` = False is used on startup, so only positive feedback is # given. `feedback` = True is used when after startup (when using the # menu action, and gives feeback if updates are, or are not found. feedback ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def check_updates(self, startup=False): """ Check for spyder updates on github releases using a QThread. """
from spyder.workers.updates import WorkerUpdates # Disable check_updates_action while the thread is working self.check_updates_action.setDisabled(True) if self.thread_updates is not None: self.thread_updates.terminate() self.thread_updates = QThread(self)...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _set(self, section, option, value, verbose): """ Private set method """
if not self.has_section(section): self.add_section( section ) if not is_text_string(value): value = repr( value ) if verbose: print('%s[ %s ] = %s' % (section, option, value)) # spyder: test-skip cp.ConfigParser.set(self, section, option, valu...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _save(self): """ Save config into the associated .ini file """
# See Issue 1086 and 1242 for background on why this # method contains all the exception handling. fname = self.filename() def _write_file(fname): if PY2: # Python 2 with codecs.open(fname, 'w', encoding='utf-8') as configfile: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def filename(self): """Defines the name of the configuration file to use."""
# Needs to be done this way to be used by the project config. # To fix on a later PR self._filename = getattr(self, '_filename', None) self._root_path = getattr(self, '_root_path', None) if self._filename is None and self._root_path is None: return self._file...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _filename_global(self): """Create a .ini filename located in user home directory. This .ini files stores the global spyder preferences. """
if self.subfolder is None: config_file = osp.join(get_home_dir(), '.%s.ini' % self.name) return config_file else: folder = get_conf_path() # Save defaults in a "defaults" dir of .spyder2 to not pollute it if 'defaults' in self.name: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def load_from_ini(self): """ Load config from the associated .ini file """
try: if PY2: # Python 2 fname = self.filename() if osp.isfile(fname): try: with codecs.open(fname, encoding='utf-8') as configfile: self.readfp(configfile) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _load_old_defaults(self, old_version): """Read old defaults"""
old_defaults = cp.ConfigParser() if check_version(old_version, '3.0.0', '<='): path = get_module_source_path('spyder') else: path = osp.dirname(self.filename()) path = osp.join(path, 'defaults') old_defaults.read(osp.join(path, 'defaults-'+old_ver...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _save_new_defaults(self, defaults, new_version, subfolder): """Save new defaults"""
new_defaults = DefaultsConfig(name='defaults-'+new_version, subfolder=subfolder) if not osp.isfile(new_defaults.filename()): new_defaults.set_defaults(defaults) new_defaults._save()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _update_defaults(self, defaults, old_version, verbose=False): """Update defaults after a change in version"""
old_defaults = self._load_old_defaults(old_version) for section, options in defaults: for option in options: new_value = options[ option ] try: old_value = old_defaults.get(section, option) except (cp.NoSectionError,...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _remove_deprecated_options(self, old_version): """ Remove options which are present in the .ini file but not in defaults """
old_defaults = self._load_old_defaults(old_version) for section in old_defaults.sections(): for option, _ in old_defaults.items(section, raw=self.raw): if self.get_default(section, option) is NoDefault: try: self.remove_optio...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def set_as_defaults(self): """ Set defaults from the current config """
self.defaults = [] for section in self.sections(): secdict = {} for option, value in self.items(section, raw=self.raw): secdict[option] = value self.defaults.append( (section, secdict) )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def reset_to_defaults(self, save=True, verbose=False, section=None): """ Reset config to Default values """
for sec, options in self.defaults: if section == None or section == sec: for option in options: value = options[ option ] self._set(sec, option, value, verbose) if save: self._save()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _check_section_option(self, section, option): """ Private method to check section and option types """
if section is None: section = self.DEFAULT_SECTION_NAME elif not is_text_string(section): raise RuntimeError("Argument 'section' must be a string") if not is_text_string(option): raise RuntimeError("Argument 'option' must be a string") return s...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_temp_dir(suffix=None): """ Return temporary Spyder directory, checking previously that it exists. """
to_join = [tempfile.gettempdir()] if os.name == 'nt': to_join.append('spyder') else: username = encoding.to_unicode_from_fs(getuser()) to_join.append('spyder-' + username) if suffix is not None: to_join.append(suffix) tempdir = osp.join(*to_join) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def is_program_installed(basename): """ Return program absolute path if installed in PATH. Otherwise, return None """
for path in os.environ["PATH"].split(os.pathsep): abspath = osp.join(path, basename) if osp.isfile(abspath): return abspath
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def alter_subprocess_kwargs_by_platform(**kwargs): """ Given a dict, populate kwargs to create a generally useful default setup for running subprocess process...
kwargs.setdefault('close_fds', os.name == 'posix') if os.name == 'nt': CONSOLE_CREATION_FLAGS = 0 # Default value # See: https://msdn.microsoft.com/en-us/library/windows/desktop/ms684863%28v=vs.85%29.aspx CREATE_NO_WINDOW = 0x08000000 # We "or" them together CONS...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def start_file(filename): """ Generalized os.startfile for all platforms supported by Qt This function is simply wrapping QDesktopServices.openUrl Return...
from qtpy.QtCore import QUrl from qtpy.QtGui import QDesktopServices # We need to use setUrl instead of setPath because this is the only # cross-platform way to open external files. setPath fails completely on # Mac and doesn't open non-ascii files on Linux. # Fixes Issue 740 url =...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_python_args(fname, python_args, interact, debug, end_args): """Construct Python interpreter arguments"""
p_args = [] if python_args is not None: p_args += python_args.split() if interact: p_args.append('-i') if debug: p_args.extend(['-m', 'pdb']) if fname is not None: if os.name == 'nt' and debug: # When calling pdb on Windows, one has to replace b...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def is_python_interpreter_valid_name(filename): """Check that the python interpreter file has a valid name."""
pattern = r'.*python(\d\.?\d*)?(w)?(.exe)?$' if re.match(pattern, filename, flags=re.I) is None: return False else: return True
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def is_python_interpreter(filename): """Evaluate wether a file is a python interpreter or not."""
real_filename = os.path.realpath(filename) # To follow symlink if existent if (not osp.isfile(real_filename) or not is_python_interpreter_valid_name(filename)): return False elif is_pythonw(filename): if os.name == 'nt': # pythonw is a binary on Windows ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def is_pythonw(filename): """Check that the python interpreter has 'pythonw'."""
pattern = r'.*python(\d\.?\d*)?w(.exe)?$' if re.match(pattern, filename, flags=re.I) is None: return False else: return True
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def check_python_help(filename): """Check that the python interpreter can execute help."""
try: proc = run_program(filename, ["-h"]) output = to_text_string(proc.communicate()[0]) valid = ("Options and arguments (and corresponding environment " "variables)") if 'usage:' in output and valid in output: return True else: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _draw_breakpoint_icon(self, top, painter, icon_name): """Draw the given breakpoint pixmap. Args: top (int): top of the line to draw the breakpoint icon. pai...
rect = QRect(0, top, self.sizeHint().width(), self.sizeHint().height()) try: icon = self.icons[icon_name] except KeyError as e: debug_print("Breakpoint icon doen't exist, {}".format(e)) else: icon.paint(painter, rect)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def sleeping_func(arg, secs=10, result_queue=None): """This methods illustrates how the workers can be used."""
import time time.sleep(secs) if result_queue is not None: result_queue.put(arg) else: return arg
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _start(self): """Start process worker for given method args and kwargs."""
error = None output = None try: output = self.func(*self.args, **self.kwargs) except Exception as err: error = err if not self._is_finished: self.sig_finished.emit(self, output, error) self._is_finished = True
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _set_environment(self, environ): """Set the environment on the QProcess."""
if environ: q_environ = self._process.processEnvironment() for k, v in environ.items(): q_environ.insert(k, v) self._process.setProcessEnvironment(q_environ)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _communicate(self): """Callback for communicate."""
if (not self._communicate_first and self._process.state() == QProcess.NotRunning): self.communicate() elif self._fired: self._timer.stop()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def terminate(self): """Terminate running processes."""
if self._process.state() == QProcess.Running: try: self._process.terminate() except Exception: pass self._fired = True
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _clean_workers(self): """Delete periodically workers in workers bag."""
while self._bag_collector: self._bag_collector.popleft() self._timer_worker_delete.stop()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _start(self, worker=None): """Start threads and check for inactive workers."""
if worker: self._queue_workers.append(worker) if self._queue_workers and self._running_threads < self._max_threads: #print('Queue: {0} Running: {1} Workers: {2} ' # 'Threads: {3}'.format(len(self._queue_workers), # s...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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: # pass self._queue_workers = deque()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _create_worker(self, worker): """Common worker setup."""
worker.sig_started.connect(self._start) self._workers.append(worker)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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: pass return res
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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', time.localtime(data['mtime'])) res += '<br><i>{}</i>: {}'.format(_('Last modified'), mtime_as_str) res += '<b...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def make_temporary_files(tempdir): """ Make temporary files to simulate a recovery use case. Create a directory under tempdir containing some original files and ...
orig_dir = osp.join(tempdir, 'orig') os.mkdir(orig_dir) autosave_dir = osp.join(tempdir, 'autosave') os.mkdir(autosave_dir) autosave_mapping = {} # ham.py: Both original and autosave files exist, mentioned in mapping orig_file = osp.join(orig_dir, 'ham.py') with open(orig_file, 'w') as...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 or...
self.data = [] try: FileNotFoundError except NameError: # Python 2 FileNotFoundError = OSError # In Python 3, easier to use os.scandir() try: for name in os.listdir(self.autosave_dir): full_name = osp.join(self.autosave_dir, n...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 = QLabel(txt, self) label.setWordWrap(True) self.layout.addWidget(label)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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().hide() table.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff) tabl...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def parent_directory(self): """Change working directory to parent directory"""
self.chdir(os.path.join(getcwd_or_home(), os.path.pardir))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def breakpoints_changed(self): """Breakpoint list has changed"""
breakpoints = self.get_breakpoints() if self.breakpoints != breakpoints: self.breakpoints = breakpoints self.save_breakpoints()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 s...
# We check " first, then ', so complex cases with nested quotes will # get the " to take precedence. text = text.replace("\\'", "") text = text.replace('\\"', '') if text.count('"') % 2: return '"' elif text.count("'") % 2: return "'" else: return ''
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 = self.editor.textCursor() last_three = self.editor.get_text('sol', 'cursor')[-3:] last_two = self.ed...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def populate(combobox, data): """ Populate the given ``combobox`` with the class or function names. Parameters combobox : :class:`qtpy.QtWidets.QComboBox` The co...
combobox.clear() combobox.addItem("<None>", 0) # First create a list of fully-qualified names. cb_data = [] for item in data: fqn = item.name for parent in reversed(item.parents): fqn = parent.name + "." + fqn cb_data.append((fqn, item)) for fqn, item in s...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _adjust_parent_stack(fsh, prev, parents): """ Adjust the parent stack in-place as the trigger level changes. Parameters fsh : :class:`FoldScopeHelper` The :c...
if prev is None: return if fsh.fold_scope.trigger_level < prev.fold_scope.trigger_level: diff = prev.fold_scope.trigger_level - fsh.fold_scope.trigger_level del parents[-diff:] elif fsh.fold_scope.trigger_level > prev.fold_scope.trigger_level: parents.append(prev) elif ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _split_classes_and_methods(folds): """ Split out classes and methods into two separate lists. Parameters folds : list of :class:`FoldScopeHelper` The result ...
classes = [] functions = [] for fold in folds: if fold.def_type == OED.FUNCTION_TOKEN: functions.append(fold) elif fold.def_type == OED.CLASS_TOKEN: classes.append(fold) return classes, functions
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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...
# Note: this might be able to be sped up by finding some kind of # abort-early condition. parents = [] for fold in folds: start, end = fold.range if linenum >= start and linenum <= end: parents.append(fold) else: continue return parents
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def update_selected_cb(parents, combobox): """ Update the combobox with the selected item based on the parents. Parameters parents : list of :class:`FoldScopeHel...
if parents is not None and len(parents) == 0: combobox.setCurrentIndex(0) else: item = parents[-1] for i in range(combobox.count()): if combobox.itemData(i) == item: combobox.setCurrentIndex(i) break
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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.folds) self.populate_dropdowns()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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.parents, self.class_cb)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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() selection = TextDecoration(cursor) selection.format.setProper...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def select_current_cell(self): """Select cell under cursor cell = group of lines separated by CELL_SEPARATORS returns the textCursor and a boolean indicating ...
cursor = self.textCursor() cursor.movePosition(QTextCursor.StartOfBlock) cur_pos = prev_pos = cursor.position() # Moving to the next line that is not a separator, if we are # exactly at one of them while self.is_cell_separator(cursor): cursor.movePos...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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_SEPARA...
cursor = self.textCursor() cursor.movePosition(QTextCursor.StartOfBlock) cur_pos = prev_pos = cursor.position() beg_pos = self.cursorForPosition(QPoint(0, 0)).position() bottom_right = QPoint(self.viewport().width() - 1, self.viewport().heig...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 cursor.movePosition(QTextCursor.NextBlock) prev_pos = cur_pos ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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) cur_pos = prev_pos = cursor.position() while not self.is_cell_se...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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.setPosition(end_pos) # Check if end_pos is at the start of a block: if so, starting # changes from ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 start location cursor.setPosition(start_pos) cursor.movePosition(QTextCursor.StartOfBlock) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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())
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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) if cursor.atBlockStart(): cursor.movePosition(QTextCursor.PreviousBlock, ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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) else: start_pos = end_pos = cursor.position(...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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([position_from, start]) else: end = max([position_from, end]) self.set_sele...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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.position() if cursor_position < position_from or cursor_position > position_to: self.set_cursor_position(position_t...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 in (Qt.Key_ParenRight, Qt.Key_Period, Qt.Key_Tab) if calltip_char not i...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 the single " "instance mode has been turned on (default)") parser.add_argum...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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', list(OrderedDict.fromkeys(recent_files))) except Env...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 recent_file in recent_files[:]: if not os.path.isfile(recent_file): ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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.load() else: if not osp.isdir(self.root_path): ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 # ?? self.save()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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')
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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.editor) dialog.exec_if_nonempty() self.recover_files_to_open = dialog.files_...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create_unique_autosave_filename(self, filename, autosave_dir): """ Create unique autosave file name for specified file name. Args: filename (str): original ...
basename = osp.basename(filename) autosave_filename = osp.join(autosave_dir, basename) if autosave_filename in self.name_mapping.values(): counter = 0 root, ext = osp.splitext(basename) while autosave_filename in self.name_mapping.values(): co...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def remove_autosave_file(self, fileinfo): """ Remove autosave file for specified file. This function also updates `self.autosave_mapping` and clears the `changed...
filename = fileinfo.filename if filename not in self.name_mapping: return autosave_filename = self.name_mapping[filename] try: os.remove(autosave_filename) except EnvironmentError as error: action = (_('Error while removing autosave file {}') ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 `filenam...
try: autosave_filename = self.name_mapping[filename] except KeyError: autosave_dir = get_conf_path('autosave') if not osp.isdir(autosave_dir): try: os.mkdir(autosave_dir) except EnvironmentError as error: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 th...
finfo = self.stack.data[index] document = finfo.editor.document() if not document.changed_since_autosave or finfo.newly_created: return autosave_filename = self.get_autosave_filename(finfo.filename) logger.debug('Autosaving %s to %s', finfo.filename, autosave_filenam...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def autosave_all(self): """Autosave all opened files."""
for index in range(self.stack.get_stack_count()): self.autosave(index)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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_mode=True, ) def fin(): """ Fixture finalizer to d...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 the slider handle may move. groove_rect = style.subControlRect( QStyle.CC_ScrollBar, opt, QStyle.SC_ScrollBarGroove, sel...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 warnings and todos block = self.editor.document().firstBlock() for line_number in range(self.editor.docu...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 which the slider handle may move. groove_rect = style.subControlRect( QStyle.CC_ScrollBar, opt, QStyle.SC_ScrollBarGroove, sel...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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()])