sentence1 stringlengths 52 3.87M | sentence2 stringlengths 1 47.2k | label stringclasses 1 value |
|---|---|---|
def _add_decoration(self, cursor):
"""
Adds a decoration for the word under ``cursor``.
"""
if self._deco is None:
if cursor.selectedText():
self._deco = TextDecoration(cursor)
if self.editor.background.lightness() < 128:
self._deco.set_foreground(QtGui.QColor('#0681e0'))
else:
self._deco.set_foreground(QtCore.Qt.blue)
self._deco.set_as_underlined()
self.editor.decorations.append(self._deco)
self.editor.set_mouse_cursor(QtCore.Qt.PointingHandCursor)
else:
self.editor.set_mouse_cursor(QtCore.Qt.IBeamCursor) | Adds a decoration for the word under ``cursor``. | entailment |
def _remove_decoration(self):
"""
Removes the word under cursor's decoration
"""
if self._deco is not None:
self.editor.decorations.remove(self._deco)
self._deco = None | Removes the word under cursor's decoration | entailment |
def date(date):
"""DokuWiki returns dates of `xmlrpclib`/`xmlrpc.client` ``DateTime``
type and the format changes between DokuWiki versions ... This function
convert *date* to a `datetime` object.
"""
date = date.value
return (datetime.strptime(date[:-5], '%Y-%m-%dT%H:%M:%S')
if len(date) == 24
else datetime.strptime(date, '%Y%m%dT%H:%M:%S')) | DokuWiki returns dates of `xmlrpclib`/`xmlrpc.client` ``DateTime``
type and the format changes between DokuWiki versions ... This function
convert *date* to a `datetime` object. | entailment |
def utc2local(date):
"""DokuWiki returns date with a +0000 timezone. This function convert *date*
to the local time.
"""
date_offset = (datetime.now() - datetime.utcnow())
# Python < 2.7 don't have the 'total_seconds' method so calculate it by hand!
date_offset = (date_offset.microseconds +
(date_offset.seconds + date_offset.days * 24 * 3600) * 1e6) / 1e6
date_offset = int(round(date_offset / 60 / 60))
return date + timedelta(hours=date_offset) | DokuWiki returns date with a +0000 timezone. This function convert *date*
to the local time. | entailment |
def parse_response(self, response):
"""parse and store cookie"""
try:
for header in response.msg.get_all("Set-Cookie"):
cookie = header.split(";", 1)[0]
cookieKey, cookieValue = cookie.split("=", 1)
self._cookies[cookieKey] = cookieValue
finally:
return Transport.parse_response(self, response) | parse and store cookie | entailment |
def parse_response(self, response):
"""parse and store cookie"""
try:
for header in response.getheader("set-cookie").split(", "):
# filter 'expire' information
if not header.startswith("D"):
continue
cookie = header.split(";", 1)[0]
cookieKey, cookieValue = cookie.split("=", 1)
self._cookies[cookieKey] = cookieValue
finally:
return Transport.parse_response(self, response) | parse and store cookie | entailment |
def send(self, command, *args, **kwargs):
"""Generic method for executing an XML-RPC *command*. *args* and
*kwargs* are the arguments and parameters needed by the command.
"""
args = list(args)
if kwargs:
args.append(kwargs)
method = self.proxy
for elt in command.split('.'):
method = getattr(method, elt)
try:
return method(*args)
except Fault as err:
if err.faultCode == 121:
return {}
elif err.faultCode == 321:
return []
raise DokuWikiError(err)
except ExpatError as err:
if str(err) != ERR:
raise DokuWikiError(err) | Generic method for executing an XML-RPC *command*. *args* and
*kwargs* are the arguments and parameters needed by the command. | entailment |
def add_acl(self, scope, user, permission):
"""Add an `ACL <https://www.dokuwiki.org/acl>`_ rule that restricts
the page/namespace *scope* to *user* (use *@group* syntax for groups)
with *permission* level. It returns a boolean that indicate if the rule
was correctly added.
"""
return self.send('plugin.acl.addAcl', scope, user, permission) | Add an `ACL <https://www.dokuwiki.org/acl>`_ rule that restricts
the page/namespace *scope* to *user* (use *@group* syntax for groups)
with *permission* level. It returns a boolean that indicate if the rule
was correctly added. | entailment |
def info(self, page, version=None):
"""Returns informations of *page*. Informations of the last version
is returned if *version* is not set.
"""
return (self._dokuwiki.send('wiki.getPageInfoVersion', page, version)
if version is not None
else self._dokuwiki.send('wiki.getPageInfo', page)) | Returns informations of *page*. Informations of the last version
is returned if *version* is not set. | entailment |
def get(self, page, version=None):
"""Returns the content of *page*. The content of the last version is
returned if *version* is not set.
"""
return (self._dokuwiki.send('wiki.getPageVersion', page, version)
if version is not None
else self._dokuwiki.send('wiki.getPage', page)) | Returns the content of *page*. The content of the last version is
returned if *version* is not set. | entailment |
def append(self, page, content, **options):
"""Appends *content* text to *page*.
Valid *options* are:
* *sum*: (str) change summary
* *minor*: (bool) whether this is a minor change
"""
return self._dokuwiki.send('dokuwiki.appendPage', page, content, options) | Appends *content* text to *page*.
Valid *options* are:
* *sum*: (str) change summary
* *minor*: (bool) whether this is a minor change | entailment |
def html(self, page, version=None):
"""Returns HTML content of *page*. The HTML content of the last version
of the page is returned if *version* is not set.
"""
return (self._dokuwiki.send('wiki.getPageHTMLVersion', page, version)
if version is not None
else self._dokuwiki.send('wiki.getPageHTML', page)) | Returns HTML content of *page*. The HTML content of the last version
of the page is returned if *version* is not set. | entailment |
def set(self, page, content, **options):
"""Set/replace the *content* of *page*.
Valid *options* are:
* *sum*: (str) change summary
* *minor*: (bool) whether this is a minor change
"""
try:
return self._dokuwiki.send('wiki.putPage', page, content, options)
except ExpatError as err:
# Sometime the first line of the XML response is blank which raise
# the 'ExpatError' exception although the change has been done. This
# allow to ignore the error.
if str(err) != ERR:
raise DokuWikiError(err) | Set/replace the *content* of *page*.
Valid *options* are:
* *sum*: (str) change summary
* *minor*: (bool) whether this is a minor change | entailment |
def lock(self, page):
"""Locks *page*."""
result = self._dokuwiki.send('dokuwiki.setLocks',
lock=[page], unlock=[])
if result['lockfail']:
raise DokuWikiError('unable to lock page') | Locks *page*. | entailment |
def get(self, media, dirpath=None, filename=None, overwrite=False, b64decode=False):
"""Returns the binary data of *media* or save it to a file. If *dirpath*
is not set the binary data is returned, otherwise the data is saved
to a file. By default, the filename is the name of the media but it can
be changed with *filename* parameter. *overwrite* parameter allow to
overwrite the file if it already exists locally.
"""
import os
data = self._dokuwiki.send('wiki.getAttachment', media)
data = base64.b64decode(data) if b64decode else data.data
if dirpath is None:
return data
if filename is None:
filename = media.replace('/', ':').split(':')[-1]
if not os.path.exists(dirpath):
os.makedirs(dirpath)
filepath = os.path.join(dirpath, filename)
if os.path.exists(filepath) and not overwrite:
raise FileExistsError("[Errno 17] File exists: '%s'" % filepath)
with open(filepath, 'wb') as fhandler:
fhandler.write(data) | Returns the binary data of *media* or save it to a file. If *dirpath*
is not set the binary data is returned, otherwise the data is saved
to a file. By default, the filename is the name of the media but it can
be changed with *filename* parameter. *overwrite* parameter allow to
overwrite the file if it already exists locally. | entailment |
def add(self, media, filepath, overwrite=True):
"""Set *media* from local file *filepath*. *overwrite* parameter specify
if the media must be overwrite if it exists remotely.
"""
with open(filepath, 'rb') as fhandler:
self._dokuwiki.send('wiki.putAttachment', media,
Binary(fhandler.read()), ow=overwrite) | Set *media* from local file *filepath*. *overwrite* parameter specify
if the media must be overwrite if it exists remotely. | entailment |
def set(self, media, _bytes, overwrite=True, b64encode=False):
"""Set *media* from *_bytes*. *overwrite* parameter specify if the media
must be overwrite if it exists remotely.
"""
data = base64.b64encode(_bytes) if b64encode else Binary(_bytes)
self._dokuwiki.send('wiki.putAttachment', media, data, ow=overwrite) | Set *media* from *_bytes*. *overwrite* parameter specify if the media
must be overwrite if it exists remotely. | entailment |
def get(content, keep_order=False):
"""Get dataentry from *content*. *keep_order* indicates whether to
return an ordered dictionnay."""
if keep_order:
from collections import OrderedDict
dataentry = OrderedDict()
else:
dataentry = {}
found = False
for line in content.split('\n'):
if line.strip().startswith('---- dataentry'):
found = True
continue
elif line == '----':
break
elif not found:
continue
line_split = line.split(':')
key = line_split[0].strip()
value = re.sub('#.*$', '', ':'.join(line_split[1:])).strip()
dataentry.setdefault(key, value)
if not found:
raise DokuWikiError('no dataentry found')
return dataentry | Get dataentry from *content*. *keep_order* indicates whether to
return an ordered dictionnay. | entailment |
def gen(name, data):
"""Generate dataentry *name* from *data*."""
return '---- dataentry %s ----\n%s\n----' % (name, '\n'.join(
'%s:%s' % (attr, value) for attr, value in data.items())) | Generate dataentry *name* from *data*. | entailment |
def ignore(content):
"""Remove dataentry from *content*."""
page_content = []
start = False
for line in content.split('\n'):
if line == '----' and not start:
start = True
continue
if start:
page_content.append(line)
return '\n'.join(page_content) if page_content else content | Remove dataentry from *content*. | entailment |
def _draw_messages(self, painter):
"""
Draw messages from all subclass of CheckerMode currently
installed on the editor.
:type painter: QtGui.QPainter
"""
checker_modes = []
for m in self.editor.modes:
if isinstance(m, modes.CheckerMode):
checker_modes.append(m)
for checker_mode in checker_modes:
for msg in checker_mode.messages:
block = msg.block
color = QtGui.QColor(msg.color)
brush = QtGui.QBrush(color)
rect = QtCore.QRect()
rect.setX(self.sizeHint().width() / 4)
rect.setY(block.blockNumber() * self.get_marker_height())
rect.setSize(self.get_marker_size())
painter.fillRect(rect, brush) | Draw messages from all subclass of CheckerMode currently
installed on the editor.
:type painter: QtGui.QPainter | entailment |
def _draw_visible_area(self, painter):
"""
Draw the visible area.
This method does not take folded blocks into account.
:type painter: QtGui.QPainter
"""
if self.editor.visible_blocks:
start = self.editor.visible_blocks[0][-1]
end = self.editor.visible_blocks[-1][-1]
rect = QtCore.QRect()
rect.setX(0)
rect.setY(start.blockNumber() * self.get_marker_height())
rect.setWidth(self.sizeHint().width())
rect.setBottom(end.blockNumber() * self.get_marker_height())
if self.editor.background.lightness() < 128:
c = self.editor.background.darker(150)
else:
c = self.editor.background.darker(110)
c.setAlpha(128)
painter.fillRect(rect, c) | Draw the visible area.
This method does not take folded blocks into account.
:type painter: QtGui.QPainter | entailment |
def paintEvent(self, event):
"""
Pains the messages and the visible area on the panel.
:param event: paint event infos
"""
if self.isVisible():
# fill background
self._background_brush = QtGui.QBrush(self.editor.background)
painter = QtGui.QPainter(self)
painter.fillRect(event.rect(), self._background_brush)
self._draw_messages(painter)
self._draw_visible_area(painter) | Pains the messages and the visible area on the panel.
:param event: paint event infos | entailment |
def get_marker_height(self):
"""
Gets the height of message marker.
"""
return self.editor.viewport().height() / TextHelper(
self.editor).line_count() | Gets the height of message marker. | entailment |
def get_marker_size(self):
"""
Gets the size of a message marker.
:return: QSize
"""
h = self.get_marker_height()
if h < 1:
h = 1
return QtCore.QSize(self.sizeHint().width() / 2, h) | Gets the size of a message marker.
:return: QSize | entailment |
def mimetype_icon(path, fallback=None):
"""
Tries to create an icon from theme using the file mimetype.
E.g.::
return self.mimetype_icon(
path, fallback=':/icons/text-x-python.png')
:param path: file path for which the icon must be created
:param fallback: fallback icon path (qrc or file system)
:returns: QIcon or None if the file mimetype icon could not be found.
"""
mime = mimetypes.guess_type(path)[0]
if mime:
icon = mime.replace('/', '-')
# if system.WINDOWS:
# return icons.file()
if QtGui.QIcon.hasThemeIcon(icon):
icon = QtGui.QIcon.fromTheme(icon)
if not icon.isNull():
return icon
if fallback:
return QtGui.QIcon(fallback)
return QtGui.QIcon.fromTheme('text-x-generic') | Tries to create an icon from theme using the file mimetype.
E.g.::
return self.mimetype_icon(
path, fallback=':/icons/text-x-python.png')
:param path: file path for which the icon must be created
:param fallback: fallback icon path (qrc or file system)
:returns: QIcon or None if the file mimetype icon could not be found. | entailment |
def main(options):
"""A simple connection test to login and print the server time."""
client = Client(server=options.server, username=options.username, password=options.password)
print('Successfully connected to %s' % client.server)
print(client.si.CurrentTime())
client.logout() | A simple connection test to login and print the server time. | entailment |
def marker_for_line(self, line):
"""
Returns the marker that is displayed at the specified line number if
any.
:param line: The marker line.
:return: Marker of None
:rtype: pyqode.core.Marker
"""
block = self.editor.document().findBlockByNumber(line)
try:
return block.userData().messages
except AttributeError:
return [] | Returns the marker that is displayed at the specified line number if
any.
:param line: The marker line.
:return: Marker of None
:rtype: pyqode.core.Marker | entailment |
def main():
"""
pyqode-console main function.
"""
global program, args, ret
print(os.getcwd())
ret = 0
if '--help' in sys.argv or '-h' in sys.argv or len(sys.argv) == 1:
print(__doc__)
else:
program = sys.argv[1]
args = sys.argv[2:]
if args:
ret = subprocess.call([program] + args)
else:
ret = subprocess.call([program])
print('\nProcess terminated with exit code %d' % ret)
prompt = 'Press ENTER to close this window...'
if sys.version_info[0] == 3:
input(prompt)
else:
raw_input(prompt)
sys.exit(ret) | pyqode-console main function. | entailment |
def linkcode_resolve(domain, info):
"""A simple function to find matching source code."""
module_name = info['module']
fullname = info['fullname']
attribute_name = fullname.split('.')[-1]
base_url = 'https://github.com/fmenabe/python-dokuwiki/blob/'
if release.endswith('-dev'):
base_url += 'master/'
else:
base_url += version + '/'
filename = module_name.replace('.', '/') + '.py'
module = sys.modules.get(module_name)
# Get the actual object
try:
actual_object = module
for obj in fullname.split('.'):
parent = actual_object
actual_object = getattr(actual_object, obj)
except AttributeError:
return None
# Fix property methods by using their getter method
if isinstance(actual_object, property):
actual_object = actual_object.fget
# Try to get the linenumber of the object
try:
source, start_line = inspect.getsourcelines(actual_object)
except TypeError:
# If it can not be found, try to find it anyway in the parents its
# source code
parent_source, parent_start_line = inspect.getsourcelines(parent)
for i, line in enumerate(parent_source):
if line.strip().startswith(attribute_name):
start_line = parent_start_line + i
end_line = start_line
break
else:
return None
else:
end_line = start_line + len(source) - 1
line_anchor = '#L%d-L%d' % (start_line, end_line)
return base_url + filename + line_anchor | A simple function to find matching source code. | entailment |
def pick_free_port():
""" Picks a free port """
test_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
test_socket.bind(('127.0.0.1', 0))
free_port = int(test_socket.getsockname()[1])
test_socket.close()
return free_port | Picks a free port | entailment |
def start(self, script, interpreter=sys.executable, args=None,
error_callback=None, reuse=False):
"""
Starts the backend process.
The backend is a python script that starts a
:class:`pyqode.core.backend.JsonServer`. You must write the backend
script so that you can apply your own backend configuration.
The script can be run with a custom interpreter. The default is to use
sys.executable.
.. note:: This restart the backend process if it was previously
running.
:param script: Path to the backend script.
:param interpreter: The python interpreter to use to run the backend
script. If None, sys.executable is used unless we are in a frozen
application (frozen backends do not require an interpreter).
:param args: list of additional command line args to use to start
the backend process.
:param reuse: True to reuse an existing backend process. WARNING: to
use this, your application must have one single server script. If
you're creating an app which supports multiple programming
languages you will need to merge all backend scripts into one
single script, otherwise the wrong script might be picked up).
"""
self._shared = reuse
if reuse and BackendManager.SHARE_COUNT:
self._port = BackendManager.LAST_PORT
self._process = BackendManager.LAST_PROCESS
BackendManager.SHARE_COUNT += 1
else:
if self.running:
self.stop()
self.server_script = script
self.interpreter = interpreter
self.args = args
backend_script = script.replace('.pyc', '.py')
self._port = self.pick_free_port()
if hasattr(sys, "frozen") and not backend_script.endswith('.py'):
# frozen backend script on windows/mac does not need an
# interpreter
program = backend_script
pgm_args = [str(self._port)]
else:
program = interpreter
pgm_args = [backend_script, str(self._port)]
if args:
pgm_args += args
self._process = BackendProcess(self.editor)
if error_callback:
self._process.error.connect(error_callback)
self._process.start(program, pgm_args)
if reuse:
BackendManager.LAST_PROCESS = self._process
BackendManager.LAST_PORT = self._port
BackendManager.SHARE_COUNT += 1
comm('starting backend process: %s %s', program,
' '.join(pgm_args))
self._heartbeat_timer.start() | Starts the backend process.
The backend is a python script that starts a
:class:`pyqode.core.backend.JsonServer`. You must write the backend
script so that you can apply your own backend configuration.
The script can be run with a custom interpreter. The default is to use
sys.executable.
.. note:: This restart the backend process if it was previously
running.
:param script: Path to the backend script.
:param interpreter: The python interpreter to use to run the backend
script. If None, sys.executable is used unless we are in a frozen
application (frozen backends do not require an interpreter).
:param args: list of additional command line args to use to start
the backend process.
:param reuse: True to reuse an existing backend process. WARNING: to
use this, your application must have one single server script. If
you're creating an app which supports multiple programming
languages you will need to merge all backend scripts into one
single script, otherwise the wrong script might be picked up). | entailment |
def stop(self):
"""
Stops the backend process.
"""
if self._process is None:
return
if self._shared:
BackendManager.SHARE_COUNT -= 1
if BackendManager.SHARE_COUNT:
return
comm('stopping backend process')
# close all sockets
for s in self._sockets:
s._callback = None
s.close()
self._sockets[:] = []
# prevent crash logs from being written if we are busy killing
# the process
self._process._prevent_logs = True
while self._process.state() != self._process.NotRunning:
self._process.waitForFinished(1)
if sys.platform == 'win32':
# Console applications on Windows that do not run an event
# loop, or whose event loop does not handle the WM_CLOSE
# message, can only be terminated by calling kill().
self._process.kill()
else:
self._process.terminate()
self._process._prevent_logs = False
self._heartbeat_timer.stop()
comm('backend process terminated') | Stops the backend process. | entailment |
def send_request(self, worker_class_or_function, args, on_receive=None):
"""
Requests some work to be done by the backend. You can get notified of
the work results by passing a callback (on_receive).
:param worker_class_or_function: Worker class or function
:param args: worker args, any Json serializable objects
:param on_receive: an optional callback executed when we receive the
worker's results. The callback will be called with one arguments:
the results of the worker (object)
:raise: backend.NotRunning if the backend process is not running.
"""
if not self.running:
try:
# try to restart the backend if it crashed.
self.start(self.server_script, interpreter=self.interpreter,
args=self.args)
except AttributeError:
pass # not started yet
finally:
# caller should try again, later
raise NotRunning()
else:
comm('sending request, worker=%r' % worker_class_or_function)
# create a socket, the request will be send as soon as the socket
# has connected
socket = JsonTcpClient(
self.editor, self._port, worker_class_or_function, args,
on_receive=on_receive)
socket.finished.connect(self._rm_socket)
self._sockets.append(socket)
# restart heartbeat timer
self._heartbeat_timer.start() | Requests some work to be done by the backend. You can get notified of
the work results by passing a callback (on_receive).
:param worker_class_or_function: Worker class or function
:param args: worker args, any Json serializable objects
:param on_receive: an optional callback executed when we receive the
worker's results. The callback will be called with one arguments:
the results of the worker (object)
:raise: backend.NotRunning if the backend process is not running. | entailment |
def running(self):
"""
Tells whether the backend process is running.
:return: True if the process is running, otherwise False
"""
try:
return (self._process is not None and
self._process.state() != self._process.NotRunning)
except RuntimeError:
return False | Tells whether the backend process is running.
:return: True if the process is running, otherwise False | entailment |
def remove(self, filename):
"""
Remove a file path from the list of recent files.
:param filename: Path of the file to remove
"""
files = self.get_value('list', [])
files.remove(filename)
self.set_value('list', files)
self.updated.emit() | Remove a file path from the list of recent files.
:param filename: Path of the file to remove | entailment |
def get_value(self, key, default=None):
"""
Reads value from QSettings
:param key: value key
:param default: default value.
:return: value
"""
def unique(seq, idfun=None):
if idfun is None:
def idfun(x):
return x
# order preserving
seen = {}
result = []
for item in seq:
marker = idfun(item)
if marker in seen:
continue
seen[marker] = 1
result.append(item)
return result
lst = self._settings.value('recent_files/%s' % key, default)
# emtpy list
if lst is None:
lst = []
# single file
if isinstance(lst, str):
lst = [lst]
return unique([os.path.normpath(pth) for pth in lst]) | Reads value from QSettings
:param key: value key
:param default: default value.
:return: value | entailment |
def set_value(self, key, value):
"""
Set the recent files value in QSettings.
:param key: value key
:param value: new value
"""
if value is None:
value = []
value = [os.path.normpath(pth) for pth in value]
self._settings.setValue('recent_files/%s' % key, value) | Set the recent files value in QSettings.
:param key: value key
:param value: new value | entailment |
def get_recent_files(self):
"""
Gets the list of recent files. (files that do not exists anymore
are automatically filtered)
"""
ret_val = []
files = self.get_value('list', [])
# filter files, remove files that do not exist anymore
for file in files:
if file is not None and os.path.exists(file):
if os.path.ismount(file) and \
sys.platform == 'win32' and not file.endswith('\\'):
file += '\\'
if file not in ret_val:
ret_val.append(file)
return ret_val | Gets the list of recent files. (files that do not exists anymore
are automatically filtered) | entailment |
def open_file(self, file):
"""
Adds a file to the list (and move it to the top of the list if the
file already exists)
:param file: file path to add the list of recent files.
"""
files = self.get_recent_files()
try:
files.remove(file)
except ValueError:
pass
files.insert(0, file)
# discard old files
del files[self.max_recent_files:]
self.set_value('list', files)
self.updated.emit() | Adds a file to the list (and move it to the top of the list if the
file already exists)
:param file: file path to add the list of recent files. | entailment |
def update_actions(self):
"""
Updates the list of actions.
"""
self.clear()
self.recent_files_actions[:] = []
for file in self.manager.get_recent_files():
action = QtWidgets.QAction(self)
action.setText(os.path.split(file)[1])
action.setToolTip(file)
action.setStatusTip(file)
action.setData(file)
action.setIcon(self.icon_provider.icon(QtCore.QFileInfo(file)))
action.triggered.connect(self._on_action_triggered)
self.addAction(action)
self.recent_files_actions.append(action)
self.addSeparator()
action_clear = QtWidgets.QAction(_('Clear list'), self)
action_clear.triggered.connect(self.clear_recent_files)
if isinstance(self.clear_icon, QtGui.QIcon):
action_clear.setIcon(self.clear_icon)
elif self.clear_icon:
theme = ''
if len(self.clear_icon) == 2:
theme, path = self.clear_icon
else:
path = self.clear_icon
icons.icon(theme, path, 'fa.times-circle')
self.addAction(action_clear) | Updates the list of actions. | entailment |
def clear_recent_files(self):
""" Clear recent files and menu. """
self.manager.clear()
self.update_actions()
self.clear_requested.emit() | Clear recent files and menu. | entailment |
def _on_action_triggered(self):
"""
Emits open_requested when a recent file action has been triggered.
"""
action = self.sender()
assert isinstance(action, QtWidgets.QAction)
path = action.data()
self.open_requested.emit(path)
self.update_actions() | Emits open_requested when a recent file action has been triggered. | entailment |
def append(self, panel, position=Panel.Position.LEFT):
"""
Installs a panel on the editor.
:param panel: Panel to install
:param position: Position where the panel must be installed.
:return: The installed panel
"""
assert panel is not None
pos_to_string = {
Panel.Position.BOTTOM: 'bottom',
Panel.Position.LEFT: 'left',
Panel.Position.RIGHT: 'right',
Panel.Position.TOP: 'top'
}
_logger().log(5, 'adding panel %s at %r', panel.name,
pos_to_string[position])
panel.order_in_zone = len(self._panels[position])
self._panels[position][panel.name] = panel
panel.position = position
panel.on_install(self.editor)
_logger().log(5, 'panel %s installed', panel.name)
return panel | Installs a panel on the editor.
:param panel: Panel to install
:param position: Position where the panel must be installed.
:return: The installed panel | entailment |
def remove(self, name_or_klass):
"""
Removes the specified panel.
:param name_or_klass: Name or class of the panel to remove.
:return: The removed panel
"""
_logger().log(5, 'removing panel %r', name_or_klass)
panel = self.get(name_or_klass)
panel.on_uninstall()
panel.hide()
panel.setParent(None)
return self._panels[panel.position].pop(panel.name, None) | Removes the specified panel.
:param name_or_klass: Name or class of the panel to remove.
:return: The removed panel | entailment |
def get(self, name_or_klass):
"""
Gets a specific panel instance.
:param name_or_klass: Name or class of the panel to retrieve.
:return: The specified panel instance.
"""
if not isinstance(name_or_klass, str):
name_or_klass = name_or_klass.__name__
for zone in range(4):
try:
panel = self._panels[zone][name_or_klass]
except KeyError:
pass
else:
return panel
raise KeyError(name_or_klass) | Gets a specific panel instance.
:param name_or_klass: Name or class of the panel to retrieve.
:return: The specified panel instance. | entailment |
def refresh(self):
""" Refreshes the editor panels (resize and update margins) """
_logger().log(5, 'refresh_panels')
self.resize()
self._update(self.editor.contentsRect(), 0,
force_update_margins=True) | Refreshes the editor panels (resize and update margins) | entailment |
def _update(self, rect, delta_y, force_update_margins=False):
""" Updates panels """
helper = TextHelper(self.editor)
if not self:
return
for zones_id, zone in self._panels.items():
if zones_id == Panel.Position.TOP or \
zones_id == Panel.Position.BOTTOM:
continue
panels = list(zone.values())
for panel in panels:
if panel.scrollable and delta_y:
panel.scroll(0, delta_y)
line, col = helper.cursor_position()
oline, ocol = self._cached_cursor_pos
if line != oline or col != ocol or panel.scrollable:
panel.update(0, rect.y(), panel.width(), rect.height())
self._cached_cursor_pos = helper.cursor_position()
if (rect.contains(self.editor.viewport().rect()) or
force_update_margins):
self._update_viewport_margins() | Updates panels | entailment |
def icon(theme_name='', path='', qta_name='', qta_options=None, use_qta=None):
"""
Creates an icon from qtawesome, from theme or from path.
:param theme_name: icon name in the current theme (GNU/Linux only)
:param path: path of the icon (from file system or qrc)
:param qta_name: icon name in qtawesome
:param qta_options: the qtawesome options to use for controlling icon
rendering. If None, QTA_OPTIONS are used.
:param use_qta: True to use qtawesome, False to use icon from theme/path.
None to use the global setting: USE_QTAWESOME.
:returns: QtGui.QIcon
"""
ret_val = None
if use_qta is None:
use_qta = USE_QTAWESOME
if qta_options is None:
qta_options = QTA_OPTIONS
if qta is not None and use_qta is True:
ret_val = qta.icon(qta_name, **qta_options)
else:
if theme_name and path:
ret_val = QtGui.QIcon.fromTheme(theme_name, QtGui.QIcon(path))
elif theme_name:
ret_val = QtGui.QIcon.fromTheme(theme_name)
elif path:
ret_val = QtGui.QIcon(path)
return ret_val | Creates an icon from qtawesome, from theme or from path.
:param theme_name: icon name in the current theme (GNU/Linux only)
:param path: path of the icon (from file system or qrc)
:param qta_name: icon name in qtawesome
:param qta_options: the qtawesome options to use for controlling icon
rendering. If None, QTA_OPTIONS are used.
:param use_qta: True to use qtawesome, False to use icon from theme/path.
None to use the global setting: USE_QTAWESOME.
:returns: QtGui.QIcon | entailment |
def set_outline(self, color):
"""
Uses an outline rectangle.
:param color: Color of the outline rect
:type color: QtGui.QColor
"""
self.format.setProperty(QtGui.QTextFormat.OutlinePen,
QtGui.QPen(color)) | Uses an outline rectangle.
:param color: Color of the outline rect
:type color: QtGui.QColor | entailment |
def set_full_width(self, flag=True, clear=True):
"""
Enables FullWidthSelection (the selection does not stops at after the
character instead it goes up to the right side of the widget).
:param flag: True to use full width selection.
:type flag: bool
:param clear: True to clear any previous selection. Default is True.
:type clear: bool
"""
if clear:
self.cursor.clearSelection()
self.format.setProperty(QtGui.QTextFormat.FullWidthSelection, flag) | Enables FullWidthSelection (the selection does not stops at after the
character instead it goes up to the right side of the widget).
:param flag: True to use full width selection.
:type flag: bool
:param clear: True to clear any previous selection. Default is True.
:type clear: bool | entailment |
def compile(self, script, bare=False):
'''compile a CoffeeScript code to a JavaScript code.
if bare is True, then compile the JavaScript without the top-level
function safety wrapper (like the coffee command).
'''
if not hasattr(self, '_context'):
self._context = self._runtime.compile(self._compiler_script)
return self._context.call(
"CoffeeScript.compile", script, {'bare': bare}) | compile a CoffeeScript code to a JavaScript code.
if bare is True, then compile the JavaScript without the top-level
function safety wrapper (like the coffee command). | entailment |
def compile_file(self, filename, encoding="utf-8", bare=False):
'''compile a CoffeeScript script file to a JavaScript code.
filename can be a list or tuple of filenames,
then contents of files are concatenated with line feeds.
if bare is True, then compile the JavaScript without the top-level
function safety wrapper (like the coffee command).
'''
if isinstance(filename, _BaseString):
filename = [filename]
scripts = []
for f in filename:
with io.open(f, encoding=encoding) as fp:
scripts.append(fp.read())
return self.compile('\n\n'.join(scripts), bare=bare) | compile a CoffeeScript script file to a JavaScript code.
filename can be a list or tuple of filenames,
then contents of files are concatenated with line feeds.
if bare is True, then compile the JavaScript without the top-level
function safety wrapper (like the coffee command). | entailment |
def setup_actions(self):
""" Connects slots to signals """
self.actionOpen.triggered.connect(self.on_open)
self.actionNew.triggered.connect(self.on_new)
self.actionSave.triggered.connect(self.on_save)
self.actionSave_as.triggered.connect(self.on_save_as)
self.actionQuit.triggered.connect(QtWidgets.QApplication.instance().quit)
self.tabWidget.current_changed.connect(
self.on_current_tab_changed)
self.actionAbout.triggered.connect(self.on_about) | Connects slots to signals | entailment |
def setup_recent_files_menu(self):
""" Setup the recent files menu and manager """
self.recent_files_manager = widgets.RecentFilesManager(
'pyQode', 'notepad')
self.menu_recents = widgets.MenuRecentFiles(
self.menuFile, title='Recents',
recent_files_manager=self.recent_files_manager)
self.menu_recents.open_requested.connect(self.open_file)
self.menuFile.insertMenu(self.actionSave, self.menu_recents)
self.menuFile.insertSeparator(self.actionSave) | Setup the recent files menu and manager | entailment |
def setup_mimetypes(self):
""" Setup additional mime types. """
# setup some specific mimetypes
mimetypes.add_type('text/xml', '.ui') # qt designer forms forms
mimetypes.add_type('text/x-rst', '.rst') # rst docs
mimetypes.add_type('text/x-cython', '.pyx') # cython impl files
mimetypes.add_type('text/x-cython', '.pxd') # cython def files
mimetypes.add_type('text/x-python', '.py')
mimetypes.add_type('text/x-python', '.pyw')
mimetypes.add_type('text/x-c', '.c')
mimetypes.add_type('text/x-c', '.h')
mimetypes.add_type('text/x-c++hdr', '.hpp')
mimetypes.add_type('text/x-c++src', '.cpp')
mimetypes.add_type('text/x-c++src', '.cxx')
# cobol files
for ext in ['.cbl', '.cob', '.cpy']:
mimetypes.add_type('text/x-cobol', ext)
mimetypes.add_type('text/x-cobol', ext.upper()) | Setup additional mime types. | entailment |
def open_file(self, path):
"""
Creates a new GenericCodeEdit, opens the requested file and adds it
to the tab widget.
:param path: Path of the file to open
"""
if path:
editor = self.tabWidget.open_document(path)
editor.cursorPositionChanged.connect(
self.on_cursor_pos_changed)
self.recent_files_manager.open_file(path)
self.menu_recents.update_actions() | Creates a new GenericCodeEdit, opens the requested file and adds it
to the tab widget.
:param path: Path of the file to open | entailment |
def on_new(self):
"""
Add a new empty code editor to the tab widget
"""
editor = self.tabWidget.create_new_document()
editor.cursorPositionChanged.connect(self.on_cursor_pos_changed)
self.refresh_color_scheme() | Add a new empty code editor to the tab widget | entailment |
def on_open(self):
"""
Shows an open file dialog and open the file if the dialog was
accepted.
"""
filename, filter = QtWidgets.QFileDialog.getOpenFileName(
self, _('Open'))
if filename:
self.open_file(filename) | Shows an open file dialog and open the file if the dialog was
accepted. | entailment |
def on_save_as(self):
"""
Save the current editor document as.
"""
self.tabWidget.save_current_as()
self._update_status_bar(self.tabWidget.current_widget()) | Save the current editor document as. | entailment |
def tab_under_menu(self):
"""
Returns the tab that sits under the context menu.
:return: QWidget
"""
if self._menu_pos:
return self.tabBar().tabAt(self._menu_pos)
else:
return self.currentIndex() | Returns the tab that sits under the context menu.
:return: QWidget | entailment |
def close_others(self):
"""
Closes every editors tabs except the current one.
"""
current_widget = self.widget(self.tab_under_menu())
if self._try_close_dirty_tabs(exept=current_widget):
i = 0
while self.count() > 1:
widget = self.widget(i)
if widget != current_widget:
self.remove_tab(i)
else:
i = 1 | Closes every editors tabs except the current one. | entailment |
def close_left(self):
"""
Closes every editors tabs on the left of the current one.
"""
current_widget = self.widget(self.tab_under_menu())
index = self.indexOf(current_widget)
if self._try_close_dirty_tabs(tab_range=range(index)):
while True:
widget = self.widget(0)
if widget != current_widget:
self.remove_tab(0)
else:
break | Closes every editors tabs on the left of the current one. | entailment |
def close_right(self):
"""
Closes every editors tabs on the left of the current one.
"""
current_widget = self.widget(self.tab_under_menu())
index = self.indexOf(current_widget)
if self._try_close_dirty_tabs(tab_range=range(index + 1, self.count())):
while True:
widget = self.widget(self.count() - 1)
if widget != current_widget:
self.remove_tab(self.count() - 1)
else:
break | Closes every editors tabs on the left of the current one. | entailment |
def close_all(self):
"""
Closes all editors
"""
if self._try_close_dirty_tabs():
while self.count():
widget = self.widget(0)
self.remove_tab(0)
self.tab_closed.emit(widget)
return True
return False | Closes all editors | entailment |
def _collect_dirty_tabs(self, skip=None, tab_range=None):
"""
Collects the list of dirty tabs
:param skip: Tab to skip (used for close_others).
"""
widgets = []
filenames = []
if tab_range is None:
tab_range = range(self.count())
for i in tab_range:
widget = self.widget(i)
try:
if widget.dirty and widget != skip:
widgets.append(widget)
if widget.file.path:
filenames.append(widget.file.path)
else:
filenames.append(widget.documentTitle())
except AttributeError:
pass
return widgets, filenames | Collects the list of dirty tabs
:param skip: Tab to skip (used for close_others). | entailment |
def _close_widget(widget):
"""
Closes the given widgets and handles cases where the widget has been
clone or is a clone of another widget
"""
if widget is None:
return
try:
widget.document().setParent(None)
widget.syntax_highlighter.setParent(None)
except AttributeError:
pass # not a QPlainTextEdit subclass
# handled cloned widgets
clones = []
if hasattr(widget, 'original') and widget.original:
# cloned widget needs to be removed from the original
widget.original.clones.remove(widget)
try:
widget.setDocument(None)
except AttributeError:
# not a QTextEdit/QPlainTextEdit
pass
elif hasattr(widget, 'clones'):
clones = widget.clones
try:
# only clear current editor if it does not have any other clones
widget.close(clear=len(clones) == 0)
except (AttributeError, TypeError):
# not a CodeEdit
widget.close()
return clones | Closes the given widgets and handles cases where the widget has been
clone or is a clone of another widget | entailment |
def remove_tab(self, index):
"""
Overrides removeTab to emit tab_closed and last_tab_closed signals.
:param index: index of the tab to remove.
"""
widget = self.widget(index)
try:
document = widget.document()
except AttributeError:
document = None # not a QPlainTextEdit
clones = self._close_widget(widget)
self.tab_closed.emit(widget)
self.removeTab(index)
self._restore_original(clones)
widget._original_tab_widget._tabs.remove(widget)
if self.count() == 0:
self.last_tab_closed.emit()
if SplittableTabWidget.tab_under_menu == widget:
SplittableTabWidget.tab_under_menu = None
if not clones:
widget.setParent(None)
else:
try:
clones[0].syntax_highlighter.setDocument(document)
except AttributeError:
pass | Overrides removeTab to emit tab_closed and last_tab_closed signals.
:param index: index of the tab to remove. | entailment |
def _on_split_requested(self):
"""
Emits the split requested signal with the desired orientation.
"""
orientation = self.sender().text()
widget = self.widget(self.tab_under_menu())
if 'horizontally' in orientation:
self.split_requested.emit(
widget, QtCore.Qt.Horizontal)
else:
self.split_requested.emit(
widget, QtCore.Qt.Vertical) | Emits the split requested signal with the desired orientation. | entailment |
def addTab(self, tab, *args):
"""
Adds a tab to the tab widget, this function set the parent_tab_widget
attribute on the tab instance.
"""
tab.parent_tab_widget = self
super(BaseTabWidget, self).addTab(tab, *args) | Adds a tab to the tab widget, this function set the parent_tab_widget
attribute on the tab instance. | entailment |
def add_context_action(self, action):
"""
Adds a custom context menu action
:param action: action to add.
"""
self.main_tab_widget.context_actions.append(action)
for child_splitter in self.child_splitters:
child_splitter.add_context_action(action) | Adds a custom context menu action
:param action: action to add. | entailment |
def add_tab(self, tab, title='', icon=None):
"""
Adds a tab to main tab widget.
:param tab: Widget to add as a new tab of the main tab widget.
:param title: Tab title
:param icon: Tab icon
"""
if icon:
tab._icon = icon
if not hasattr(tab, 'clones'):
tab.clones = []
if not hasattr(tab, 'original'):
tab.original = None
if icon:
self.main_tab_widget.addTab(tab, icon, title)
else:
self.main_tab_widget.addTab(tab, title)
self.main_tab_widget.setCurrentIndex(
self.main_tab_widget.indexOf(tab))
self.main_tab_widget.show()
tab._uuid = self._uuid
try:
scroll_bar = tab.horizontalScrollBar()
except AttributeError:
# not a QPlainTextEdit class
pass
else:
scroll_bar.setValue(0)
tab.setFocus()
tab._original_tab_widget = self
self._tabs.append(tab)
self._on_focus_changed(None, tab) | Adds a tab to main tab widget.
:param tab: Widget to add as a new tab of the main tab widget.
:param title: Tab title
:param icon: Tab icon | entailment |
def split(self, widget, orientation):
"""
Split the the current widget in new SplittableTabWidget.
:param widget: widget to split
:param orientation: orientation of the splitter
:return: the new splitter
"""
if widget.original:
base = widget.original
else:
base = widget
clone = base.split()
if not clone:
return
if orientation == int(QtCore.Qt.Horizontal):
orientation = QtCore.Qt.Horizontal
else:
orientation = QtCore.Qt.Vertical
self.setOrientation(orientation)
splitter = self._make_splitter()
splitter.show()
self.addWidget(splitter)
self.child_splitters.append(splitter)
if clone not in base.clones:
# code editors maintain the list of clones internally but some
# other widgets (user widgets) might not.
base.clones.append(clone)
clone.original = base
splitter._parent_splitter = self
splitter.last_tab_closed.connect(self._on_last_child_tab_closed)
splitter.tab_detached.connect(self.tab_detached.emit)
if hasattr(base, '_icon'):
icon = base._icon
else:
icon = None
# same group of tab splitter (user might have a group for editors and
# another group for consoles or whatever).
splitter._uuid = self._uuid
splitter.add_tab(clone, title=self.main_tab_widget.tabText(
self.main_tab_widget.indexOf(widget)), icon=icon)
self.setSizes([1 for i in range(self.count())])
return splitter | Split the the current widget in new SplittableTabWidget.
:param widget: widget to split
:param orientation: orientation of the splitter
:return: the new splitter | entailment |
def has_children(self):
"""
Checks if there are children tab widgets.
:return: True if there is at least one tab in the children tab widget.
"""
for splitter in self.child_splitters:
if splitter.has_children():
return splitter
return self.main_tab_widget.count() != 0 | Checks if there are children tab widgets.
:return: True if there is at least one tab in the children tab widget. | entailment |
def widgets(self, include_clones=False):
"""
Recursively gets the list of widgets.
:param include_clones: True to retrieve all tabs, including clones,
otherwise only original widgets are returned.
"""
widgets = []
for i in range(self.main_tab_widget.count()):
widget = self.main_tab_widget.widget(i)
try:
if widget.original is None or include_clones:
widgets.append(widget)
except AttributeError:
pass
for child in self.child_splitters:
widgets += child.widgets(include_clones=include_clones)
return widgets | Recursively gets the list of widgets.
:param include_clones: True to retrieve all tabs, including clones,
otherwise only original widgets are returned. | entailment |
def count(self):
"""
Returns the number of widgets currently displayed (takes child splits
into account).
"""
c = self.main_tab_widget.count()
for child in self.child_splitters:
c += child.count()
return c | Returns the number of widgets currently displayed (takes child splits
into account). | entailment |
def get_filter(cls, mimetype):
"""
Returns a filter string for the file dialog. The filter is based
on the mime type.
:param mimetype: path from which the filter must be derived.
:return: Filter string
"""
filters = ' '.join(
['*%s' % ext for ext in mimetypes.guess_all_extensions(mimetype)])
return '%s (%s)' % (mimetype, filters) | Returns a filter string for the file dialog. The filter is based
on the mime type.
:param mimetype: path from which the filter must be derived.
:return: Filter string | entailment |
def addTab(self, widget, *args):
"""
Re-implements addTab to connect to the dirty changed signal and setup
some helper attributes.
:param widget: widget to add
:param args: optional addtional arguments (name and/or icon).
"""
widget.dirty_changed.connect(self._on_dirty_changed)
super(CodeEditTabWidget, self).addTab(widget, *args) | Re-implements addTab to connect to the dirty changed signal and setup
some helper attributes.
:param widget: widget to add
:param args: optional addtional arguments (name and/or icon). | entailment |
def _on_dirty_changed(self, dirty):
"""
Adds a star in front of a dirtt tab and emits dirty_changed.
"""
widget = self.sender()
if isinstance(widget, DraggableTabBar):
return
parent = widget.parent_tab_widget
index = parent.indexOf(widget)
title = parent.tabText(index)
title = title.replace('* ', '')
if dirty:
parent.setTabText(index, "* " + title)
else:
parent.setTabText(index, title)
parent.dirty_changed.emit(dirty) | Adds a star in front of a dirtt tab and emits dirty_changed. | entailment |
def _ask_path(cls, editor):
"""
Shows a QFileDialog and ask for a save filename.
:return: save filename
"""
try:
filter = cls.get_filter(editor.mimetypes[0])
except IndexError:
filter = _('All files (*)')
return QtWidgets.QFileDialog.getSaveFileName(
editor, _('Save file as'), cls.default_directory, filter) | Shows a QFileDialog and ask for a save filename.
:return: save filename | entailment |
def save_widget(cls, editor):
"""
Implements SplittableTabWidget.save_widget to actually save the
code editor widget.
If the editor.file.path is None or empty or the file does not exist,
a save as dialog is shown (save as).
:param editor: editor widget to save.
:return: False if there was a problem saving the editor (e.g. the save
as dialog has been canceled by the user, or a permission error,...)
"""
if editor.original:
editor = editor.original
if editor.file.path is None or not os.path.exists(editor.file.path):
# save as
path, filter = cls._ask_path(editor)
if not path:
return False
if not os.path.splitext(path)[1]:
if len(editor.mimetypes):
path += mimetypes.guess_extension(editor.mimetypes[0])
try:
_logger().debug('saving %r as %r', editor.file._old_path, path)
except AttributeError:
_logger().debug('saving %r as %r', editor.file.path, path)
editor.file._path = path
else:
path = editor.file.path
try:
editor.file.save(path)
except Exception as e:
QtWidgets.QMessageBox.warning(editor, "Failed to save file", 'Failed to save %r.\n\nError="%s"' %
(path, e))
else:
tw = editor.parent_tab_widget
text = tw.tabText(tw.indexOf(editor)).replace('*', '')
tw.setTabText(tw.indexOf(editor), text)
for clone in [editor] + editor.clones:
if clone != editor:
tw = clone.parent_tab_widget
tw.setTabText(tw.indexOf(clone), text)
return True | Implements SplittableTabWidget.save_widget to actually save the
code editor widget.
If the editor.file.path is None or empty or the file does not exist,
a save as dialog is shown (save as).
:param editor: editor widget to save.
:return: False if there was a problem saving the editor (e.g. the save
as dialog has been canceled by the user, or a permission error,...) | entailment |
def register_code_edit(cls, code_edit_class):
"""
Register an additional code edit **class**
.. warning: This method expect a class, not an instance!
:param code_edit_class: code edit class to register.
"""
if not inspect.isclass(code_edit_class):
raise TypeError('must be a class, not an instance.')
for mimetype in code_edit_class.mimetypes:
if mimetype in cls.editors:
_logger().warn('editor for mimetype already registered, '
'skipping')
cls.editors[mimetype] = code_edit_class
_logger().log(5, 'registered editors: %r', cls.editors) | Register an additional code edit **class**
.. warning: This method expect a class, not an instance!
:param code_edit_class: code edit class to register. | entailment |
def save_current_as(self):
"""
Save current widget as.
"""
if not self.current_widget():
return
mem = self.current_widget().file.path
self.current_widget().file._path = None
self.current_widget().file._old_path = mem
CodeEditTabWidget.default_directory = os.path.dirname(mem)
widget = self.current_widget()
try:
success = self.main_tab_widget.save_widget(widget)
except Exception as e:
QtWidgets.QMessageBox.warning(
self, _('Failed to save file as'),
_('Failed to save file as %s\nError=%s') % (
widget.file.path, str(e)))
widget.file._path = mem
else:
if not success:
widget.file._path = mem
else:
CodeEditTabWidget.default_directory = os.path.expanduser('~')
self.document_saved.emit(widget.file.path, '')
# rename tab
tw = widget.parent_tab_widget
tw.setTabText(tw.indexOf(widget),
os.path.split(widget.file.path)[1])
return self.current_widget().file.path | Save current widget as. | entailment |
def save_current(self):
"""
Save current editor. If the editor.file.path is None, a save as dialog
will be shown.
"""
if self.current_widget() is not None:
editor = self.current_widget()
self._save(editor) | Save current editor. If the editor.file.path is None, a save as dialog
will be shown. | entailment |
def save_all(self):
"""
Save all editors.
"""
for w in self.widgets():
try:
self._save(w)
except OSError:
_logger().exception('failed to save %s', w.file.path) | Save all editors. | entailment |
def _create_code_edit(self, mimetype, *args, **kwargs):
"""
Create a code edit instance based on the mimetype of the file to
open/create.
:type mimetype: mime type
:param args: Positional arguments that must be forwarded to the editor
widget constructor.
:param kwargs: Keyworded arguments that must be forwarded to the editor
widget constructor.
:return: Code editor widget instance.
"""
if mimetype in self.editors.keys():
return self.editors[mimetype](
*args, parent=self.main_tab_widget, **kwargs)
editor = self.fallback_editor(*args, parent=self.main_tab_widget,
**kwargs)
return editor | Create a code edit instance based on the mimetype of the file to
open/create.
:type mimetype: mime type
:param args: Positional arguments that must be forwarded to the editor
widget constructor.
:param kwargs: Keyworded arguments that must be forwarded to the editor
widget constructor.
:return: Code editor widget instance. | entailment |
def create_new_document(self, base_name='New Document',
extension='.txt', preferred_eol=0,
autodetect_eol=True, **kwargs):
"""
Creates a new document.
The document name will be ``base_name + count + extension``
:param base_name: Base name of the document. An int will be appended.
:param extension: Document extension (dotted)
:param args: Positional arguments that must be forwarded to the editor
widget constructor.
:param preferred_eol: Preferred EOL convention. This setting will be
used for saving the document unless autodetect_eol is True.
:param autodetect_eol: If true, automatically detects file EOL and
use it instead of the preferred EOL when saving files.
:param kwargs: Keyworded arguments that must be forwarded to the editor
widget constructor.
:return: Code editor widget instance.
"""
SplittableCodeEditTabWidget._new_count += 1
name = '%s%d%s' % (base_name, self._new_count, extension)
tab = self._create_code_edit(
self.guess_mimetype(name), **kwargs)
self.editor_created.emit(tab)
tab.file.autodetect_eol = autodetect_eol
tab.file.preferred_eol = preferred_eol
tab.setDocumentTitle(name)
self.add_tab(tab, title=name, icon=self._icon(name))
self.document_opened.emit(tab)
return tab | Creates a new document.
The document name will be ``base_name + count + extension``
:param base_name: Base name of the document. An int will be appended.
:param extension: Document extension (dotted)
:param args: Positional arguments that must be forwarded to the editor
widget constructor.
:param preferred_eol: Preferred EOL convention. This setting will be
used for saving the document unless autodetect_eol is True.
:param autodetect_eol: If true, automatically detects file EOL and
use it instead of the preferred EOL when saving files.
:param kwargs: Keyworded arguments that must be forwarded to the editor
widget constructor.
:return: Code editor widget instance. | entailment |
def open_document(self, path, encoding=None, replace_tabs_by_spaces=True,
clean_trailing_whitespaces=True, safe_save=True,
restore_cursor_position=True, preferred_eol=0,
autodetect_eol=True, show_whitespaces=False, **kwargs):
"""
Opens a document.
:param path: Path of the document to open
:param encoding: The encoding to use to open the file. Default is
locale.getpreferredencoding().
:param replace_tabs_by_spaces: Enable/Disable replace tabs by spaces.
Default is true.
:param clean_trailing_whitespaces: Enable/Disable clean trailing
whitespaces (on save). Default is True.
:param safe_save: If True, the file is saved to a temporary file first.
If the save went fine, the temporary file is renamed to the final
filename.
:param restore_cursor_position: If true, last cursor position will be
restored. Default is True.
:param preferred_eol: Preferred EOL convention. This setting will be
used for saving the document unless autodetect_eol is True.
:param autodetect_eol: If true, automatically detects file EOL and
use it instead of the preferred EOL when saving files.
:param show_whitespaces: True to show white spaces.
:param kwargs: addtional keyword args to pass to the widget
constructor.
:return: The created code editor
"""
original_path = os.path.normpath(path)
path = os.path.normcase(original_path)
paths = []
widgets = []
for w in self.widgets(include_clones=False):
if os.path.exists(w.file.path):
# skip new docs
widgets.append(w)
paths.append(os.path.normcase(w.file.path))
if path in paths:
i = paths.index(path)
w = widgets[i]
tw = w.parent_tab_widget
tw.setCurrentIndex(tw.indexOf(w))
return w
else:
assert os.path.exists(original_path)
name = os.path.split(original_path)[1]
use_parent_dir = False
for tab in self.widgets():
title = QtCore.QFileInfo(tab.file.path).fileName()
if title == name:
tw = tab.parent_tab_widget
new_name = os.path.join(os.path.split(os.path.dirname(
tab.file.path))[1], title)
tw.setTabText(tw.indexOf(tab), new_name)
use_parent_dir = True
if use_parent_dir:
name = os.path.join(
os.path.split(os.path.dirname(path))[1], name)
use_parent_dir = False
tab = self._create_code_edit(self.guess_mimetype(path), **kwargs)
self.editor_created.emit(tab)
tab.open_parameters = {
'encoding': encoding,
'replace_tabs_by_spaces': replace_tabs_by_spaces,
'clean_trailing_whitespaces': clean_trailing_whitespaces,
'safe_save': safe_save,
'restore_cursor_position': restore_cursor_position,
'preferred_eol': preferred_eol,
'autodetect_eol': autodetect_eol,
'show_whitespaces': show_whitespaces,
'kwargs': kwargs
}
tab.file.clean_trailing_whitespaces = clean_trailing_whitespaces
tab.file.safe_save = safe_save
tab.file.restore_cursor = restore_cursor_position
tab.file.replace_tabs_by_spaces = replace_tabs_by_spaces
tab.file.autodetect_eol = autodetect_eol
tab.file.preferred_eol = preferred_eol
tab.show_whitespaces = show_whitespaces
try:
tab.file.open(original_path, encoding=encoding)
except Exception as e:
_logger().exception('exception while opening file')
tab.close()
tab.setParent(None)
tab.deleteLater()
raise e
else:
tab.setDocumentTitle(name)
tab.file._path = original_path
icon = self._icon(path)
self.add_tab(tab, title=name, icon=icon)
self.document_opened.emit(tab)
for action in self.closed_tabs_menu.actions():
if action.toolTip() == original_path:
self.closed_tabs_menu.removeAction(action)
break
self.closed_tabs_history_btn.setEnabled(
len(self.closed_tabs_menu.actions()) > 0)
return tab | Opens a document.
:param path: Path of the document to open
:param encoding: The encoding to use to open the file. Default is
locale.getpreferredencoding().
:param replace_tabs_by_spaces: Enable/Disable replace tabs by spaces.
Default is true.
:param clean_trailing_whitespaces: Enable/Disable clean trailing
whitespaces (on save). Default is True.
:param safe_save: If True, the file is saved to a temporary file first.
If the save went fine, the temporary file is renamed to the final
filename.
:param restore_cursor_position: If true, last cursor position will be
restored. Default is True.
:param preferred_eol: Preferred EOL convention. This setting will be
used for saving the document unless autodetect_eol is True.
:param autodetect_eol: If true, automatically detects file EOL and
use it instead of the preferred EOL when saving files.
:param show_whitespaces: True to show white spaces.
:param kwargs: addtional keyword args to pass to the widget
constructor.
:return: The created code editor | entailment |
def close_document(self, path):
"""
Closes a text document.
:param path: Path of the document to close.
"""
to_close = []
for widget in self.widgets(include_clones=True):
p = os.path.normpath(os.path.normcase(widget.file.path))
path = os.path.normpath(os.path.normcase(path))
if p == path:
to_close.append(widget)
for widget in to_close:
tw = widget.parent_tab_widget
tw.remove_tab(tw.indexOf(widget)) | Closes a text document.
:param path: Path of the document to close. | entailment |
def rename_document(self, old_path, new_path):
"""
Renames an already opened document (this will not rename the file,
just update the file path and tab title).
Use that function to update a file that has been renamed externally.
:param old_path: old path (path of the widget to rename with
``new_path``
:param new_path: new path that will be used to rename the tab.
"""
to_rename = []
title = os.path.split(new_path)[1]
for widget in self.widgets(include_clones=True):
p = os.path.normpath(os.path.normcase(widget.file.path))
old_path = os.path.normpath(os.path.normcase(old_path))
if p == old_path:
to_rename.append(widget)
for widget in to_rename:
tw = widget.parent_tab_widget
widget.file._path = new_path
tw.setTabText(tw.indexOf(widget), title) | Renames an already opened document (this will not rename the file,
just update the file path and tab title).
Use that function to update a file that has been renamed externally.
:param old_path: old path (path of the widget to rename with
``new_path``
:param new_path: new path that will be used to rename the tab. | entailment |
def closeEvent(self, event):
"""
Saves dirty editors on close and cancel the event if the user choosed
to continue to work.
:param event: close event
"""
dirty_widgets = []
for w in self.widgets(include_clones=False):
if w.dirty:
dirty_widgets.append(w)
filenames = []
for w in dirty_widgets:
if os.path.exists(w.file.path):
filenames.append(w.file.path)
else:
filenames.append(w.documentTitle())
if len(filenames) == 0:
self.close_all()
return
dlg = DlgUnsavedFiles(self, files=filenames)
if dlg.exec_() == dlg.Accepted:
if not dlg.discarded:
for item in dlg.listWidget.selectedItems():
filename = item.text()
widget = None
for widget in dirty_widgets:
if widget.file.path == filename or \
widget.documentTitle() == filename:
break
tw = widget.parent_tab_widget
tw.save_widget(widget)
tw.remove_tab(tw.indexOf(widget))
self.close_all()
else:
event.ignore() | Saves dirty editors on close and cancel the event if the user choosed
to continue to work.
:param event: close event | entailment |
def _is_shortcut(self, event):
"""
Checks if the event's key and modifiers make the completion shortcut
(Ctrl+Space)
:param event: QKeyEvent
:return: bool
"""
modifier = (QtCore.Qt.MetaModifier if sys.platform == 'darwin' else
QtCore.Qt.ControlModifier)
valid_modifier = int(event.modifiers() & modifier) == modifier
valid_key = event.key() == self._trigger_key
return valid_key and valid_modifier | Checks if the event's key and modifiers make the completion shortcut
(Ctrl+Space)
:param event: QKeyEvent
:return: bool | entailment |
def _hide_popup(self):
"""
Hides the completer popup
"""
debug('hide popup')
if (self._completer.popup() is not None and
self._completer.popup().isVisible()):
self._completer.popup().hide()
self._last_cursor_column = -1
self._last_cursor_line = -1
QtWidgets.QToolTip.hideText() | Hides the completer popup | entailment |
def _show_popup(self, index=0):
"""
Shows the popup at the specified index.
:param index: index
:return:
"""
full_prefix = self._helper.word_under_cursor(
select_whole_word=False).selectedText()
if self._case_sensitive:
self._completer.setCaseSensitivity(QtCore.Qt.CaseSensitive)
else:
self._completer.setCaseSensitivity(QtCore.Qt.CaseInsensitive)
# set prefix
self._completer.setCompletionPrefix(self.completion_prefix)
cnt = self._completer.completionCount()
selected = self._completer.currentCompletion()
if (full_prefix == selected) and cnt == 1:
debug('user already typed the only completion that we '
'have')
self._hide_popup()
else:
# show the completion list
if self.editor.isVisible():
if self._completer.widget() != self.editor:
self._completer.setWidget(self.editor)
self._completer.complete(self._get_popup_rect())
self._completer.popup().setCurrentIndex(
self._completer.completionModel().index(index, 0))
debug(
"popup shown: %r" % self._completer.popup().isVisible())
else:
debug('cannot show popup, editor is not visible') | Shows the popup at the specified index.
:param index: index
:return: | entailment |
def _update_model(self, completions):
"""
Creates a QStandardModel that holds the suggestion from the completion
models for the QCompleter
:param completionPrefix:
"""
# build the completion model
cc_model = QtGui.QStandardItemModel()
self._tooltips.clear()
for completion in completions:
name = completion['name']
item = QtGui.QStandardItem()
item.setData(name, QtCore.Qt.DisplayRole)
if 'tooltip' in completion and completion['tooltip']:
self._tooltips[name] = completion['tooltip']
if 'icon' in completion:
icon = completion['icon']
if isinstance(icon, list):
icon = QtGui.QIcon.fromTheme(icon[0], QtGui.QIcon(icon[1]))
else:
icon = QtGui.QIcon(icon)
item.setData(QtGui.QIcon(icon),
QtCore.Qt.DecorationRole)
cc_model.appendRow(item)
try:
self._completer.setModel(cc_model)
except RuntimeError:
self._create_completer()
self._completer.setModel(cc_model)
return cc_model | Creates a QStandardModel that holds the suggestion from the completion
models for the QCompleter
:param completionPrefix: | entailment |
def create(client, _type, **kwargs):
"""Create a suds object of the requested _type."""
obj = client.factory.create("ns0:%s" % _type)
for key, value in kwargs.items():
setattr(obj, key, value)
return obj | Create a suds object of the requested _type. | entailment |
def invoke(client, method, **kwargs):
"""Invoke a method on the underlying soap service."""
try:
# Proxy the method to the suds service
result = getattr(client.service, method)(**kwargs)
except AttributeError:
logger.critical("Unknown method: %s", method)
raise
except URLError as e:
logger.debug(pprint(e))
logger.debug("A URL related error occurred while invoking the '%s' "
"method on the VIM server, this can be caused by "
"name resolution or connection problems.", method)
logger.debug("The underlying error is: %s", e.reason[1])
raise
except suds.client.TransportError as e:
logger.debug(pprint(e))
logger.debug("TransportError: %s", e)
except suds.WebFault as e:
# Get the type of fault
logger.critical("SUDS Fault: %s" % e.fault.faultstring)
if len(e.fault.faultstring) > 0:
raise
detail = e.document.childAtPath("/Envelope/Body/Fault/detail")
fault_type = detail.getChildren()[0].name
fault = create(fault_type)
if isinstance(e.fault.detail[0], list):
for attr in e.fault.detail[0]:
setattr(fault, attr[0], attr[1])
else:
fault["text"] = e.fault.detail[0]
raise VimFault(fault)
return result | Invoke a method on the underlying soap service. | entailment |
def prettydate(date):
now = datetime.now(timezone.utc)
"""
Return the relative timeframe between the given date and now.
e.g. 'Just now', 'x days ago', 'x hours ago', ...
When the difference is greater than 7 days, the timestamp will be returned
instead.
"""
diff = now - date
# Show the timestamp rather than the relative timeframe when the difference
# is greater than 7 days
if diff.days > 7:
return date.strftime("%d. %b %Y")
return arrow.get(date).humanize() | Return the relative timeframe between the given date and now.
e.g. 'Just now', 'x days ago', 'x hours ago', ...
When the difference is greater than 7 days, the timestamp will be returned
instead. | entailment |
def discovery(self, compute_resource):
"""An example that discovers hosts and VMs in the inventory."""
# Find the first ClusterComputeResource
if compute_resource is None:
cr_list = ComputeResource.all(self.client)
print("ERROR: You must specify a ComputeResource.")
print("Available ComputeResource's:")
for cr in cr_list:
print(cr.name)
sys.exit(1)
try:
ccr = ComputeResource.get(self.client, name=compute_resource)
except ObjectNotFoundError:
print("ERROR: Could not find ComputeResource with name %s" %
compute_resource)
sys.exit(1)
print('Cluster: %s (%s hosts)' % (ccr.name, len(ccr.host)))
ccr.preload("host", properties=["name", "vm"])
for host in ccr.host:
print(' Host: %s (%s VMs)' % (host.name, len(host.vm)))
# Get the vm views in one fell swoop
host.preload("vm", properties=["name"])
for vm in host.vm:
print(' VM: %s' % vm.name) | An example that discovers hosts and VMs in the inventory. | entailment |
def _get_app_auth_headers(self):
"""Set the correct auth headers to authenticate against GitHub."""
now = datetime.now(timezone.utc)
expiry = now + timedelta(minutes=5)
data = {"iat": now, "exp": expiry, "iss": self.app_id}
app_token = jwt.encode(data, self.app_key, algorithm="RS256").decode("utf-8")
headers = {
"Accept": PREVIEW_JSON_ACCEPT,
"Authorization": "Bearer {}".format(app_token),
}
return headers | Set the correct auth headers to authenticate against GitHub. | entailment |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.