text_prompt
stringlengths 100
17.7k
⌀ | code_prompt
stringlengths 7
9.86k
⌀ |
---|---|
<SYSTEM_TASK:>
Restart kernel of current client.
<END_TASK>
<USER_TASK:>
Description:
def restart_kernel(self):
"""Restart kernel of current client."""
|
client = self.get_current_client()
if client is not None:
self.switch_to_plugin()
client.restart_kernel()
|
<SYSTEM_TASK:>
Update actions following the execution state of the kernel.
<END_TASK>
<USER_TASK:>
Description:
def update_execution_state_kernel(self):
"""Update actions following the execution state of the kernel."""
|
client = self.get_current_client()
if client is not None:
executing = client.stop_button.isEnabled()
self.interrupt_action.setEnabled(executing)
|
<SYSTEM_TASK:>
Connect an external kernel to the Variable Explorer and Help, if
<END_TASK>
<USER_TASK:>
Description:
def connect_external_kernel(self, shellwidget):
"""
Connect an external kernel to the Variable Explorer and Help, if
it is a Spyder kernel.
"""
|
sw = shellwidget
kc = shellwidget.kernel_client
if self.main.help is not None:
self.main.help.set_shell(sw)
if self.main.variableexplorer is not None:
self.main.variableexplorer.add_shellwidget(sw)
sw.set_namespace_view_settings()
sw.refresh_namespacebrowser()
kc.stopped_channels.connect(lambda :
self.main.variableexplorer.remove_shellwidget(id(sw)))
|
<SYSTEM_TASK:>
Generate a file name without ambiguation.
<END_TASK>
<USER_TASK:>
Description:
def disambiguate_fname(self, fname):
"""Generate a file name without ambiguation."""
|
files_path_list = [filename for filename in self.filenames
if filename]
return sourcecode.disambiguate_fname(files_path_list, fname)
|
<SYSTEM_TASK:>
Rename tabs after a change in name.
<END_TASK>
<USER_TASK:>
Description:
def rename_tabs_after_change(self, given_name):
"""Rename tabs after a change in name."""
|
client = self.get_current_client()
# Prevent renames that want to assign the same name of
# a previous tab
repeated = False
for cl in self.get_clients():
if id(client) != id(cl) and given_name == cl.given_name:
repeated = True
break
# Rename current client tab to add str_id
if client.allow_rename and not u'/' in given_name and not repeated:
self.rename_client_tab(client, given_name)
else:
self.rename_client_tab(client, None)
# Rename related clients
if client.allow_rename and not u'/' in given_name and not repeated:
for cl in self.get_related_clients(client):
self.rename_client_tab(cl, given_name)
|
<SYSTEM_TASK:>
Trigger the tab name editor.
<END_TASK>
<USER_TASK:>
Description:
def tab_name_editor(self):
"""Trigger the tab name editor."""
|
index = self.tabwidget.currentIndex()
self.tabwidget.tabBar().tab_name_editor.edit_tab(index)
|
<SYSTEM_TASK:>
Remove stderr files left by previous Spyder instances.
<END_TASK>
<USER_TASK:>
Description:
def _remove_old_stderr_files(self):
"""
Remove stderr files left by previous Spyder instances.
This is only required on Windows because we can't
clean up stderr files while Spyder is running on it.
"""
|
if os.name == 'nt':
tmpdir = get_temp_dir()
for fname in os.listdir(tmpdir):
if osp.splitext(fname)[1] == '.stderr':
try:
os.remove(osp.join(tmpdir, fname))
except Exception:
pass
|
<SYSTEM_TASK:>
Rotate the kill ring, then yank back the new top.
<END_TASK>
<USER_TASK:>
Description:
def rotate(self):
""" Rotate the kill ring, then yank back the new top.
Returns
-------
A text string or None.
"""
|
self._index -= 1
if self._index >= 0:
return self._ring[self._index]
return None
|
<SYSTEM_TASK:>
Kills the text selected by the give cursor.
<END_TASK>
<USER_TASK:>
Description:
def kill_cursor(self, cursor):
""" Kills the text selected by the give cursor.
"""
|
text = cursor.selectedText()
if text:
cursor.removeSelectedText()
self.kill(text)
|
<SYSTEM_TASK:>
Yank back the most recently killed text.
<END_TASK>
<USER_TASK:>
Description:
def yank(self):
""" Yank back the most recently killed text.
"""
|
text = self._ring.yank()
if text:
self._skip_cursor = True
cursor = self._text_edit.textCursor()
cursor.insertText(text)
self._prev_yank = text
|
<SYSTEM_TASK:>
Normalize path fixing case, making absolute and removing symlinks
<END_TASK>
<USER_TASK:>
Description:
def fixpath(path):
"""Normalize path fixing case, making absolute and removing symlinks"""
|
norm = osp.normcase if os.name == 'nt' else osp.normpath
return norm(osp.abspath(osp.realpath(path)))
|
<SYSTEM_TASK:>
List files and directories
<END_TASK>
<USER_TASK:>
Description:
def listdir(path, include=r'.', exclude=r'\.pyc$|^\.', show_all=False,
folders_only=False):
"""List files and directories"""
|
namelist = []
dirlist = [to_text_string(osp.pardir)]
for item in os.listdir(to_text_string(path)):
if re.search(exclude, item) and not show_all:
continue
if osp.isdir(osp.join(path, item)):
dirlist.append(item)
elif folders_only:
continue
elif re.search(include, item) or show_all:
namelist.append(item)
return sorted(dirlist, key=str_lower) + \
sorted(namelist, key=str_lower)
|
<SYSTEM_TASK:>
Return True if path has subdirectories
<END_TASK>
<USER_TASK:>
Description:
def has_subdirectories(path, include, exclude, show_all):
"""Return True if path has subdirectories"""
|
try:
# > 1 because of '..'
return len( listdir(path, include, exclude,
show_all, folders_only=True) ) > 1
except (IOError, OSError):
return False
|
<SYSTEM_TASK:>
Set single click to open items.
<END_TASK>
<USER_TASK:>
Description:
def set_single_click_to_open(self, value):
"""Set single click to open items."""
|
self.single_click_to_open = value
self.parent_widget.sig_option_changed.emit('single_click_to_open',
value)
|
<SYSTEM_TASK:>
Setup tree widget
<END_TASK>
<USER_TASK:>
Description:
def setup(self, name_filters=['*.py', '*.pyw'], show_all=False,
single_click_to_open=False):
"""Setup tree widget"""
|
self.setup_view()
self.set_name_filters(name_filters)
self.show_all = show_all
self.single_click_to_open = single_click_to_open
# Setup context menu
self.menu = QMenu(self)
self.common_actions = self.setup_common_actions()
|
<SYSTEM_TASK:>
Return folder management actions
<END_TASK>
<USER_TASK:>
Description:
def create_folder_manage_actions(self, fnames):
"""Return folder management actions"""
|
actions = []
if os.name == 'nt':
_title = _("Open command prompt here")
else:
_title = _("Open terminal here")
_title = _("Open IPython console here")
action = create_action(self, _title,
triggered=lambda:
self.open_interpreter(fnames))
actions.append(action)
return actions
|
<SYSTEM_TASK:>
Open files with the appropriate application
<END_TASK>
<USER_TASK:>
Description:
def open(self, fnames=None):
"""Open files with the appropriate application"""
|
if fnames is None:
fnames = self.get_selected_filenames()
for fname in fnames:
if osp.isfile(fname) and encoding.is_text_file(fname):
self.parent_widget.sig_open_file.emit(fname)
else:
self.open_outside_spyder([fname])
|
<SYSTEM_TASK:>
Open file outside Spyder with the appropriate application
<END_TASK>
<USER_TASK:>
Description:
def open_outside_spyder(self, fnames):
"""Open file outside Spyder with the appropriate application
If this does not work, opening unknown file in Spyder, as text file"""
|
for path in sorted(fnames):
path = file_uri(path)
ok = programs.start_file(path)
if not ok:
self.sig_edit.emit(path)
|
<SYSTEM_TASK:>
Remove whole directory tree
<END_TASK>
<USER_TASK:>
Description:
def remove_tree(self, dirname):
"""Remove whole directory tree
Reimplemented in project explorer widget"""
|
while osp.exists(dirname):
try:
shutil.rmtree(dirname, onerror=misc.onerror)
except Exception as e:
# This handles a Windows problem with shutil.rmtree.
# See issue #8567.
if type(e).__name__ == "OSError":
error_path = to_text_string(e.filename)
shutil.rmtree(error_path, ignore_errors=True)
|
<SYSTEM_TASK:>
Convert an IPython notebook to a Python script in editor
<END_TASK>
<USER_TASK:>
Description:
def convert_notebook(self, fname):
"""Convert an IPython notebook to a Python script in editor"""
|
try:
script = nbexporter().from_filename(fname)[0]
except Exception as e:
QMessageBox.critical(self, _('Conversion error'),
_("It was not possible to convert this "
"notebook. The error is:\n\n") + \
to_text_string(e))
return
self.sig_new_file.emit(script)
|
<SYSTEM_TASK:>
Convert IPython notebooks to Python scripts in editor
<END_TASK>
<USER_TASK:>
Description:
def convert_notebooks(self):
"""Convert IPython notebooks to Python scripts in editor"""
|
fnames = self.get_selected_filenames()
if not isinstance(fnames, (tuple, list)):
fnames = [fnames]
for fname in fnames:
self.convert_notebook(fname)
|
<SYSTEM_TASK:>
Create new file
<END_TASK>
<USER_TASK:>
Description:
def create_new_file(self, current_path, title, filters, create_func):
"""Create new file
Returns True if successful"""
|
if current_path is None:
current_path = ''
if osp.isfile(current_path):
current_path = osp.dirname(current_path)
self.redirect_stdio.emit(False)
fname, _selfilter = getsavefilename(self, title, current_path, filters)
self.redirect_stdio.emit(True)
if fname:
try:
create_func(fname)
return fname
except EnvironmentError as error:
QMessageBox.critical(self, _("New file"),
_("<b>Unable to create file <i>%s</i>"
"</b><br><br>Error message:<br>%s"
) % (fname, to_text_string(error)))
|
<SYSTEM_TASK:>
Create shortcuts for this file explorer.
<END_TASK>
<USER_TASK:>
Description:
def create_shortcuts(self):
"""Create shortcuts for this file explorer."""
|
# Configurable
copy_clipboard_file = config_shortcut(self.copy_file_clipboard,
context='explorer',
name='copy file', parent=self)
paste_clipboard_file = config_shortcut(self.save_file_clipboard,
context='explorer',
name='paste file', parent=self)
copy_absolute_path = config_shortcut(self.copy_absolute_path,
context='explorer',
name='copy absolute path',
parent=self)
copy_relative_path = config_shortcut(self.copy_relative_path,
context='explorer',
name='copy relative path',
parent=self)
return [copy_clipboard_file, paste_clipboard_file, copy_absolute_path,
copy_relative_path]
|
<SYSTEM_TASK:>
Restore scrollbar positions once tree is loaded
<END_TASK>
<USER_TASK:>
Description:
def restore_scrollbar_positions(self):
"""Restore scrollbar positions once tree is loaded"""
|
hor, ver = self._scrollbar_positions
self.horizontalScrollBar().setValue(hor)
self.verticalScrollBar().setValue(ver)
|
<SYSTEM_TASK:>
Restore directory expanded state
<END_TASK>
<USER_TASK:>
Description:
def restore_directory_state(self, fname):
"""Restore directory expanded state"""
|
root = osp.normpath(to_text_string(fname))
if not osp.exists(root):
# Directory has been (re)moved outside Spyder
return
for basename in os.listdir(root):
path = osp.normpath(osp.join(root, basename))
if osp.isdir(path) and path in self.__expanded_state:
self.__expanded_state.pop(self.__expanded_state.index(path))
if self._to_be_loaded is None:
self._to_be_loaded = []
self._to_be_loaded.append(path)
self.setExpanded(self.get_index(path), True)
if not self.__expanded_state:
self.fsmodel.directoryLoaded.disconnect(self.restore_directory_state)
|
<SYSTEM_TASK:>
Follow directories loaded during startup
<END_TASK>
<USER_TASK:>
Description:
def follow_directories_loaded(self, fname):
"""Follow directories loaded during startup"""
|
if self._to_be_loaded is None:
return
path = osp.normpath(to_text_string(fname))
if path in self._to_be_loaded:
self._to_be_loaded.remove(path)
if self._to_be_loaded is not None and len(self._to_be_loaded) == 0:
self.fsmodel.directoryLoaded.disconnect(
self.follow_directories_loaded)
if self._scrollbar_positions is not None:
# The tree view need some time to render branches:
QTimer.singleShot(50, self.restore_scrollbar_positions)
|
<SYSTEM_TASK:>
Filter the directories to show
<END_TASK>
<USER_TASK:>
Description:
def filter_directories(self):
"""Filter the directories to show"""
|
index = self.get_index('.spyproject')
if index is not None:
self.setRowHidden(index.row(), index.parent(), True)
|
<SYSTEM_TASK:>
Show tooltip with full path only for the root directory
<END_TASK>
<USER_TASK:>
Description:
def data(self, index, role):
"""Show tooltip with full path only for the root directory"""
|
if role == Qt.ToolTipRole:
root_dir = self.path_list[0].split(osp.sep)[-1]
if index.data() == root_dir:
return osp.join(self.root_path, root_dir)
return QSortFilterProxyModel.data(self, index, role)
|
<SYSTEM_TASK:>
Return index associated with filename
<END_TASK>
<USER_TASK:>
Description:
def get_index(self, filename):
"""Return index associated with filename"""
|
index = self.fsmodel.index(filename)
if index.isValid() and index.model() is self.fsmodel:
return self.proxymodel.mapFromSource(index)
|
<SYSTEM_TASK:>
Toggle show current directory only mode
<END_TASK>
<USER_TASK:>
Description:
def toggle_show_cd_only(self, checked):
"""Toggle show current directory only mode"""
|
self.parent_widget.sig_option_changed.emit('show_cd_only', checked)
self.show_cd_only = checked
if checked:
if self.__last_folder is not None:
self.set_current_folder(self.__last_folder)
elif self.__original_root_index is not None:
self.setRootIndex(self.__original_root_index)
|
<SYSTEM_TASK:>
Set current folder and return associated model index
<END_TASK>
<USER_TASK:>
Description:
def set_current_folder(self, folder):
"""Set current folder and return associated model index"""
|
index = self.fsmodel.setRootPath(folder)
self.__last_folder = folder
if self.show_cd_only:
if self.__original_root_index is None:
self.__original_root_index = self.rootIndex()
self.setRootIndex(index)
return index
|
<SYSTEM_TASK:>
Go to parent directory
<END_TASK>
<USER_TASK:>
Description:
def go_to_parent_directory(self):
"""Go to parent directory"""
|
self.chdir(osp.abspath(osp.join(getcwd_or_home(), os.pardir)))
|
<SYSTEM_TASK:>
Get the list of languages we need to start servers and create
<END_TASK>
<USER_TASK:>
Description:
def get_languages(self):
"""
Get the list of languages we need to start servers and create
clients for.
"""
|
languages = ['python']
all_options = CONF.options(self.CONF_SECTION)
for option in all_options:
if option in [l.lower() for l in LSP_LANGUAGES]:
languages.append(option)
return languages
|
<SYSTEM_TASK:>
Get root path to pass to the LSP servers.
<END_TASK>
<USER_TASK:>
Description:
def get_root_path(self, language):
"""
Get root path to pass to the LSP servers.
This can be the current project path or the output of
getcwd_or_home (except for Python, see below).
"""
|
path = None
# Get path of the current project
if self.main and self.main.projects:
path = self.main.projects.get_active_project_path()
# If there's no project, use the output of getcwd_or_home.
if not path:
# We can't use getcwd_or_home for Python because if it
# returns home and you have a lot of Python files on it
# then computing Rope completions takes a long time
# and blocks the PyLS server.
# Instead we use an empty directory inside our config one,
# just like we did for Rope in Spyder 3.
if language == 'python':
path = get_conf_path('lsp_root_path')
if not osp.exists(path):
os.mkdir(path)
else:
path = getcwd_or_home()
return path
|
<SYSTEM_TASK:>
Send a new initialize message to each LSP server when the project
<END_TASK>
<USER_TASK:>
Description:
def reinitialize_all_clients(self):
"""
Send a new initialize message to each LSP server when the project
path has changed so they can update the respective server root paths.
"""
|
for language in self.clients:
language_client = self.clients[language]
if language_client['status'] == self.RUNNING:
folder = self.get_root_path(language)
instance = language_client['instance']
instance.folder = folder
instance.initialize()
|
<SYSTEM_TASK:>
Start an LSP client for a given language.
<END_TASK>
<USER_TASK:>
Description:
def start_client(self, language):
"""Start an LSP client for a given language."""
|
started = False
if language in self.clients:
language_client = self.clients[language]
queue = self.register_queue[language]
# Don't start LSP services when testing unless we demand
# them.
if running_under_pytest():
if not os.environ.get('SPY_TEST_USE_INTROSPECTION'):
return started
# Start client
started = language_client['status'] == self.RUNNING
if language_client['status'] == self.STOPPED:
config = language_client['config']
if not config['external']:
port = select_port(default_port=config['port'])
config['port'] = port
language_client['instance'] = LSPClient(
parent=self,
server_settings=config,
folder=self.get_root_path(language),
language=language
)
# Connect signals emitted by the client to the methods that
# can handle them
if self.main and self.main.editor:
language_client['instance'].sig_initialize.connect(
self.main.editor.register_lsp_server_settings)
logger.info("Starting LSP client for {}...".format(language))
language_client['instance'].start()
language_client['status'] = self.RUNNING
for entry in queue:
language_client.register_file(*entry)
self.register_queue[language] = []
return started
|
<SYSTEM_TASK:>
Return a unicode version of string decoded using the file system encoding.
<END_TASK>
<USER_TASK:>
Description:
def to_unicode_from_fs(string):
"""
Return a unicode version of string decoded using the file system encoding.
"""
|
if not is_string(string): # string is a QString
string = to_text_string(string.toUtf8(), 'utf-8')
else:
if is_binary_string(string):
try:
unic = string.decode(FS_ENCODING)
except (UnicodeError, TypeError):
pass
else:
return unic
return string
|
<SYSTEM_TASK:>
Return a byte string version of unic encoded using the file
<END_TASK>
<USER_TASK:>
Description:
def to_fs_from_unicode(unic):
"""
Return a byte string version of unic encoded using the file
system encoding.
"""
|
if is_unicode(unic):
try:
string = unic.encode(FS_ENCODING)
except (UnicodeError, TypeError):
pass
else:
return string
return unic
|
<SYSTEM_TASK:>
Function to decode a text.
<END_TASK>
<USER_TASK:>
Description:
def decode(text):
"""
Function to decode a text.
@param text text to decode (string)
@return decoded text and encoding
"""
|
try:
if text.startswith(BOM_UTF8):
# UTF-8 with BOM
return to_text_string(text[len(BOM_UTF8):], 'utf-8'), 'utf-8-bom'
elif text.startswith(BOM_UTF16):
# UTF-16 with BOM
return to_text_string(text[len(BOM_UTF16):], 'utf-16'), 'utf-16'
elif text.startswith(BOM_UTF32):
# UTF-32 with BOM
return to_text_string(text[len(BOM_UTF32):], 'utf-32'), 'utf-32'
coding = get_coding(text)
if coding:
return to_text_string(text, coding), coding
except (UnicodeError, LookupError):
pass
# Assume UTF-8
try:
return to_text_string(text, 'utf-8'), 'utf-8-guessed'
except (UnicodeError, LookupError):
pass
# Assume Latin-1 (behaviour before 3.7.1)
return to_text_string(text, "latin-1"), 'latin-1-guessed'
|
<SYSTEM_TASK:>
Return all file type extensions supported by Pygments
<END_TASK>
<USER_TASK:>
Description:
def _get_pygments_extensions():
"""Return all file type extensions supported by Pygments"""
|
# NOTE: Leave this import here to keep startup process fast!
import pygments.lexers as lexers
extensions = []
for lx in lexers.get_all_lexers():
lexer_exts = lx[2]
if lexer_exts:
# Reference: This line was included for leaving untrimmed the
# extensions not starting with `*`
other_exts = [le for le in lexer_exts if not le.startswith('*')]
# Reference: This commented line was replaced by the following one
# to trim only extensions that start with '*'
# lexer_exts = [le[1:] for le in lexer_exts]
lexer_exts = [le[1:] for le in lexer_exts if le.startswith('*')]
lexer_exts = [le for le in lexer_exts if not le.endswith('_*')]
extensions = extensions + list(lexer_exts) + list(other_exts)
return sorted(list(set(extensions)))
|
<SYSTEM_TASK:>
Return filter associated to file extension
<END_TASK>
<USER_TASK:>
Description:
def get_filter(filetypes, ext):
"""Return filter associated to file extension"""
|
if not ext:
return ALL_FILTER
for title, ftypes in filetypes:
if ext in ftypes:
return _create_filter(title, ftypes)
else:
return ''
|
<SYSTEM_TASK:>
Get all file types supported by the Editor
<END_TASK>
<USER_TASK:>
Description:
def get_edit_filetypes():
"""Get all file types supported by the Editor"""
|
# The filter details are not hidden on Windows, so we can't use
# all Pygments extensions on that platform
if os.name == 'nt':
supported_exts = []
else:
try:
supported_exts = _get_pygments_extensions()
except Exception:
supported_exts = []
# NOTE: Try to not add too much extensions to this list to not
# make the filter look too big on Windows
favorite_exts = ['.py', '.R', '.jl', '.ipynb', '.md', '.pyw', '.pyx',
'.c', '.cpp', '.json', '.dat', '.csv', '.tsv', '.txt',
'.ini', '.html', '.js', '.h', '.bat']
other_exts = [ext for ext in supported_exts if ext not in favorite_exts]
all_exts = tuple(favorite_exts + other_exts)
text_filetypes = (_("Supported text files"), all_exts)
return [text_filetypes] + EDIT_FILETYPES
|
<SYSTEM_TASK:>
Detect if we are running in an Ubuntu-based distribution
<END_TASK>
<USER_TASK:>
Description:
def is_ubuntu():
"""Detect if we are running in an Ubuntu-based distribution"""
|
if sys.platform.startswith('linux') and osp.isfile('/etc/lsb-release'):
release_info = open('/etc/lsb-release').read()
if 'Ubuntu' in release_info:
return True
else:
return False
else:
return False
|
<SYSTEM_TASK:>
Detect if we are running in a Gtk-based desktop
<END_TASK>
<USER_TASK:>
Description:
def is_gtk_desktop():
"""Detect if we are running in a Gtk-based desktop"""
|
if sys.platform.startswith('linux'):
xdg_desktop = os.environ.get('XDG_CURRENT_DESKTOP', '')
if xdg_desktop:
gtk_desktops = ['Unity', 'GNOME', 'XFCE']
if any([xdg_desktop.startswith(d) for d in gtk_desktops]):
return True
else:
return False
else:
return False
else:
return False
|
<SYSTEM_TASK:>
Detect if we are running in a KDE desktop
<END_TASK>
<USER_TASK:>
Description:
def is_kde_desktop():
"""Detect if we are running in a KDE desktop"""
|
if sys.platform.startswith('linux'):
xdg_desktop = os.environ.get('XDG_CURRENT_DESKTOP', '')
if xdg_desktop:
if 'KDE' in xdg_desktop:
return True
else:
return False
else:
return False
else:
return False
|
<SYSTEM_TASK:>
Return True if dirname is in project's PYTHONPATH
<END_TASK>
<USER_TASK:>
Description:
def is_in_pythonpath(self, dirname):
"""Return True if dirname is in project's PYTHONPATH"""
|
return fixpath(dirname) in [fixpath(_p) for _p in self.pythonpath]
|
<SYSTEM_TASK:>
Remove path from project's PYTHONPATH
<END_TASK>
<USER_TASK:>
Description:
def remove_from_pythonpath(self, path):
"""Remove path from project's PYTHONPATH
Return True if path was removed, False if it was not found"""
|
pathlist = self.get_pythonpath()
if path in pathlist:
pathlist.pop(pathlist.index(path))
self.set_pythonpath(pathlist)
return True
else:
return False
|
<SYSTEM_TASK:>
Add path to project's PYTHONPATH
<END_TASK>
<USER_TASK:>
Description:
def add_to_pythonpath(self, path):
"""Add path to project's PYTHONPATH
Return True if path was added, False if it was already there"""
|
pathlist = self.get_pythonpath()
if path in pathlist:
return False
else:
pathlist.insert(0, path)
self.set_pythonpath(pathlist)
return True
|
<SYSTEM_TASK:>
Set the OpenGL implementation used by Spyder.
<END_TASK>
<USER_TASK:>
Description:
def set_opengl_implementation(option):
"""
Set the OpenGL implementation used by Spyder.
See issue 7447 for the details.
"""
|
if option == 'software':
QCoreApplication.setAttribute(Qt.AA_UseSoftwareOpenGL)
if QQuickWindow is not None:
QQuickWindow.setSceneGraphBackend(QSGRendererInterface.Software)
elif option == 'desktop':
QCoreApplication.setAttribute(Qt.AA_UseDesktopOpenGL)
if QQuickWindow is not None:
QQuickWindow.setSceneGraphBackend(QSGRendererInterface.OpenGL)
elif option == 'gles':
QCoreApplication.setAttribute(Qt.AA_UseOpenGLES)
if QQuickWindow is not None:
QQuickWindow.setSceneGraphBackend(QSGRendererInterface.OpenGL)
|
<SYSTEM_TASK:>
Setup logging with cli options defined by the user.
<END_TASK>
<USER_TASK:>
Description:
def setup_logging(cli_options):
"""Setup logging with cli options defined by the user."""
|
if cli_options.debug_info or get_debug_level() > 0:
levels = {2: logging.INFO, 3: logging.DEBUG}
log_level = levels[get_debug_level()]
log_format = '%(asctime)s [%(levelname)s] [%(name)s] -> %(message)s'
if cli_options.debug_output == 'file':
log_file = 'spyder-debug.log'
else:
log_file = None
logging.basicConfig(level=log_level,
format=log_format,
filename=log_file,
filemode='w+')
|
<SYSTEM_TASK:>
Qt warning messages are intercepted by this handler.
<END_TASK>
<USER_TASK:>
Description:
def qt_message_handler(msg_type, msg_log_context, msg_string):
"""
Qt warning messages are intercepted by this handler.
On some operating systems, warning messages might be displayed
even if the actual message does not apply. This filter adds a
blacklist for messages that are being printed for no apparent
reason. Anything else will get printed in the internal console.
In DEV mode, all messages are printed.
"""
|
BLACKLIST = [
'QMainWidget::resizeDocks: all sizes need to be larger than 0',
]
if DEV or msg_string not in BLACKLIST:
print(msg_string)
|
<SYSTEM_TASK:>
Initialize Qt, patching sys.exit and eventually setting up ETS
<END_TASK>
<USER_TASK:>
Description:
def initialize():
"""Initialize Qt, patching sys.exit and eventually setting up ETS"""
|
# This doesn't create our QApplication, just holds a reference to
# MAIN_APP, created above to show our splash screen as early as
# possible
app = qapplication()
# --- Set application icon
app.setWindowIcon(APP_ICON)
#----Monkey patching QApplication
class FakeQApplication(QApplication):
"""Spyder's fake QApplication"""
def __init__(self, args):
self = app # analysis:ignore
@staticmethod
def exec_():
"""Do nothing because the Qt mainloop is already running"""
pass
from qtpy import QtWidgets
QtWidgets.QApplication = FakeQApplication
# ----Monkey patching sys.exit
def fake_sys_exit(arg=[]):
pass
sys.exit = fake_sys_exit
# ----Monkey patching sys.excepthook to avoid crashes in PyQt 5.5+
if PYQT5:
def spy_excepthook(type_, value, tback):
sys.__excepthook__(type_, value, tback)
sys.excepthook = spy_excepthook
# Removing arguments from sys.argv as in standard Python interpreter
sys.argv = ['']
# Selecting Qt4 backend for Enthought Tool Suite (if installed)
try:
from enthought.etsconfig.api import ETSConfig
ETSConfig.toolkit = 'qt4'
except ImportError:
pass
return app
|
<SYSTEM_TASK:>
Create and show Spyder's main window
<END_TASK>
<USER_TASK:>
Description:
def run_spyder(app, options, args):
"""
Create and show Spyder's main window
Start QApplication event loop
"""
|
#TODO: insert here
# Main window
main = MainWindow(options)
try:
main.setup()
except BaseException:
if main.console is not None:
try:
main.console.shell.exit_interpreter()
except BaseException:
pass
raise
main.show()
main.post_visible_setup()
if main.console:
main.console.shell.interpreter.namespace['spy'] = \
Spy(app=app, window=main)
# Open external files passed as args
if args:
for a in args:
main.open_external_file(a)
# Don't show icons in menus for Mac
if sys.platform == 'darwin':
QCoreApplication.setAttribute(Qt.AA_DontShowIconsInMenus, True)
# Open external files with our Mac app
if running_in_mac_app():
app.sig_open_external_file.connect(main.open_external_file)
# To give focus again to the last focused widget after restoring
# the window
app.focusChanged.connect(main.change_last_focused_widget)
if not running_under_pytest():
app.exec_()
return main
|
<SYSTEM_TASK:>
Actions to be performed only after the main window's `show` method
<END_TASK>
<USER_TASK:>
Description:
def post_visible_setup(self):
"""Actions to be performed only after the main window's `show` method
was triggered"""
|
self.restore_scrollbar_position.emit()
# [Workaround for Issue 880]
# QDockWidget objects are not painted if restored as floating
# windows, so we must dock them before showing the mainwindow,
# then set them again as floating windows here.
for widget in self.floating_dockwidgets:
widget.setFloating(True)
# In MacOS X 10.7 our app is not displayed after initialized (I don't
# know why because this doesn't happen when started from the terminal),
# so we need to resort to this hack to make it appear.
if running_in_mac_app():
idx = __file__.index(MAC_APP_NAME)
app_path = __file__[:idx]
subprocess.call(['open', app_path + MAC_APP_NAME])
# Server to maintain just one Spyder instance and open files in it if
# the user tries to start other instances with
# $ spyder foo.py
if (CONF.get('main', 'single_instance') and not self.new_instance
and self.open_files_server):
t = threading.Thread(target=self.start_open_files_server)
t.setDaemon(True)
t.start()
# Connect the window to the signal emmited by the previous server
# when it gets a client connected to it
self.sig_open_external_file.connect(self.open_external_file)
# Create Plugins and toolbars submenus
self.create_plugins_menu()
self.create_toolbars_menu()
# Update toolbar visibility status
self.toolbars_visible = CONF.get('main', 'toolbars_visible')
self.load_last_visible_toolbars()
# Update lock status
self.lock_interface_action.setChecked(self.interface_locked)
# Hide Internal Console so that people don't use it instead of
# the External or IPython ones
if self.console.dockwidget.isVisible() and DEV is None:
self.console.toggle_view_action.setChecked(False)
self.console.dockwidget.hide()
# Show Help and Consoles by default
plugins_to_show = [self.ipyconsole]
if self.help is not None:
plugins_to_show.append(self.help)
for plugin in plugins_to_show:
if plugin.dockwidget.isVisible():
plugin.dockwidget.raise_()
# Show history file if no console is visible
if not self.ipyconsole.isvisible:
self.historylog.add_history(get_conf_path('history.py'))
if self.open_project:
self.projects.open_project(self.open_project)
else:
# Load last project if a project was active when Spyder
# was closed
self.projects.reopen_last_project()
# If no project is active, load last session
if self.projects.get_active_project() is None:
self.editor.setup_open_files()
# Check for spyder updates
if DEV is None and CONF.get('main', 'check_updates_on_startup'):
self.give_updates_feedback = False
self.check_updates(startup=True)
# Show dialog with missing dependencies
self.report_missing_dependencies()
# Raise the menuBar to the top of the main window widget's stack
# (Fixes issue 3887)
self.menuBar().raise_()
self.is_setting_up = False
|
<SYSTEM_TASK:>
Show a QMessageBox with a list of missing hard dependencies
<END_TASK>
<USER_TASK:>
Description:
def report_missing_dependencies(self):
"""Show a QMessageBox with a list of missing hard dependencies"""
|
missing_deps = dependencies.missing_dependencies()
if missing_deps:
QMessageBox.critical(self, _('Error'),
_("<b>You have missing dependencies!</b>"
"<br><br><tt>%s</tt><br><br>"
"<b>Please install them to avoid this message.</b>"
"<br><br>"
"<i>Note</i>: Spyder could work without some of these "
"dependencies, however to have a smooth experience when "
"using Spyder we <i>strongly</i> recommend you to install "
"all the listed missing dependencies.<br><br>"
"Failing to install these dependencies might result in bugs. "
"Please be sure that any found bugs are not the direct "
"result of missing dependencies, prior to reporting a new "
"issue."
) % missing_deps, QMessageBox.Ok)
|
<SYSTEM_TASK:>
Return current window settings
<END_TASK>
<USER_TASK:>
Description:
def get_window_settings(self):
"""Return current window settings
Symetric to the 'set_window_settings' setter"""
|
window_size = (self.window_size.width(), self.window_size.height())
is_fullscreen = self.isFullScreen()
if is_fullscreen:
is_maximized = self.maximized_flag
else:
is_maximized = self.isMaximized()
pos = (self.window_position.x(), self.window_position.y())
prefs_dialog_size = (self.prefs_dialog_size.width(),
self.prefs_dialog_size.height())
hexstate = qbytearray_to_str(self.saveState())
return (hexstate, window_size, prefs_dialog_size, pos, is_maximized,
is_fullscreen)
|
<SYSTEM_TASK:>
Set window settings
<END_TASK>
<USER_TASK:>
Description:
def set_window_settings(self, hexstate, window_size, prefs_dialog_size,
pos, is_maximized, is_fullscreen):
"""Set window settings
Symetric to the 'get_window_settings' accessor"""
|
self.setUpdatesEnabled(False)
self.window_size = QSize(window_size[0], window_size[1]) # width,height
self.prefs_dialog_size = QSize(prefs_dialog_size[0],
prefs_dialog_size[1]) # width,height
self.window_position = QPoint(pos[0], pos[1]) # x,y
self.setWindowState(Qt.WindowNoState)
self.resize(self.window_size)
self.move(self.window_position)
# Window layout
if hexstate:
self.restoreState( QByteArray().fromHex(
str(hexstate).encode('utf-8')) )
# [Workaround for Issue 880]
# QDockWidget objects are not painted if restored as floating
# windows, so we must dock them before showing the mainwindow.
for widget in self.children():
if isinstance(widget, QDockWidget) and widget.isFloating():
self.floating_dockwidgets.append(widget)
widget.setFloating(False)
# Is fullscreen?
if is_fullscreen:
self.setWindowState(Qt.WindowFullScreen)
self.__update_fullscreen_action()
# Is maximized?
if is_fullscreen:
self.maximized_flag = is_maximized
elif is_maximized:
self.setWindowState(Qt.WindowMaximized)
self.setUpdatesEnabled(True)
|
<SYSTEM_TASK:>
Reset window layout to default
<END_TASK>
<USER_TASK:>
Description:
def reset_window_layout(self):
"""Reset window layout to default"""
|
answer = QMessageBox.warning(self, _("Warning"),
_("Window layout will be reset to default settings: "
"this affects window position, size and dockwidgets.\n"
"Do you want to continue?"),
QMessageBox.Yes | QMessageBox.No)
if answer == QMessageBox.Yes:
self.setup_layout(default=True)
|
<SYSTEM_TASK:>
Update the text displayed in the menu entry.
<END_TASK>
<USER_TASK:>
Description:
def _update_show_toolbars_action(self):
"""Update the text displayed in the menu entry."""
|
if self.toolbars_visible:
text = _("Hide toolbars")
tip = _("Hide toolbars")
else:
text = _("Show toolbars")
tip = _("Show toolbars")
self.show_toolbars_action.setText(text)
self.show_toolbars_action.setToolTip(tip)
|
<SYSTEM_TASK:>
Saves the name of the visible toolbars in the .ini file.
<END_TASK>
<USER_TASK:>
Description:
def save_visible_toolbars(self):
"""Saves the name of the visible toolbars in the .ini file."""
|
toolbars = []
for toolbar in self.visible_toolbars:
toolbars.append(toolbar.objectName())
CONF.set('main', 'last_visible_toolbars', toolbars)
|
<SYSTEM_TASK:>
Handle an invalid active project.
<END_TASK>
<USER_TASK:>
Description:
def valid_project(self):
"""Handle an invalid active project."""
|
try:
path = self.projects.get_active_project_path()
except AttributeError:
return
if bool(path):
if not self.projects.is_valid_project(path):
if path:
QMessageBox.critical(
self,
_('Error'),
_("<b>{}</b> is no longer a valid Spyder project! "
"Since it is the current active project, it will "
"be closed automatically.").format(path))
self.projects.close_project()
|
<SYSTEM_TASK:>
Show action shortcuts in menu
<END_TASK>
<USER_TASK:>
Description:
def show_shortcuts(self, menu):
"""Show action shortcuts in menu"""
|
for element in getattr(self, menu + '_menu_actions'):
if element and isinstance(element, QAction):
if element._shown_shortcut is not None:
element.setShortcut(element._shown_shortcut)
|
<SYSTEM_TASK:>
Hide action shortcuts in menu
<END_TASK>
<USER_TASK:>
Description:
def hide_shortcuts(self, menu):
"""Hide action shortcuts in menu"""
|
for element in getattr(self, menu + '_menu_actions'):
if element and isinstance(element, QAction):
if element._shown_shortcut is not None:
element.setShortcut(QKeySequence())
|
<SYSTEM_TASK:>
To keep track of to the last focused widget
<END_TASK>
<USER_TASK:>
Description:
def change_last_focused_widget(self, old, now):
"""To keep track of to the last focused widget"""
|
if (now is None and QApplication.activeWindow() is not None):
QApplication.activeWindow().setFocus()
self.last_focused_widget = QApplication.focusWidget()
elif now is not None:
self.last_focused_widget = now
self.previous_focused_widget = old
|
<SYSTEM_TASK:>
Add widget actions to toolbar
<END_TASK>
<USER_TASK:>
Description:
def add_to_toolbar(self, toolbar, widget):
"""Add widget actions to toolbar"""
|
actions = widget.toolbar_actions
if actions is not None:
add_actions(toolbar, actions)
|
<SYSTEM_TASK:>
Report a Spyder issue to github, generating body text if needed.
<END_TASK>
<USER_TASK:>
Description:
def report_issue(self, body=None, title=None, open_webpage=False):
"""Report a Spyder issue to github, generating body text if needed."""
|
if body is None:
from spyder.widgets.reporterror import SpyderErrorDialog
report_dlg = SpyderErrorDialog(self, is_report=True)
report_dlg.show()
else:
if open_webpage:
if PY3:
from urllib.parse import quote
else:
from urllib import quote # analysis:ignore
from qtpy.QtCore import QUrlQuery
url = QUrl(__project_url__ + '/issues/new')
query = QUrlQuery()
query.addQueryItem("body", quote(body))
if title:
query.addQueryItem("title", quote(title))
url.setQuery(query)
QDesktopServices.openUrl(url)
|
<SYSTEM_TASK:>
Open external console
<END_TASK>
<USER_TASK:>
Description:
def open_external_console(self, fname, wdir, args, interact, debug, python,
python_args, systerm, post_mortem=False):
"""Open external console"""
|
if systerm:
# Running script in an external system terminal
try:
if CONF.get('main_interpreter', 'default'):
executable = get_python_executable()
else:
executable = CONF.get('main_interpreter', 'executable')
programs.run_python_script_in_terminal(
fname, wdir, args, interact, debug, python_args,
executable)
except NotImplementedError:
QMessageBox.critical(self, _("Run"),
_("Running an external system terminal "
"is not supported on platform %s."
) % os.name)
|
<SYSTEM_TASK:>
Execute lines in IPython console and eventually set focus
<END_TASK>
<USER_TASK:>
Description:
def execute_in_external_console(self, lines, focus_to_editor):
"""
Execute lines in IPython console and eventually set focus
to the Editor.
"""
|
console = self.ipyconsole
console.switch_to_plugin()
console.execute_code(lines)
if focus_to_editor:
self.editor.switch_to_plugin()
|
<SYSTEM_TASK:>
Open external files that can be handled either by the Editor or the
<END_TASK>
<USER_TASK:>
Description:
def open_external_file(self, fname):
"""
Open external files that can be handled either by the Editor or the
variable explorer inside Spyder.
"""
|
fname = encoding.to_unicode_from_fs(fname)
if osp.isfile(fname):
self.open_file(fname, external=True)
elif osp.isfile(osp.join(CWD, fname)):
self.open_file(osp.join(CWD, fname), external=True)
|
<SYSTEM_TASK:>
Apply settings changed in 'Preferences' dialog box
<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:
style_name = CONF.get('appearance', 'windows_style',
self.default_style)
style = QStyleFactory.create(style_name)
if style is not None:
style.setProperty('name', style_name)
qapp.setStyle(style)
default = self.DOCKOPTIONS
if CONF.get('main', 'vertical_tabs'):
default = default|QMainWindow.VerticalTabs
if CONF.get('main', 'animated_docks'):
default = default|QMainWindow.AnimatedDocks
self.setDockOptions(default)
self.apply_panes_settings()
self.apply_statusbar_settings()
if CONF.get('main', 'use_custom_cursor_blinking'):
qapp.setCursorFlashTime(CONF.get('main', 'custom_cursor_blinking'))
else:
qapp.setCursorFlashTime(self.CURSORBLINK_OSDEFAULT)
|
<SYSTEM_TASK:>
Quit and reset Spyder and then Restart application.
<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:>
Quit and Restart Spyder application.
<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 spyder/app/start.py
env = os.environ.copy()
bootstrap_args = env.pop('SPYDER_BOOTSTRAP_ARGS', None)
spyder_args = env.pop('SPYDER_ARGS')
# Get current process and python running spyder
pid = os.getpid()
python = sys.executable
# Check if started with bootstrap.py
if bootstrap_args is not None:
spyder_args = bootstrap_args
is_bootstrap = True
else:
is_bootstrap = False
# Pass variables as environment variables (str) to restarter subprocess
env['SPYDER_ARGS'] = spyder_args
env['SPYDER_PID'] = str(pid)
env['SPYDER_IS_BOOTSTRAP'] = str(is_bootstrap)
env['SPYDER_RESET'] = str(reset)
if DEV:
if os.name == 'nt':
env['PYTHONPATH'] = ';'.join(sys.path)
else:
env['PYTHONPATH'] = ':'.join(sys.path)
# Build the command and popen arguments depending on the OS
if os.name == 'nt':
# Hide flashing command prompt
startupinfo = subprocess.STARTUPINFO()
startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
shell = False
else:
startupinfo = None
shell = True
command = '"{0}" "{1}"'
command = command.format(python, restart_script)
try:
if self.closing(True):
subprocess.Popen(command, shell=shell, env=env,
startupinfo=startupinfo)
self.console.quit()
except Exception as error:
# If there is an error with subprocess, Spyder should not quit and
# the error can be inspected in the internal console
print(error) # spyder: test-skip
print(command)
|
<SYSTEM_TASK:>
Called by WorkerUpdates when ready
<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 = self.give_updates_feedback
# Get results from worker
update_available = self.worker_updates.update_available
latest_release = self.worker_updates.latest_release
error_msg = self.worker_updates.error
url_r = __project_url__ + '/releases'
url_i = 'https://docs.spyder-ide.org/installation.html'
# Define the custom QMessageBox
box = MessageCheckBox(icon=QMessageBox.Information,
parent=self)
box.setWindowTitle(_("Spyder updates"))
box.set_checkbox_text(_("Check for updates on startup"))
box.setStandardButtons(QMessageBox.Ok)
box.setDefaultButton(QMessageBox.Ok)
# Adjust the checkbox depending on the stored configuration
section, option = 'main', 'check_updates_on_startup'
check_updates = CONF.get(section, option)
box.set_checked(check_updates)
if error_msg is not None:
msg = error_msg
box.setText(msg)
box.set_check_visible(False)
box.exec_()
check_updates = box.is_checked()
else:
if update_available:
anaconda_msg = ''
if 'Anaconda' in sys.version or 'conda-forge' in sys.version:
anaconda_msg = _("<hr><b>IMPORTANT NOTE:</b> It seems "
"that you are using Spyder with "
"<b>Anaconda/Miniconda</b>. Please "
"<b>don't</b> use <code>pip</code> to "
"update it as that will probably break "
"your installation.<br><br>"
"Instead, please wait until new conda "
"packages are available and use "
"<code>conda</code> to perform the "
"update.<hr>")
msg = _("<b>Spyder %s is available!</b> <br><br>Please use "
"your package manager to update Spyder or go to our "
"<a href=\"%s\">Releases</a> page to download this "
"new version. <br><br>If you are not sure how to "
"proceed to update Spyder please refer to our "
" <a href=\"%s\">Installation</a> instructions."
"") % (latest_release, url_r, url_i)
msg += '<br>' + anaconda_msg
box.setText(msg)
box.set_check_visible(True)
box.exec_()
check_updates = box.is_checked()
elif feedback:
msg = _("Spyder is up to date.")
box.setText(msg)
box.set_check_visible(False)
box.exec_()
check_updates = box.is_checked()
# Update checkbox based on user interaction
CONF.set(section, option, check_updates)
# Enable check_updates_action after the thread has finished
self.check_updates_action.setDisabled(False)
# Provide feeback when clicking menu if check on startup is on
self.give_updates_feedback = True
|
<SYSTEM_TASK:>
Save config into the associated .ini file
<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:
self._write(configfile)
else:
# Python 3
with open(fname, 'w', encoding='utf-8') as configfile:
self.write(configfile)
try: # the "easy" way
_write_file(fname)
except EnvironmentError:
try: # the "delete and sleep" way
if osp.isfile(fname):
os.remove(fname)
time.sleep(0.05)
_write_file(fname)
except Exception as e:
print("Failed to write user configuration file to disk, with "
"the exception shown below") # spyder: test-skip
print(e)
|
<SYSTEM_TASK:>
Defines the name of the configuration file to use.
<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._filename_global()
else:
return self._filename_projects()
|
<SYSTEM_TASK:>
Create a .ini filename located in user home directory.
<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:
folder = osp.join(folder, 'defaults')
if not osp.isdir(folder):
os.mkdir(folder)
config_file = osp.join(folder, '%s.ini' % self.name)
return config_file
|
<SYSTEM_TASK:>
Load config from the associated .ini file
<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)
except IOError:
print("Failed reading file", fname) # spyder: test-skip
else:
# Python 3
self.read(self.filename(), encoding='utf-8')
except cp.MissingSectionHeaderError:
print("Warning: File contains no section headers.")
|
<SYSTEM_TASK:>
Update defaults after a change in version
<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, cp.NoOptionError):
old_value = None
if old_value is None or \
to_text_string(new_value) != old_value:
self._set(section, option, new_value, verbose)
|
<SYSTEM_TASK:>
Remove options which are present in the .ini file but not in defaults
<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_option(section, option)
if len(self.items(section, raw=self.raw)) == 0:
self.remove_section(section)
except cp.NoSectionError:
self.remove_section(section)
|
<SYSTEM_TASK:>
Set defaults from the current config
<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:>
Private method to check section and option types
<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 section
|
<SYSTEM_TASK:>
Return temporary Spyder directory, checking previously that it exists.
<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)
if not osp.isdir(tempdir):
os.mkdir(tempdir)
return tempdir
|
<SYSTEM_TASK:>
Return program absolute path if installed in PATH.
<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:>
Given a dict, populate kwargs to create a generally
<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 processes
on different platforms. For example, `close_fds` is
set on posix and creation of a new console window is
disabled on Windows.
This function will alter the given kwargs and return
the modified dict.
"""
|
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
CONSOLE_CREATION_FLAGS |= CREATE_NO_WINDOW
kwargs.setdefault('creationflags', CONSOLE_CREATION_FLAGS)
return kwargs
|
<SYSTEM_TASK:>
Generalized os.startfile for all platforms supported by Qt
<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
Returns True if successfull, otherwise returns False.
"""
|
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 = QUrl()
url.setUrl(filename)
return QDesktopServices.openUrl(url)
|
<SYSTEM_TASK:>
Check that the python interpreter file has a valid name.
<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:>
Evaluate wether a file is a python interpreter or not.
<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
if not encoding.is_text_file(real_filename):
return True
else:
return False
elif sys.platform == 'darwin':
# pythonw is a text file in Anaconda but a binary in
# the system
if is_anaconda() and encoding.is_text_file(real_filename):
return True
elif not encoding.is_text_file(real_filename):
return True
else:
return False
else:
# There's no pythonw in other systems
return False
elif encoding.is_text_file(real_filename):
# At this point we can't have a text file
return False
else:
return check_python_help(filename)
|
<SYSTEM_TASK:>
Check that the python interpreter has 'pythonw'.
<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:>
Check that the python interpreter can execute help.
<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:
return False
except:
return False
|
<SYSTEM_TASK:>
Draw the given breakpoint pixmap.
<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.
painter (QPainter)
icon_name (srt): key of icon to draw (see: self.icons)
"""
|
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:>
This methods illustrates how the workers can be used.
<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:>
Start process worker for given method args and kwargs.
<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:>
Set the environment on the QProcess.
<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:>
Delete periodically workers in workers bag.
<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:>
Start threads and check for inactive workers.
<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),
# self._running_threads,
# len(self._workers),
# len(self._threads)))
self._running_threads += 1
worker = self._queue_workers.popleft()
thread = QThread()
if isinstance(worker, PythonWorker):
worker.moveToThread(thread)
worker.sig_finished.connect(thread.quit)
thread.started.connect(worker._start)
thread.start()
elif isinstance(worker, ProcessWorker):
thread.quit()
worker._start()
self._threads.append(thread)
else:
self._timer.start()
if self._workers:
for w in self._workers:
if w.is_finished():
self._bag_collector.append(w)
self._workers.remove(w)
if self._threads:
for t in self._threads:
if t.isFinished():
self._threads.remove(t)
self._running_threads -= 1
if len(self._threads) == 0 and len(self._workers) == 0:
self._timer.stop()
self._timer_worker_delete.start()
|
<SYSTEM_TASK:>
Create a new python worker instance.
<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:>
Create a new process worker instance.
<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:>
Gather data about a given file.
<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:>
Convert file data to a string for display.
<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 += '<br><i>{}</i>: {} {}'.format(
_('Size'), data['size'], _('bytes'))
except KeyError:
res += '<br>' + _('<i>File no longer exists</i>')
return res
|
<SYSTEM_TASK:>
Make temporary files to simulate a recovery use case.
<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 another
directory with autosave files. Return a tuple with the name of the
directory with the original files, the name of the directory with the
autosave files, and the autosave mapping.
"""
|
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 f:
f.write('ham = "original"\n')
autosave_file = osp.join(autosave_dir, 'ham.py')
with open(autosave_file, 'w') as f:
f.write('ham = "autosave"\n')
autosave_mapping[orig_file] = autosave_file
# spam.py: Only autosave file exists, mentioned in mapping
orig_file = osp.join(orig_dir, 'spam.py')
autosave_file = osp.join(autosave_dir, 'spam.py')
with open(autosave_file, 'w') as f:
f.write('spam = "autosave"\n')
autosave_mapping[orig_file] = autosave_file
# eggs.py: Only original files exists, mentioned in mapping
orig_file = osp.join(orig_dir, 'eggs.py')
with open(orig_file, 'w') as f:
f.write('eggs = "original"\n')
autosave_file = osp.join(autosave_dir, 'eggs.py')
autosave_mapping[orig_file] = autosave_file
# cheese.py: Only autosave file exists, not mentioned in mapping
autosave_file = osp.join(autosave_dir, 'cheese.py')
with open(autosave_file, 'w') as f:
f.write('cheese = "autosave"\n')
return orig_dir, autosave_dir, autosave_mapping
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.